diff --git a/.github/workflows/build-alpine-linux.yml b/.github/workflows/build-alpine-linux.yml index c356a8a0f2a..c39962fa07f 100644 --- a/.github/workflows/build-alpine-linux.yml +++ b/.github/workflows/build-alpine-linux.yml @@ -97,6 +97,7 @@ jobs: --with-zlib=system --with-jmod-compress=zip-1 --with-external-symbols-in-bundles=none + --with-native-debug-symbols-level=1 ${{ inputs.extra-conf-options }} ${{ inputs.configure-arguments }} || ( echo "Dumping config.log:" && cat config.log && diff --git a/.github/workflows/build-cross-compile.yml b/.github/workflows/build-cross-compile.yml index c2ed63aa439..a0642d469aa 100644 --- a/.github/workflows/build-cross-compile.yml +++ b/.github/workflows/build-cross-compile.yml @@ -180,6 +180,7 @@ jobs: --with-sysroot=sysroot --with-jmod-compress=zip-1 --with-external-symbols-in-bundles=none + --with-native-debug-symbols-level=1 CC=${{ matrix.gnu-arch }}-linux-gnu${{ matrix.gnu-abi}}-gcc-${{ inputs.gcc-major-version }} CXX=${{ matrix.gnu-arch }}-linux-gnu${{ matrix.gnu-abi}}-g++-${{ inputs.gcc-major-version }} ${{ inputs.extra-conf-options }} ${{ inputs.configure-arguments }} || ( diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index a668cb5a0f9..791b53a3f04 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -144,6 +144,7 @@ jobs: --with-zlib=system --with-jmod-compress=zip-1 --with-external-symbols-in-bundles=none + --with-native-debug-symbols-level=1 ${{ inputs.extra-conf-options }} ${{ inputs.configure-arguments }} || ( echo "Dumping config.log:" && cat config.log && diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index 4535d0dd760..484e616fad7 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -111,6 +111,7 @@ jobs: --with-zlib=system --with-jmod-compress=zip-1 --with-external-symbols-in-bundles=none + --with-native-debug-symbols-level=1 ${{ inputs.extra-conf-options }} ${{ inputs.configure-arguments }} || ( echo "Dumping config.log:" && cat config.log && diff --git a/make/autoconf/flags-cflags.m4 b/make/autoconf/flags-cflags.m4 index 6298bcae416..5a9fdc57c74 100644 --- a/make/autoconf/flags-cflags.m4 +++ b/make/autoconf/flags-cflags.m4 @@ -69,6 +69,23 @@ AC_DEFUN([FLAGS_SETUP_DEBUG_SYMBOLS], # Debug prefix mapping if supported by compiler DEBUG_PREFIX_CFLAGS= + UTIL_ARG_WITH(NAME: native-debug-symbols-level, TYPE: string, + DEFAULT: "", + RESULT: DEBUG_SYMBOLS_LEVEL, + DESC: [set the native debug symbol level (GCC and Clang only)], + DEFAULT_DESC: [toolchain default]) + AC_SUBST(DEBUG_SYMBOLS_LEVEL) + + if test "x${TOOLCHAIN_TYPE}" = xgcc || \ + test "x${TOOLCHAIN_TYPE}" = xclang; then + DEBUG_SYMBOLS_LEVEL_FLAGS="-g" + if test "x${DEBUG_SYMBOLS_LEVEL}" != "x"; then + DEBUG_SYMBOLS_LEVEL_FLAGS="-g${DEBUG_SYMBOLS_LEVEL}" + FLAGS_COMPILER_CHECK_ARGUMENTS(ARGUMENT: [${DEBUG_SYMBOLS_LEVEL_FLAGS}], + IF_FALSE: AC_MSG_ERROR("Debug info level ${DEBUG_SYMBOLS_LEVEL} is not supported")) + fi + fi + # Debug symbols if test "x$TOOLCHAIN_TYPE" = xgcc; then if test "x$ALLOW_ABSOLUTE_PATHS_IN_OUTPUT" = "xfalse"; then @@ -93,8 +110,9 @@ AC_DEFUN([FLAGS_SETUP_DEBUG_SYMBOLS], ) fi - CFLAGS_DEBUG_SYMBOLS="-g -gdwarf-4" - ASFLAGS_DEBUG_SYMBOLS="-g" + # Debug info level should follow the debug format to be effective. + CFLAGS_DEBUG_SYMBOLS="-gdwarf-4 ${DEBUG_SYMBOLS_LEVEL_FLAGS}" + ASFLAGS_DEBUG_SYMBOLS="${DEBUG_SYMBOLS_LEVEL_FLAGS}" elif test "x$TOOLCHAIN_TYPE" = xclang; then if test "x$ALLOW_ABSOLUTE_PATHS_IN_OUTPUT" = "xfalse"; then # Check if compiler supports -fdebug-prefix-map. If so, use that to make @@ -113,8 +131,9 @@ AC_DEFUN([FLAGS_SETUP_DEBUG_SYMBOLS], FLAGS_COMPILER_CHECK_ARGUMENTS(ARGUMENT: [${GDWARF_FLAGS}], IF_FALSE: [GDWARF_FLAGS=""]) - CFLAGS_DEBUG_SYMBOLS="-g ${GDWARF_FLAGS}" - ASFLAGS_DEBUG_SYMBOLS="-g" + # Debug info level should follow the debug format to be effective. + CFLAGS_DEBUG_SYMBOLS="${GDWARF_FLAGS} ${DEBUG_SYMBOLS_LEVEL_FLAGS}" + ASFLAGS_DEBUG_SYMBOLS="${DEBUG_SYMBOLS_LEVEL_FLAGS}" elif test "x$TOOLCHAIN_TYPE" = xmicrosoft; then CFLAGS_DEBUG_SYMBOLS="-Z7" fi diff --git a/make/common/Utils.gmk b/make/common/Utils.gmk index c0ebabca3f7..b4bb949d3ee 100644 --- a/make/common/Utils.gmk +++ b/make/common/Utils.gmk @@ -114,7 +114,7 @@ EscapeDollar = $(subst $$,\$$,$(subst \$$,$$,$(strip $1))) ################################################################################ # This macro works just like EscapeDollar above, but for #. -EscapeHash = $(subst \#,\\\#,$(subst \\\#,\#,$(strip $1))) +EscapeHash = $(subst $(HASH),\$(HASH),$(subst \$(HASH),$(HASH),$(strip $1))) ################################################################################ # This macro translates $ into $$ to protect the string from make itself. diff --git a/make/langtools/tools/propertiesparser/gen/ClassGenerator.java b/make/langtools/tools/propertiesparser/gen/ClassGenerator.java index 247537b4676..14e8c4fb00a 100644 --- a/make/langtools/tools/propertiesparser/gen/ClassGenerator.java +++ b/make/langtools/tools/propertiesparser/gen/ClassGenerator.java @@ -286,7 +286,7 @@ public class ClassGenerator { diagnosticFlags.isEmpty() ? StubKind.DIAGNOSTIC_FLAGS_EMPTY.format() : StubKind.DIAGNOSTIC_FLAGS_NON_EMPTY.format(diagnosticFlags), - StubKind.LINT_CATEGORY.format("\"" + lintCategory + "\""), + StubKind.LINT_CATEGORY.format(toLintFieldName(lintCategory)), "\"" + keyParts[0] + "\"", "\"" + Stream.of(keyParts).skip(2).collect(Collectors.joining(".")) + "\"", javadoc); @@ -314,7 +314,7 @@ public class ClassGenerator { diagnosticFlags.isEmpty() ? StubKind.DIAGNOSTIC_FLAGS_EMPTY.format() : StubKind.DIAGNOSTIC_FLAGS_NON_EMPTY.format(diagnosticFlags), - StubKind.LINT_CATEGORY.format("\"" + lintCategory + "\""), + StubKind.LINT_CATEGORY.format(toLintFieldName(lintCategory)), "\"" + keyParts[0] + "\"", "\"" + Stream.of(keyParts).skip(2).collect(Collectors.joining(".")) + "\"", argNames.stream().collect(Collectors.joining(", "))); @@ -329,6 +329,11 @@ public class ClassGenerator { } } + String toLintFieldName(String lintCategory) { + return lintCategory.toUpperCase() + .replaceAll("-", "_"); + } + /** * Form the name of a factory method/field given a resource key. */ diff --git a/make/langtools/tools/propertiesparser/resources/templates.properties b/make/langtools/tools/propertiesparser/resources/templates.properties index 81a9be2552c..f8ff07a878f 100644 --- a/make/langtools/tools/propertiesparser/resources/templates.properties +++ b/make/langtools/tools/propertiesparser/resources/templates.properties @@ -87,7 +87,7 @@ suppress.warnings=\ @SuppressWarnings("rawtypes")\n lint.category=\ - LintCategory.get({0}).get() + LintCategory.{0} diagnostic.flags.empty=\ EnumSet.noneOf(DiagnosticFlag.class) diff --git a/src/hotspot/cpu/aarch64/immediate_aarch64.cpp b/src/hotspot/cpu/aarch64/immediate_aarch64.cpp index 710a1f0677d..eb4cb23100c 100644 --- a/src/hotspot/cpu/aarch64/immediate_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/immediate_aarch64.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, 2020, Red Hat Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -23,13 +23,13 @@ * */ -#include // do not reorder -#include // do not reorder - +#include "cppstdlib/cstdlib.hpp" #include "immediate_aarch64.hpp" #include "metaprogramming/primitiveConversions.hpp" #include "utilities/globalDefinitions.hpp" +#include + // there are at most 2^13 possible logical immediate encodings // however, some combinations of immr and imms are invalid static const unsigned LI_TABLE_SIZE = (1 << 13); diff --git a/src/hotspot/cpu/aarch64/immediate_aarch64.hpp b/src/hotspot/cpu/aarch64/immediate_aarch64.hpp index 0cbdb562088..fb38995417b 100644 --- a/src/hotspot/cpu/aarch64/immediate_aarch64.hpp +++ b/src/hotspot/cpu/aarch64/immediate_aarch64.hpp @@ -1,4 +1,5 @@ /* + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, Red Hat Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -22,10 +23,10 @@ * */ -#ifndef _IMMEDIATE_H -#define _IMMEDIATE_H +#ifndef CPU_AARCH64_IMMEDIATE_AARCH64_HPP +#define CPU_AARCH64_IMMEDIATE_AARCH64_HPP -#include +#include /* * functions to map backwards and forwards between logical or floating @@ -51,4 +52,4 @@ uint32_t encoding_for_logical_immediate(uint64_t immediate); uint64_t fp_immediate_for_encoding(uint32_t imm8, int is_dp); uint32_t encoding_for_fp_immediate(float immediate); -#endif // _IMMEDIATE_H +#endif // CPU_AARCH64_IMMEDIATE_AARCH64_HPP diff --git a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp index 2ccc755be3c..b8a9afc123f 100644 --- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp @@ -6259,14 +6259,10 @@ void MacroAssembler::fill_words(Register base, Register cnt, Register value) // Intrinsic for // -// - sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len) -// Encodes char[] to byte[] in ISO-8859-1 -// -// - java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len) -// Encodes byte[] (containing UTF-16) to byte[] in ISO-8859-1 -// -// - java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len) -// Encodes char[] to byte[] in ASCII +// - sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray +// return the number of characters copied. +// - java/lang/StringUTF16.compress +// return index of non-latin1 character if copy fails, otherwise 'len'. // // This version always returns the number of characters copied, and does not // clobber the 'len' register. A successful copy will complete with the post- diff --git a/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp b/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp index dcf20752a21..824ea872935 100644 --- a/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp @@ -2813,14 +2813,10 @@ void C2_MacroAssembler::char_array_compress_v(Register src, Register dst, Regist // Intrinsic for // -// - sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len) -// Encodes char[] to byte[] in ISO-8859-1 -// -// - java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len) -// Encodes byte[] (containing UTF-16) to byte[] in ISO-8859-1 -// -// - java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len) -// Encodes char[] to byte[] in ASCII +// - sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray +// return the number of characters copied. +// - java/lang/StringUTF16.compress +// return index of non-latin1 character if copy fails, otherwise 'len'. // // This version always returns the number of characters copied. A successful // copy will complete with the post-condition: 'res' == 'len', while an diff --git a/src/hotspot/cpu/riscv/riscv_v.ad b/src/hotspot/cpu/riscv/riscv_v.ad index d162280106a..aeb8398f06f 100644 --- a/src/hotspot/cpu/riscv/riscv_v.ad +++ b/src/hotspot/cpu/riscv/riscv_v.ad @@ -114,12 +114,12 @@ source %{ case Op_VectorCastHF2F: case Op_VectorCastF2HF: case Op_AddVHF: + case Op_SubVHF: + case Op_MulVHF: case Op_DivVHF: case Op_MaxVHF: case Op_MinVHF: - case Op_MulVHF: case Op_SqrtVHF: - case Op_SubVHF: return UseZvfh; case Op_FmaVHF: return UseZvfh && UseFMA; @@ -147,13 +147,28 @@ source %{ if (!UseRVV) { return false; } + switch (opcode) { case Op_SelectFromTwoVector: // There is no masked version of selectFrom two vector, i.e. selectFrom(av, bv, mask) in vector API. return false; + // Currently, the masked versions of the following 8 Float16 operations are disabled. + // When the support for Float16 vector classes is added in VectorAPI and the masked + // Float16 IR can be generated, these masked operations will be enabled and relevant + // backend support added. + case Op_AddVHF: + case Op_SubVHF: + case Op_MulVHF: + case Op_DivVHF: + case Op_MaxVHF: + case Op_MinVHF: + case Op_SqrtVHF: + case Op_FmaVHF: + return false; default: break; } + return match_rule_supported_vector(opcode, vlen, bt); } diff --git a/src/hotspot/cpu/x86/macroAssembler_x86.cpp b/src/hotspot/cpu/x86/macroAssembler_x86.cpp index 3f18d8c6262..be7deb884ce 100644 --- a/src/hotspot/cpu/x86/macroAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/macroAssembler_x86.cpp @@ -6251,46 +6251,32 @@ void MacroAssembler::evpbroadcast(BasicType type, XMMRegister dst, Register src, } } -// Encode given char[]/byte[] to byte[] in ISO_8859_1 or ASCII -// -// @IntrinsicCandidate -// int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0( -// char[] sa, int sp, byte[] da, int dp, int len) { -// int i = 0; -// for (; i < len; i++) { -// char c = sa[sp++]; -// if (c > '\u00FF') -// break; -// da[dp++] = (byte) c; -// } -// return i; -// } -// -// @IntrinsicCandidate -// int java.lang.StringCoding.encodeISOArray0( -// byte[] sa, int sp, byte[] da, int dp, int len) { -// int i = 0; -// for (; i < len; i++) { -// char c = StringUTF16.getChar(sa, sp++); -// if (c > '\u00FF') -// break; -// da[dp++] = (byte) c; -// } -// return i; -// } -// -// @IntrinsicCandidate -// int java.lang.StringCoding.encodeAsciiArray0( -// char[] sa, int sp, byte[] da, int dp, int len) { -// int i = 0; -// for (; i < len; i++) { -// char c = sa[sp++]; -// if (c >= '\u0080') -// break; -// da[dp++] = (byte) c; -// } -// return i; -// } +// encode char[] to byte[] in ISO_8859_1 or ASCII + //@IntrinsicCandidate + //private static int implEncodeISOArray(byte[] sa, int sp, + //byte[] da, int dp, int len) { + // int i = 0; + // for (; i < len; i++) { + // char c = StringUTF16.getChar(sa, sp++); + // if (c > '\u00FF') + // break; + // da[dp++] = (byte)c; + // } + // return i; + //} + // + //@IntrinsicCandidate + //private static int implEncodeAsciiArray(char[] sa, int sp, + // byte[] da, int dp, int len) { + // int i = 0; + // for (; i < len; i++) { + // char c = sa[sp++]; + // if (c >= '\u0080') + // break; + // da[dp++] = (byte)c; + // } + // return i; + //} void MacroAssembler::encode_iso_array(Register src, Register dst, Register len, XMMRegister tmp1Reg, XMMRegister tmp2Reg, XMMRegister tmp3Reg, XMMRegister tmp4Reg, diff --git a/src/hotspot/cpu/x86/x86.ad b/src/hotspot/cpu/x86/x86.ad index 5958db5d1eb..93b306c37d6 100644 --- a/src/hotspot/cpu/x86/x86.ad +++ b/src/hotspot/cpu/x86/x86.ad @@ -1,5 +1,5 @@ // -// Copyright (c) 2011, 2025, Oracle and/or its affiliates. All rights reserved. +// Copyright (c) 2011, 2026, 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 @@ -2633,17 +2633,19 @@ bool Matcher::supports_vector_calling_convention(void) { return EnableVectorSupport; } +static bool is_ndd_demotable_opr1(const MachNode* mdef) { + return ((mdef->flags() & Node::PD::Flag_ndd_demotable_opr1) != 0); +} + +static bool is_ndd_demotable_opr2(const MachNode* mdef) { + return ((mdef->flags() & Node::PD::Flag_ndd_demotable_opr2) != 0); +} + +#ifdef ASSERT static bool is_ndd_demotable(const MachNode* mdef) { - return ((mdef->flags() & Node::PD::Flag_ndd_demotable) != 0); -} - -static bool is_ndd_demotable_commutative(const MachNode* mdef) { - return ((mdef->flags() & Node::PD::Flag_ndd_demotable_commutative) != 0); -} - -static bool is_demotion_candidate(const MachNode* mdef) { - return (is_ndd_demotable(mdef) || is_ndd_demotable_commutative(mdef)); + return (is_ndd_demotable_opr1(mdef) || is_ndd_demotable_opr2(mdef)); } +#endif bool Matcher::is_register_biasing_candidate(const MachNode* mdef, int oper_index) { @@ -2653,8 +2655,8 @@ bool Matcher::is_register_biasing_candidate(const MachNode* mdef, if (mdef->num_opnds() <= oper_index || mdef->operand_index(oper_index) < 0 || mdef->in(mdef->operand_index(oper_index)) == nullptr) { - assert(oper_index != 1 || !is_demotion_candidate(mdef), "%s", mdef->Name()); - assert(oper_index != 2 || !is_ndd_demotable_commutative(mdef), "%s", mdef->Name()); + assert(oper_index != 1 || !is_ndd_demotable_opr1(mdef), "%s", mdef->Name()); + assert(oper_index != 2 || !is_ndd_demotable_opr2(mdef), "%s", mdef->Name()); return false; } @@ -2662,14 +2664,13 @@ bool Matcher::is_register_biasing_candidate(const MachNode* mdef, // address computation. Biasing def towards any address component will not // result in NDD demotion by assembler. if (mdef->operand_num_edges(oper_index) != 1) { - assert(!is_ndd_demotable(mdef), "%s", mdef->Name()); return false; } // Demotion candidate must be register mask compatible with definition. const RegMask& oper_mask = mdef->in_RegMask(mdef->operand_index(oper_index)); if (!oper_mask.overlap(mdef->out_RegMask())) { - assert(!is_demotion_candidate(mdef), "%s", mdef->Name()); + assert(!is_ndd_demotable(mdef), "%s", mdef->Name()); return false; } @@ -2681,12 +2682,12 @@ bool Matcher::is_register_biasing_candidate(const MachNode* mdef, // EVEX prefix with shorter REX/REX2 encoding. Demotion candidates // are decorated with a special flag by instruction selector. case 1: - return is_demotion_candidate(mdef); + return is_ndd_demotable_opr1(mdef); // Definition operand of commutative operation can be biased towards second // operand. case 2: - return is_ndd_demotable_commutative(mdef); + return is_ndd_demotable_opr2(mdef); // Current scheme only selects up to two biasing candidates default: @@ -2888,9 +2889,9 @@ public: Flag_clears_zero_flag = Node::_last_flag << 9, Flag_clears_overflow_flag = Node::_last_flag << 10, Flag_clears_sign_flag = Node::_last_flag << 11, - Flag_ndd_demotable = Node::_last_flag << 12, - Flag_ndd_demotable_commutative = Node::_last_flag << 13, - _last_flag = Flag_ndd_demotable_commutative + Flag_ndd_demotable_opr1 = Node::_last_flag << 12, + Flag_ndd_demotable_opr2 = Node::_last_flag << 13, + _last_flag = Flag_ndd_demotable_opr2 }; }; @@ -9872,7 +9873,7 @@ instruct addI_rReg_ndd(rRegI dst, rRegI src1, rRegI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (AddI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); format %{ "eaddl $dst, $src1, $src2\t# int ndd" %} ins_encode %{ @@ -9900,7 +9901,7 @@ instruct addI_rReg_rReg_imm_ndd(rRegI dst, rRegI src1, immI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (AddI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1); format %{ "eaddl $dst, $src1, $src2\t# int ndd" %} ins_encode %{ @@ -9943,7 +9944,7 @@ instruct addI_rReg_rReg_mem_ndd(rRegI dst, rRegI src1, memory src2, rFlagsReg cr predicate(UseAPX); match(Set dst (AddI src1 (LoadI src2))); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(150); format %{ "eaddl $dst, $src1, $src2\t# int ndd" %} @@ -10000,7 +10001,7 @@ instruct incI_rReg_ndd(rRegI dst, rRegI src, immI_1 val, rFlagsReg cr) predicate(UseAPX && UseIncDec); match(Set dst (AddI src val)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "eincl $dst, $src\t# int ndd" %} ins_encode %{ @@ -10055,7 +10056,7 @@ instruct decI_rReg_ndd(rRegI dst, rRegI src, immI_M1 val, rFlagsReg cr) predicate(UseAPX && UseIncDec); match(Set dst (AddI src val)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "edecl $dst, $src\t# int ndd" %} ins_encode %{ @@ -10162,7 +10163,7 @@ instruct addL_rReg_ndd(rRegL dst, rRegL src1, rRegL src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (AddL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); format %{ "eaddq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -10190,7 +10191,7 @@ instruct addL_rReg_rReg_imm_ndd(rRegL dst, rRegL src1, immL32 src2, rFlagsReg cr predicate(UseAPX); match(Set dst (AddL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1); format %{ "eaddq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -10233,7 +10234,7 @@ instruct addL_rReg_rReg_mem_ndd(rRegL dst, rRegL src1, memory src2, rFlagsReg cr predicate(UseAPX); match(Set dst (AddL src1 (LoadL src2))); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(150); format %{ "eaddq $dst, $src1, $src2\t# long ndd" %} @@ -10289,7 +10290,7 @@ instruct incL_rReg_ndd(rRegL dst, rRegI src, immL1 val, rFlagsReg cr) predicate(UseAPX && UseIncDec); match(Set dst (AddL src val)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "eincq $dst, $src\t# long ndd" %} ins_encode %{ @@ -10344,7 +10345,7 @@ instruct decL_rReg_ndd(rRegL dst, rRegL src, immL_M1 val, rFlagsReg cr) predicate(UseAPX && UseIncDec); match(Set dst (AddL src val)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "edecq $dst, $src\t# long ndd" %} ins_encode %{ @@ -11059,7 +11060,7 @@ instruct subI_rReg_ndd(rRegI dst, rRegI src1, rRegI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (SubI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1); format %{ "esubl $dst, $src1, $src2\t# int ndd" %} ins_encode %{ @@ -11073,7 +11074,7 @@ instruct subI_rReg_rReg_imm_ndd(rRegI dst, rRegI src1, immI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (SubI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1); format %{ "esubl $dst, $src1, $src2\t# int ndd" %} ins_encode %{ @@ -11116,7 +11117,7 @@ instruct subI_rReg_rReg_mem_ndd(rRegI dst, rRegI src1, memory src2, rFlagsReg cr predicate(UseAPX); match(Set dst (SubI src1 (LoadI src2))); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1); ins_cost(150); format %{ "esubl $dst, $src1, $src2\t# int ndd" %} @@ -11174,7 +11175,7 @@ instruct subL_rReg_ndd(rRegL dst, rRegL src1, rRegL src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (SubL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1); format %{ "esubq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -11188,7 +11189,7 @@ instruct subL_rReg_rReg_imm_ndd(rRegL dst, rRegL src1, immL32 src2, rFlagsReg cr predicate(UseAPX); match(Set dst (SubL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1); format %{ "esubq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -11231,7 +11232,7 @@ instruct subL_rReg_rReg_mem_ndd(rRegL dst, rRegL src1, memory src2, rFlagsReg cr predicate(UseAPX); match(Set dst (SubL src1 (LoadL src2))); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_carry_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1); ins_cost(150); format %{ "esubq $dst, $src1, $src2\t# long ndd" %} @@ -11303,7 +11304,7 @@ instruct negI_rReg_ndd(rRegI dst, rRegI src, immI_0 zero, rFlagsReg cr) predicate(UseAPX); match(Set dst (SubI zero src)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr2); format %{ "enegl $dst, $src\t# int ndd" %} ins_encode %{ @@ -11331,7 +11332,7 @@ instruct negI_rReg_2_ndd(rRegI dst, rRegI src, rFlagsReg cr) predicate(UseAPX); match(Set dst (NegI src)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1); format %{ "enegl $dst, $src\t# int ndd" %} ins_encode %{ @@ -11372,7 +11373,7 @@ instruct negL_rReg_ndd(rRegL dst, rRegL src, immL0 zero, rFlagsReg cr) predicate(UseAPX); match(Set dst (SubL zero src)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr2); format %{ "enegq $dst, $src\t# long ndd" %} ins_encode %{ @@ -11400,7 +11401,7 @@ instruct negL_rReg_2_ndd(rRegL dst, rRegL src, rFlagsReg cr) predicate(UseAPX); match(Set dst (NegL src)); effect(KILL cr); - flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_overflow_flag, PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_ndd_demotable_opr1); format %{ "enegq $dst, $src\t# long ndd" %} ins_encode %{ @@ -11445,7 +11446,7 @@ instruct mulI_rReg_ndd(rRegI dst, rRegI src1, rRegI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (MulI src1 src2)); effect(KILL cr); - flag(PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(300); format %{ "eimull $dst, $src1, $src2\t# int ndd" %} @@ -11487,7 +11488,7 @@ instruct mulI_rReg_rReg_mem_ndd(rRegI dst, rRegI src1, memory src2, rFlagsReg cr predicate(UseAPX); match(Set dst (MulI src1 (LoadI src2))); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(350); format %{ "eimull $dst, $src1, $src2\t# int ndd" %} @@ -11539,7 +11540,7 @@ instruct mulL_rReg_ndd(rRegL dst, rRegL src1, rRegL src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (MulL src1 src2)); effect(KILL cr); - flag(PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(300); format %{ "eimulq $dst, $src1, $src2\t# long ndd" %} @@ -11581,7 +11582,7 @@ instruct mulL_rReg_rReg_mem_ndd(rRegL dst, rRegL src1, memory src2, rFlagsReg cr predicate(UseAPX); match(Set dst (MulL src1 (LoadL src2))); effect(KILL cr); - flag(PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(350); format %{ "eimulq $dst, $src1, $src2 \t# long" %} @@ -11856,7 +11857,7 @@ instruct salI_rReg_immI2_ndd(rRegI dst, rRegI src, immI2 shift, rFlagsReg cr) predicate(UseAPX); match(Set dst (LShiftI src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "esall $dst, $src, $shift\t# int(ndd)" %} ins_encode %{ @@ -11885,7 +11886,7 @@ instruct salI_rReg_imm_ndd(rRegI dst, rRegI src, immI8 shift, rFlagsReg cr) predicate(UseAPX); match(Set dst (LShiftI src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "esall $dst, $src, $shift\t# int (ndd)" %} ins_encode %{ @@ -11992,7 +11993,7 @@ instruct sarI_rReg_imm_ndd(rRegI dst, rRegI src, immI8 shift, rFlagsReg cr) predicate(UseAPX); match(Set dst (RShiftI src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "esarl $dst, $src, $shift\t# int (ndd)" %} ins_encode %{ @@ -12099,7 +12100,7 @@ instruct shrI_rReg_imm_ndd(rRegI dst, rRegI src, immI8 shift, rFlagsReg cr) predicate(UseAPX); match(Set dst (URShiftI src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "eshrl $dst, $src, $shift\t # int (ndd)" %} ins_encode %{ @@ -12207,7 +12208,7 @@ instruct salL_rReg_immI2_ndd(rRegL dst, rRegL src, immI2 shift, rFlagsReg cr) predicate(UseAPX); match(Set dst (LShiftL src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "esalq $dst, $src, $shift\t# long (ndd)" %} ins_encode %{ @@ -12236,7 +12237,7 @@ instruct salL_rReg_imm_ndd(rRegL dst, rRegL src, immI8 shift, rFlagsReg cr) predicate(UseAPX); match(Set dst (LShiftL src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "esalq $dst, $src, $shift\t# long (ndd)" %} ins_encode %{ @@ -12343,7 +12344,7 @@ instruct sarL_rReg_imm_ndd(rRegL dst, rRegL src, immI shift, rFlagsReg cr) predicate(UseAPX); match(Set dst (RShiftL src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "esarq $dst, $src, $shift\t# long (ndd)" %} ins_encode %{ @@ -12450,7 +12451,7 @@ instruct shrL_rReg_imm_ndd(rRegL dst, rRegL src, immI8 shift, rFlagsReg cr) predicate(UseAPX); match(Set dst (URShiftL src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "eshrq $dst, $src, $shift\t# long (ndd)" %} ins_encode %{ @@ -12622,7 +12623,7 @@ instruct rolI_rReg_Var_ndd(rRegI dst, rRegI src, rcx_RegI shift, rFlagsReg cr) predicate(UseAPX && n->bottom_type()->basic_type() == T_INT); match(Set dst (RotateLeft src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "eroll $dst, $src, $shift\t# rotate left (int ndd)" %} ins_encode %{ @@ -12687,7 +12688,7 @@ instruct rorI_rReg_Var_ndd(rRegI dst, rRegI src, rcx_RegI shift, rFlagsReg cr) predicate(UseAPX && n->bottom_type()->basic_type() == T_INT); match(Set dst (RotateRight src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "erorl $dst, $src, $shift\t# rotate right(int ndd)" %} ins_encode %{ @@ -12754,7 +12755,7 @@ instruct rolL_rReg_Var_ndd(rRegL dst, rRegL src, rcx_RegI shift, rFlagsReg cr) predicate(UseAPX && n->bottom_type()->basic_type() == T_LONG); match(Set dst (RotateLeft src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "erolq $dst, $src, $shift\t# rotate left(long ndd)" %} ins_encode %{ @@ -12819,7 +12820,7 @@ instruct rorL_rReg_Var_ndd(rRegL dst, rRegL src, rcx_RegI shift, rFlagsReg cr) predicate(UseAPX && n->bottom_type()->basic_type() == T_LONG); match(Set dst (RotateRight src shift)); effect(KILL cr); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "erorq $dst, $src, $shift\t# rotate right(long ndd)" %} ins_encode %{ @@ -12897,7 +12898,7 @@ instruct andI_rReg_ndd(rRegI dst, rRegI src1, rRegI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (AndI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); format %{ "eandl $dst, $src1, $src2\t# int ndd" %} ins_encode %{ @@ -12990,7 +12991,7 @@ instruct andI_rReg_rReg_imm_ndd(rRegI dst, rRegI src1, immI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (AndI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); format %{ "eandl $dst, $src1, $src2\t# int ndd" %} ins_encode %{ @@ -13034,7 +13035,7 @@ instruct andI_rReg_rReg_mem_ndd(rRegI dst, rRegI src1, memory src2, rFlagsReg cr predicate(UseAPX); match(Set dst (AndI src1 (LoadI src2))); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(150); format %{ "eandl $dst, $src1, $src2\t# int ndd" %} @@ -13234,7 +13235,7 @@ instruct orI_rReg_ndd(rRegI dst, rRegI src1, rRegI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (OrI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); format %{ "eorl $dst, $src1, $src2\t# int ndd" %} ins_encode %{ @@ -13263,7 +13264,7 @@ instruct orI_rReg_rReg_imm_ndd(rRegI dst, rRegI src1, immI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (OrI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); format %{ "eorl $dst, $src1, $src2\t# int ndd" %} ins_encode %{ @@ -13277,7 +13278,7 @@ instruct orI_rReg_imm_rReg_ndd(rRegI dst, immI src1, rRegI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (OrI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); format %{ "eorl $dst, $src2, $src1\t# int ndd" %} ins_encode %{ @@ -13321,7 +13322,7 @@ instruct orI_rReg_rReg_mem_ndd(rRegI dst, rRegI src1, memory src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (OrI src1 (LoadI src2))); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(150); format %{ "eorl $dst, $src1, $src2\t# int ndd" %} @@ -13397,7 +13398,7 @@ instruct xorI_rReg_ndd(rRegI dst, rRegI src1, rRegI src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (XorI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); format %{ "exorl $dst, $src1, $src2\t# int ndd" %} ins_encode %{ @@ -13423,7 +13424,7 @@ instruct xorI_rReg_im1_ndd(rRegI dst, rRegI src, immI_M1 imm) %{ match(Set dst (XorI src imm)); predicate(UseAPX); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "enotl $dst, $src" %} ins_encode %{ @@ -13454,7 +13455,7 @@ instruct xorI_rReg_rReg_imm_ndd(rRegI dst, rRegI src1, immI src2, rFlagsReg cr) predicate(UseAPX && n->in(2)->bottom_type()->is_int()->get_con() != -1); match(Set dst (XorI src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); format %{ "exorl $dst, $src1, $src2\t# int ndd" %} ins_encode %{ @@ -13500,7 +13501,7 @@ instruct xorI_rReg_rReg_mem_ndd(rRegI dst, rRegI src1, memory src2, rFlagsReg cr predicate(UseAPX); match(Set dst (XorI src1 (LoadI src2))); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(150); format %{ "exorl $dst, $src1, $src2\t# int ndd" %} @@ -13579,7 +13580,7 @@ instruct andL_rReg_ndd(rRegL dst, rRegL src1, rRegL src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (AndL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); format %{ "eandq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -13635,7 +13636,7 @@ instruct andL_rReg_rReg_imm_ndd(rRegL dst, rRegL src1, immL32 src2, rFlagsReg cr predicate(UseAPX); match(Set dst (AndL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); format %{ "eandq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -13679,7 +13680,7 @@ instruct andL_rReg_rReg_mem_ndd(rRegL dst, rRegL src1, memory src2, rFlagsReg cr predicate(UseAPX); match(Set dst (AndL src1 (LoadL src2))); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(150); format %{ "eandq $dst, $src1, $src2\t# long ndd" %} @@ -13882,7 +13883,7 @@ instruct orL_rReg_ndd(rRegL dst, rRegL src1, rRegL src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (OrL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); format %{ "eorq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -13937,7 +13938,7 @@ instruct orL_rReg_rReg_imm_ndd(rRegL dst, rRegL src1, immL32 src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (OrL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); format %{ "eorq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -13951,7 +13952,7 @@ instruct orL_rReg_imm_rReg_ndd(rRegL dst, immL32 src1, rRegL src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (OrL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); format %{ "eorq $dst, $src2, $src1\t# long ndd" %} ins_encode %{ @@ -13996,7 +13997,7 @@ instruct orL_rReg_rReg_mem_ndd(rRegL dst, rRegL src1, memory src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (OrL src1 (LoadL src2))); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(150); format %{ "eorq $dst, $src1, $src2\t# long ndd" %} @@ -14075,7 +14076,7 @@ instruct xorL_rReg_ndd(rRegL dst, rRegL src1, rRegL src2, rFlagsReg cr) predicate(UseAPX); match(Set dst (XorL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); format %{ "exorq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -14101,7 +14102,7 @@ instruct xorL_rReg_im1_ndd(rRegL dst,rRegL src, immL_M1 imm) %{ predicate(UseAPX); match(Set dst (XorL src imm)); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); format %{ "enotq $dst, $src" %} ins_encode %{ @@ -14132,7 +14133,7 @@ instruct xorL_rReg_rReg_imm(rRegL dst, rRegL src1, immL32 src2, rFlagsReg cr) predicate(UseAPX && n->in(2)->bottom_type()->is_long()->get_con() != -1L); match(Set dst (XorL src1 src2)); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1); format %{ "exorq $dst, $src1, $src2\t# long ndd" %} ins_encode %{ @@ -14178,7 +14179,7 @@ instruct xorL_rReg_rReg_mem_ndd(rRegL dst, rRegL src1, memory src2, rFlagsReg cr predicate(UseAPX); match(Set dst (XorL src1 (LoadL src2))); effect(KILL cr); - flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_commutative); + flag(PD::Flag_sets_sign_flag, PD::Flag_sets_zero_flag, PD::Flag_sets_parity_flag, PD::Flag_clears_overflow_flag, PD::Flag_clears_carry_flag, PD::Flag_ndd_demotable_opr1, PD::Flag_ndd_demotable_opr2); ins_cost(150); format %{ "exorq $dst, $src1, $src2\t# long ndd" %} @@ -16633,7 +16634,7 @@ instruct minI_rReg_ndd(rRegI dst, rRegI src1, rRegI src2) predicate(UseAPX); match(Set dst (MinI src1 src2)); effect(DEF dst, USE src1, USE src2); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); ins_cost(200); expand %{ @@ -16685,7 +16686,7 @@ instruct maxI_rReg_ndd(rRegI dst, rRegI src1, rRegI src2) predicate(UseAPX); match(Set dst (MaxI src1 src2)); effect(DEF dst, USE src1, USE src2); - flag(PD::Flag_ndd_demotable); + flag(PD::Flag_ndd_demotable_opr1); ins_cost(200); expand %{ diff --git a/src/hotspot/os/aix/libodm_aix.cpp b/src/hotspot/os/aix/libodm_aix.cpp index 035703a1771..38e8067181a 100644 --- a/src/hotspot/os/aix/libodm_aix.cpp +++ b/src/hotspot/os/aix/libodm_aix.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2015, 2019 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -23,15 +23,15 @@ * */ +#include "cppstdlib/cstdlib.hpp" #include "libodm_aix.hpp" #include "misc_aix.hpp" -#include -#include -#include #include "runtime/arguments.hpp" #include "runtime/os.hpp" #include "utilities/permitForbiddenFunctions.hpp" +#include +#include dynamicOdm::dynamicOdm() { const char* libodmname = "/usr/lib/libodm.a(shr_64.o)"; diff --git a/src/hotspot/os/aix/libperfstat_aix.hpp b/src/hotspot/os/aix/libperfstat_aix.hpp index 5a6ddfd8f4d..aff11cfb41f 100644 --- a/src/hotspot/os/aix/libperfstat_aix.hpp +++ b/src/hotspot/os/aix/libperfstat_aix.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2024 SAP SE. All rights reserved. * Copyright (c) 2022, IBM Corp. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -32,8 +32,9 @@ #ifndef OS_AIX_LIBPERFSTAT_AIX_HPP #define OS_AIX_LIBPERFSTAT_AIX_HPP +#include "cppstdlib/cstdlib.hpp" + #include -#include /////////////////////////////////////////////////////////////////////////////////////////////// // These are excerpts from the AIX 7.1 libperfstat.h - diff --git a/src/hotspot/os/aix/os_perf_aix.cpp b/src/hotspot/os/aix/os_perf_aix.cpp index 8444002b871..aa8819d035f 100644 --- a/src/hotspot/os/aix/os_perf_aix.cpp +++ b/src/hotspot/os/aix/os_perf_aix.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2022, 2024, IBM Corp. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -23,6 +23,7 @@ * */ +#include "cppstdlib/cstdlib.hpp" #include "jvm.h" #include "libperfstat_aix.hpp" #include "memory/allocation.inline.hpp" @@ -46,7 +47,6 @@ #include #include #include -#include #include typedef struct { diff --git a/src/hotspot/os/bsd/memMapPrinter_macosx.cpp b/src/hotspot/os/bsd/memMapPrinter_macosx.cpp index a7ddab04d85..6fd08d63e85 100644 --- a/src/hotspot/os/bsd/memMapPrinter_macosx.cpp +++ b/src/hotspot/os/bsd/memMapPrinter_macosx.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023, 2024, Red Hat, Inc. and/or its affiliates. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -25,6 +25,7 @@ #if defined(__APPLE__) +#include "cppstdlib/cstdlib.hpp" #include "nmt/memMapPrinter.hpp" #include "runtime/os.hpp" #include "utilities/align.hpp" @@ -34,7 +35,6 @@ #include #include -#include #include #include diff --git a/src/hotspot/os/linux/os_linux.cpp b/src/hotspot/os/linux/os_linux.cpp index a28f9850495..88e5e9b582a 100644 --- a/src/hotspot/os/linux/os_linux.cpp +++ b/src/hotspot/os/linux/os_linux.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2015, 2024 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -27,6 +27,7 @@ #include "code/vtableStubs.hpp" #include "compiler/compileBroker.hpp" #include "compiler/disassembler.hpp" +#include "cppstdlib/cstdlib.hpp" #include "hugepages.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" @@ -96,7 +97,6 @@ # include # include # include -# include # include # include # include diff --git a/src/hotspot/os/linux/os_perf_linux.cpp b/src/hotspot/os/linux/os_perf_linux.cpp index 5708194521f..9f91f3b4c0d 100644 --- a/src/hotspot/os/linux/os_perf_linux.cpp +++ b/src/hotspot/os/linux/os_perf_linux.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -22,6 +22,7 @@ * */ +#include "cppstdlib/cstdlib.hpp" #include "jvm.h" #include "memory/allocation.inline.hpp" #include "os_linux.inline.hpp" @@ -40,7 +41,6 @@ #include #include #include -#include #include #include #include diff --git a/src/hotspot/os/posix/forbiddenFunctions_posix.hpp b/src/hotspot/os/posix/forbiddenFunctions_posix.hpp index 529cf22078e..1c91e9d2599 100644 --- a/src/hotspot/os/posix/forbiddenFunctions_posix.hpp +++ b/src/hotspot/os/posix/forbiddenFunctions_posix.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2026, 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 @@ -36,15 +36,12 @@ #include #endif +// POSIX puts _exit in . +FORBID_IMPORTED_NORETURN_C_FUNCTION(void _exit(int), /* not noexcept */, "use os::exit") + // If needed, add os::strndup and use that instead. FORBID_C_FUNCTION(char* strndup(const char*, size_t), noexcept, "don't use"); -// These are unimplementable for Windows, and they aren't useful for a -// POSIX implementation of NMT either. -// https://stackoverflow.com/questions/62962839/stdaligned-alloc-missing-from-visual-studio-2019 -FORBID_C_FUNCTION(int posix_memalign(void**, size_t, size_t), noexcept, "don't use"); -FORBID_C_FUNCTION(void* aligned_alloc(size_t, size_t), noexcept, "don't use"); - // realpath with a null second argument mallocs a string for the result. // With a non-null second argument, there is a risk of buffer overrun. PRAGMA_DIAG_PUSH diff --git a/src/hotspot/os/posix/os_posix.cpp b/src/hotspot/os/posix/os_posix.cpp index 07e1920c62d..4cae7d359e4 100644 --- a/src/hotspot/os/posix/os_posix.cpp +++ b/src/hotspot/os/posix/os_posix.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2026, 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,6 +23,7 @@ */ #include "classfile/classLoader.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "jvmtifiles/jvmti.h" diff --git a/src/hotspot/os/posix/permitForbiddenFunctions_posix.hpp b/src/hotspot/os/posix/permitForbiddenFunctions_posix.hpp index 3ff8c383a31..b45cede2e5f 100644 --- a/src/hotspot/os/posix/permitForbiddenFunctions_posix.hpp +++ b/src/hotspot/os/posix/permitForbiddenFunctions_posix.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2026, 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,15 +25,20 @@ #ifndef OS_POSIX_PERMITFORBIDDENFUNCTIONS_POSIX_HPP #define OS_POSIX_PERMITFORBIDDENFUNCTIONS_POSIX_HPP +#include "cppstdlib/cstdlib.hpp" #include "utilities/compilerWarnings.hpp" #include "utilities/globalDefinitions.hpp" +#include + // Provide wrappers for some functions otherwise forbidden from use in HotSpot. // See forbiddenFunctions.hpp for details. namespace permit_forbidden_function { BEGIN_ALLOW_FORBIDDEN_FUNCTIONS +[[noreturn]] inline void _exit(int status) { ::_exit(status); } + // Used by the POSIX implementation of os::realpath. inline char* realpath(const char* path, char* resolved_path) { return ::realpath(path, resolved_path); diff --git a/src/hotspot/os/windows/os_windows.cpp b/src/hotspot/os/windows/os_windows.cpp index 0ac05e8a435..efbd1fe7c68 100644 --- a/src/hotspot/os/windows/os_windows.cpp +++ b/src/hotspot/os/windows/os_windows.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, 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 @@ #include "code/vtableStubs.hpp" #include "compiler/compileBroker.hpp" #include "compiler/disassembler.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "jvmtifiles/jvmti.h" diff --git a/src/hotspot/os/windows/permitForbiddenFunctions_windows.hpp b/src/hotspot/os/windows/permitForbiddenFunctions_windows.hpp index 99e77464fbd..fbd476ceb60 100644 --- a/src/hotspot/os/windows/permitForbiddenFunctions_windows.hpp +++ b/src/hotspot/os/windows/permitForbiddenFunctions_windows.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2026, 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 @@ #ifndef OS_WINDOWS_PERMITFORBIDDENFUNCTIONS_WINDOWS_HPP #define OS_WINDOWS_PERMITFORBIDDENFUNCTIONS_WINDOWS_HPP +#include "cppstdlib/cstdlib.hpp" #include "utilities/compilerWarnings.hpp" #include "utilities/globalDefinitions.hpp" @@ -34,6 +35,8 @@ namespace permit_forbidden_function { BEGIN_ALLOW_FORBIDDEN_FUNCTIONS +[[noreturn]] inline void _exit(int status) { ::_exit(status); } + // Used by the Windows implementation of os::realpath. inline char* _fullpath(char* absPath, const char* relPath, size_t maxLength) { return ::_fullpath(absPath, relPath, maxLength); diff --git a/src/hotspot/os/windows/vmError_windows.cpp b/src/hotspot/os/windows/vmError_windows.cpp index 22df4d82cbf..66df38d2734 100644 --- a/src/hotspot/os/windows/vmError_windows.cpp +++ b/src/hotspot/os/windows/vmError_windows.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, 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,6 +24,7 @@ #include "cds/aotMetaspace.hpp" #include "cds/cdsConfig.hpp" +#include "cppstdlib/cstdlib.hpp" #include "runtime/arguments.hpp" #include "runtime/javaThread.hpp" #include "runtime/os.hpp" diff --git a/src/hotspot/os_cpu/aix_ppc/prefetch_aix_ppc.inline.hpp b/src/hotspot/os_cpu/aix_ppc/prefetch_aix_ppc.inline.hpp index 1f9917acae7..c741335b5f0 100644 --- a/src/hotspot/os_cpu/aix_ppc/prefetch_aix_ppc.inline.hpp +++ b/src/hotspot/os_cpu/aix_ppc/prefetch_aix_ppc.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2013 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,8 +26,7 @@ #ifndef OS_CPU_AIX_PPC_PREFETCH_AIX_PPC_INLINE_HPP #define OS_CPU_AIX_PPC_PREFETCH_AIX_PPC_INLINE_HPP -#include "runtime/prefetch.hpp" - +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read(const void *loc, intx interval) { #if !defined(USE_XLC_BUILTINS) diff --git a/src/hotspot/os_cpu/bsd_aarch64/os_bsd_aarch64.cpp b/src/hotspot/os_cpu/bsd_aarch64/os_bsd_aarch64.cpp index f6e2d39e315..62dba218b2f 100644 --- a/src/hotspot/os_cpu/bsd_aarch64/os_bsd_aarch64.cpp +++ b/src/hotspot/os_cpu/bsd_aarch64/os_bsd_aarch64.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, Red Hat Inc. All rights reserved. * Copyright (c) 2021, Azul Systems, Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -29,6 +29,7 @@ #include "classfile/vmSymbols.hpp" #include "code/codeCache.hpp" #include "code/vtableStubs.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "logging/log.hpp" @@ -63,7 +64,6 @@ # include # include # include -# include # include # include # include diff --git a/src/hotspot/os_cpu/bsd_aarch64/prefetch_bsd_aarch64.inline.hpp b/src/hotspot/os_cpu/bsd_aarch64/prefetch_bsd_aarch64.inline.hpp index 1bcbdcaf90d..185f9b54144 100644 --- a/src/hotspot/os_cpu/bsd_aarch64/prefetch_bsd_aarch64.inline.hpp +++ b/src/hotspot/os_cpu/bsd_aarch64/prefetch_bsd_aarch64.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, Red Hat Inc. All rights reserved. * Copyright (c) 2021, Azul Systems, Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -27,8 +27,7 @@ #ifndef OS_CPU_BSD_AARCH64_PREFETCH_BSD_AARCH64_INLINE_HPP #define OS_CPU_BSD_AARCH64_PREFETCH_BSD_AARCH64_INLINE_HPP -#include "runtime/prefetch.hpp" - +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read (const void *loc, intx interval) { if (interval >= 0) diff --git a/src/hotspot/os_cpu/bsd_x86/os_bsd_x86.cpp b/src/hotspot/os_cpu/bsd_x86/os_bsd_x86.cpp index 420e7b4cd8d..f1c80594eaf 100644 --- a/src/hotspot/os_cpu/bsd_x86/os_bsd_x86.cpp +++ b/src/hotspot/os_cpu/bsd_x86/os_bsd_x86.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2026, 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 @@ #include "classfile/vmSymbols.hpp" #include "code/codeCache.hpp" #include "code/vtableStubs.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "logging/log.hpp" @@ -58,7 +59,6 @@ # include # include # include -# include # include # include # include diff --git a/src/hotspot/os_cpu/bsd_x86/prefetch_bsd_x86.inline.hpp b/src/hotspot/os_cpu/bsd_x86/prefetch_bsd_x86.inline.hpp index 52cc405e211..464740920a1 100644 --- a/src/hotspot/os_cpu/bsd_x86/prefetch_bsd_x86.inline.hpp +++ b/src/hotspot/os_cpu/bsd_x86/prefetch_bsd_x86.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, 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 @@ #ifndef OS_CPU_BSD_X86_PREFETCH_BSD_X86_INLINE_HPP #define OS_CPU_BSD_X86_PREFETCH_BSD_X86_INLINE_HPP -#include "runtime/prefetch.hpp" - +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read (const void *loc, intx interval) { __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval)); diff --git a/src/hotspot/os_cpu/bsd_zero/prefetch_bsd_zero.inline.hpp b/src/hotspot/os_cpu/bsd_zero/prefetch_bsd_zero.inline.hpp index 220d6a08f68..5edf3744719 100644 --- a/src/hotspot/os_cpu/bsd_zero/prefetch_bsd_zero.inline.hpp +++ b/src/hotspot/os_cpu/bsd_zero/prefetch_bsd_zero.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright 2007, 2008 Red Hat, Inc. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,7 +26,7 @@ #ifndef OS_CPU_BSD_ZERO_PREFETCH_BSD_ZERO_INLINE_HPP #define OS_CPU_BSD_ZERO_PREFETCH_BSD_ZERO_INLINE_HPP -#include "runtime/prefetch.hpp" +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read(const void* loc, intx interval) { } diff --git a/src/hotspot/os_cpu/linux_aarch64/os_linux_aarch64.cpp b/src/hotspot/os_cpu/linux_aarch64/os_linux_aarch64.cpp index e565f353382..da9e7e159f1 100644 --- a/src/hotspot/os_cpu/linux_aarch64/os_linux_aarch64.cpp +++ b/src/hotspot/os_cpu/linux_aarch64/os_linux_aarch64.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, Red Hat Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -28,6 +28,7 @@ #include "code/codeCache.hpp" #include "code/vtableStubs.hpp" #include "code/nativeInst.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "memory/allocation.inline.hpp" @@ -59,7 +60,6 @@ # include # include # include -# include # include # include # include diff --git a/src/hotspot/os_cpu/linux_aarch64/prefetch_linux_aarch64.inline.hpp b/src/hotspot/os_cpu/linux_aarch64/prefetch_linux_aarch64.inline.hpp index 168a680a404..580e9f4ffa2 100644 --- a/src/hotspot/os_cpu/linux_aarch64/prefetch_linux_aarch64.inline.hpp +++ b/src/hotspot/os_cpu/linux_aarch64/prefetch_linux_aarch64.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, Red Hat Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,8 +26,7 @@ #ifndef OS_CPU_LINUX_AARCH64_PREFETCH_LINUX_AARCH64_INLINE_HPP #define OS_CPU_LINUX_AARCH64_PREFETCH_LINUX_AARCH64_INLINE_HPP -#include "runtime/prefetch.hpp" - +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read (const void *loc, intx interval) { if (interval >= 0) diff --git a/src/hotspot/os_cpu/linux_arm/os_linux_arm.cpp b/src/hotspot/os_cpu/linux_arm/os_linux_arm.cpp index f4196d89fe3..41a4dbea384 100644 --- a/src/hotspot/os_cpu/linux_arm/os_linux_arm.cpp +++ b/src/hotspot/os_cpu/linux_arm/os_linux_arm.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2026, 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 @@ #include "asm/assembler.inline.hpp" #include "classfile/vmSymbols.hpp" #include "code/vtableStubs.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "memory/allocation.inline.hpp" @@ -57,7 +58,6 @@ # include # include # include -# include # include # include # include diff --git a/src/hotspot/os_cpu/linux_arm/prefetch_linux_arm.inline.hpp b/src/hotspot/os_cpu/linux_arm/prefetch_linux_arm.inline.hpp index dfbab55d9b9..a536c17fbe3 100644 --- a/src/hotspot/os_cpu/linux_arm/prefetch_linux_arm.inline.hpp +++ b/src/hotspot/os_cpu/linux_arm/prefetch_linux_arm.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2026, 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 @@ #ifndef OS_CPU_LINUX_ARM_PREFETCH_LINUX_ARM_INLINE_HPP #define OS_CPU_LINUX_ARM_PREFETCH_LINUX_ARM_INLINE_HPP -#include "runtime/prefetch.hpp" +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read (const void *loc, intx interval) { #if defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_5TE__) diff --git a/src/hotspot/os_cpu/linux_ppc/os_linux_ppc.cpp b/src/hotspot/os_cpu/linux_ppc/os_linux_ppc.cpp index 5909b5799b9..6854fb805a9 100644 --- a/src/hotspot/os_cpu/linux_ppc/os_linux_ppc.cpp +++ b/src/hotspot/os_cpu/linux_ppc/os_linux_ppc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2025 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -28,6 +28,7 @@ #include "classfile/vmSymbols.hpp" #include "code/codeCache.hpp" #include "code/vtableStubs.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "memory/allocation.inline.hpp" @@ -62,7 +63,6 @@ # include # include # include -# include # include # include # include diff --git a/src/hotspot/os_cpu/linux_ppc/prefetch_linux_ppc.inline.hpp b/src/hotspot/os_cpu/linux_ppc/prefetch_linux_ppc.inline.hpp index 12c65e6bf00..c33624a07de 100644 --- a/src/hotspot/os_cpu/linux_ppc/prefetch_linux_ppc.inline.hpp +++ b/src/hotspot/os_cpu/linux_ppc/prefetch_linux_ppc.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2013 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,8 +26,7 @@ #ifndef OS_CPU_LINUX_PPC_PREFETCH_LINUX_PPC_INLINE_HPP #define OS_CPU_LINUX_PPC_PREFETCH_LINUX_PPC_INLINE_HPP -#include "runtime/prefetch.hpp" - +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read(const void *loc, intx interval) { __asm__ __volatile__ ( diff --git a/src/hotspot/os_cpu/linux_riscv/os_linux_riscv.cpp b/src/hotspot/os_cpu/linux_riscv/os_linux_riscv.cpp index 7a5929b0f41..d4a306d35b1 100644 --- a/src/hotspot/os_cpu/linux_riscv/os_linux_riscv.cpp +++ b/src/hotspot/os_cpu/linux_riscv/os_linux_riscv.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2020, 2022, Huawei Technologies Co., Ltd. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -28,6 +28,7 @@ #include "code/codeCache.hpp" #include "code/nativeInst.hpp" #include "code/vtableStubs.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "memory/allocation.inline.hpp" @@ -61,7 +62,6 @@ # include # include # include -# include # include # include # include diff --git a/src/hotspot/os_cpu/linux_riscv/prefetch_linux_riscv.inline.hpp b/src/hotspot/os_cpu/linux_riscv/prefetch_linux_riscv.inline.hpp index a2dd79544c1..c17054e8a0c 100644 --- a/src/hotspot/os_cpu/linux_riscv/prefetch_linux_riscv.inline.hpp +++ b/src/hotspot/os_cpu/linux_riscv/prefetch_linux_riscv.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2020, 2021, Huawei Technologies Co., Ltd. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,7 +26,7 @@ #ifndef OS_CPU_LINUX_RISCV_VM_PREFETCH_LINUX_RISCV_INLINE_HPP #define OS_CPU_LINUX_RISCV_VM_PREFETCH_LINUX_RISCV_INLINE_HPP -#include "runtime/prefetch.hpp" +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read (const void *loc, intx interval) { if (interval >= 0 && UseZicbop) { diff --git a/src/hotspot/os_cpu/linux_s390/os_linux_s390.cpp b/src/hotspot/os_cpu/linux_s390/os_linux_s390.cpp index 4e074512e34..749f6bec032 100644 --- a/src/hotspot/os_cpu/linux_s390/os_linux_s390.cpp +++ b/src/hotspot/os_cpu/linux_s390/os_linux_s390.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2016, 2024 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -30,6 +30,7 @@ #include "code/nativeInst.hpp" #include "code/vtableStubs.hpp" #include "compiler/disassembler.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "memory/allocation.inline.hpp" @@ -62,7 +63,6 @@ # include # include # include -# include # include # include # include diff --git a/src/hotspot/os_cpu/linux_s390/prefetch_linux_s390.inline.hpp b/src/hotspot/os_cpu/linux_s390/prefetch_linux_s390.inline.hpp index ee55d01886f..56038714a9a 100644 --- a/src/hotspot/os_cpu/linux_s390/prefetch_linux_s390.inline.hpp +++ b/src/hotspot/os_cpu/linux_s390/prefetch_linux_s390.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2016 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,7 +26,7 @@ #ifndef OS_CPU_LINUX_S390_PREFETCH_LINUX_S390_INLINE_HPP #define OS_CPU_LINUX_S390_PREFETCH_LINUX_S390_INLINE_HPP -#include "runtime/prefetch.hpp" +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read(const void* loc, intx interval) { // No prefetch instructions on z/Architecture -> implement trivially. diff --git a/src/hotspot/os_cpu/linux_x86/os_linux_x86.cpp b/src/hotspot/os_cpu/linux_x86/os_linux_x86.cpp index a7f4e5ef688..07f53582a76 100644 --- a/src/hotspot/os_cpu/linux_x86/os_linux_x86.cpp +++ b/src/hotspot/os_cpu/linux_x86/os_linux_x86.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2026, 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 @@ #include "classfile/vmSymbols.hpp" #include "code/codeCache.hpp" #include "code/vtableStubs.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "logging/log.hpp" @@ -59,7 +60,6 @@ # include # include # include -# include # include # include # include diff --git a/src/hotspot/os_cpu/linux_x86/prefetch_linux_x86.inline.hpp b/src/hotspot/os_cpu/linux_x86/prefetch_linux_x86.inline.hpp index bb4302e1ddb..aadd21bca40 100644 --- a/src/hotspot/os_cpu/linux_x86/prefetch_linux_x86.inline.hpp +++ b/src/hotspot/os_cpu/linux_x86/prefetch_linux_x86.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, 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 @@ #ifndef OS_CPU_LINUX_X86_PREFETCH_LINUX_X86_INLINE_HPP #define OS_CPU_LINUX_X86_PREFETCH_LINUX_X86_INLINE_HPP -#include "runtime/prefetch.hpp" - +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read (const void *loc, intx interval) { __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval)); diff --git a/src/hotspot/os_cpu/linux_zero/prefetch_linux_zero.inline.hpp b/src/hotspot/os_cpu/linux_zero/prefetch_linux_zero.inline.hpp index a510fa87834..3a34c311acd 100644 --- a/src/hotspot/os_cpu/linux_zero/prefetch_linux_zero.inline.hpp +++ b/src/hotspot/os_cpu/linux_zero/prefetch_linux_zero.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright 2007, 2008 Red Hat, Inc. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,7 +26,7 @@ #ifndef OS_CPU_LINUX_ZERO_PREFETCH_LINUX_ZERO_INLINE_HPP #define OS_CPU_LINUX_ZERO_PREFETCH_LINUX_ZERO_INLINE_HPP -#include "runtime/prefetch.hpp" +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read(const void* loc, intx interval) { } diff --git a/src/hotspot/os_cpu/windows_aarch64/os_windows_aarch64.cpp b/src/hotspot/os_cpu/windows_aarch64/os_windows_aarch64.cpp index d99e0167cbd..2c2afb168fd 100644 --- a/src/hotspot/os_cpu/windows_aarch64/os_windows_aarch64.cpp +++ b/src/hotspot/os_cpu/windows_aarch64/os_windows_aarch64.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2020, Microsoft Corporation. All rights reserved. - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, 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 @@ -28,6 +28,7 @@ #include "code/codeCache.hpp" #include "code/vtableStubs.hpp" #include "code/nativeInst.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/interpreter.hpp" #include "jvm.h" #include "memory/allocation.inline.hpp" @@ -54,7 +55,6 @@ # include # include # include -# include # include # include diff --git a/src/hotspot/os_cpu/windows_aarch64/prefetch_windows_aarch64.inline.hpp b/src/hotspot/os_cpu/windows_aarch64/prefetch_windows_aarch64.inline.hpp index df301ade92d..a360ee342be 100644 --- a/src/hotspot/os_cpu/windows_aarch64/prefetch_windows_aarch64.inline.hpp +++ b/src/hotspot/os_cpu/windows_aarch64/prefetch_windows_aarch64.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Microsoft Corporation. All rights reserved. + * Copyright (c) 2020, 2026, Microsoft Corporation. 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 @@ #ifndef OS_CPU_WINDOWS_AARCH64_PREFETCH_WINDOWS_AARCH64_INLINE_HPP #define OS_CPU_WINDOWS_AARCH64_PREFETCH_WINDOWS_AARCH64_INLINE_HPP -#include "runtime/prefetch.hpp" - +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read (const void *loc, intx interval) { } diff --git a/src/hotspot/os_cpu/windows_x86/prefetch_windows_x86.inline.hpp b/src/hotspot/os_cpu/windows_x86/prefetch_windows_x86.inline.hpp index 996625cb0ad..645fbe99a22 100644 --- a/src/hotspot/os_cpu/windows_x86/prefetch_windows_x86.inline.hpp +++ b/src/hotspot/os_cpu/windows_x86/prefetch_windows_x86.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, 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 @@ #ifndef OS_CPU_WINDOWS_X86_PREFETCH_WINDOWS_X86_INLINE_HPP #define OS_CPU_WINDOWS_X86_PREFETCH_WINDOWS_X86_INLINE_HPP -#include "runtime/prefetch.hpp" +// Included in runtime/prefetch.inline.hpp inline void Prefetch::read (const void *loc, intx interval) {} inline void Prefetch::write(void *loc, intx interval) {} diff --git a/src/hotspot/share/c1/c1_LinearScan.hpp b/src/hotspot/share/c1/c1_LinearScan.hpp index 33cc0e5d17b..3873c371a47 100644 --- a/src/hotspot/share/c1/c1_LinearScan.hpp +++ b/src/hotspot/share/c1/c1_LinearScan.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, 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 @@ -884,7 +884,6 @@ class LinearScanStatistic : public StackObj { counter_throw, counter_unwind, counter_typecheck, - counter_fpu_stack, counter_misc_inst, counter_other_inst, blank_line_2, diff --git a/src/hotspot/share/cds/aotConstantPoolResolver.cpp b/src/hotspot/share/cds/aotConstantPoolResolver.cpp index c4bb26f6fb1..93145940955 100644 --- a/src/hotspot/share/cds/aotConstantPoolResolver.cpp +++ b/src/hotspot/share/cds/aotConstantPoolResolver.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, 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 @@ -116,6 +116,10 @@ bool AOTConstantPoolResolver::is_class_resolution_deterministic(InstanceKlass* c return false; } } else if (resolved_class->is_objArray_klass()) { + if (CDSConfig::is_dumping_dynamic_archive()) { + // This is difficult to handle. See JDK-8374639 + return false; + } Klass* elem = ObjArrayKlass::cast(resolved_class)->bottom_klass(); if (elem->is_instance_klass()) { return is_class_resolution_deterministic(cp_holder, InstanceKlass::cast(elem)); diff --git a/src/hotspot/share/cds/aotMappedHeapWriter.cpp b/src/hotspot/share/cds/aotMappedHeapWriter.cpp index 9c67b2e0e8d..e73b980614a 100644 --- a/src/hotspot/share/cds/aotMappedHeapWriter.cpp +++ b/src/hotspot/share/cds/aotMappedHeapWriter.cpp @@ -696,7 +696,7 @@ template void AOTMappedHeapWriter::relocate_field_in_buffer(T* fiel // We use zero-based, 0-shift encoding, so the narrowOop is just the lower // 32 bits of request_referent intptr_t addr = cast_from_oop(request_referent); - *((narrowOop*)field_addr_in_buffer) = checked_cast(addr); + *((narrowOop*)field_addr_in_buffer) = CompressedOops::narrow_oop_cast(addr); } else { store_requested_oop_in_buffer(field_addr_in_buffer, request_referent); } diff --git a/src/hotspot/share/cds/aotMetaspace.cpp b/src/hotspot/share/cds/aotMetaspace.cpp index 3824a2be3e2..79d789e0c70 100644 --- a/src/hotspot/share/cds/aotMetaspace.cpp +++ b/src/hotspot/share/cds/aotMetaspace.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -2159,7 +2159,6 @@ void AOTMetaspace::initialize_shared_spaces() { intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data(); ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress); DynamicArchive::serialize(&rc); - DynamicArchive::setup_array_klasses(); } LogStreamHandle(Info, aot) lsh; diff --git a/src/hotspot/share/cds/archiveBuilder.cpp b/src/hotspot/share/cds/archiveBuilder.cpp index 3c7f25a950b..6bbefea5cd9 100644 --- a/src/hotspot/share/cds/archiveBuilder.cpp +++ b/src/hotspot/share/cds/archiveBuilder.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, 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 @@ -984,8 +984,6 @@ void ArchiveBuilder::make_klasses_shareable() { #undef STATS_FORMAT #undef STATS_PARAMS - - DynamicArchive::make_array_klasses_shareable(); } void ArchiveBuilder::make_training_data_shareable() { diff --git a/src/hotspot/share/cds/dynamicArchive.cpp b/src/hotspot/share/cds/dynamicArchive.cpp index 8fae8dabf8c..d39cf3775e4 100644 --- a/src/hotspot/share/cds/dynamicArchive.cpp +++ b/src/hotspot/share/cds/dynamicArchive.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ -48,6 +48,7 @@ #include "logging/log.hpp" #include "memory/metaspaceClosure.hpp" #include "memory/resourceArea.hpp" +#include "oops/array.hpp" #include "oops/klass.inline.hpp" #include "runtime/arguments.hpp" #include "runtime/os.hpp" @@ -95,7 +96,6 @@ public: void sort_methods(InstanceKlass* ik) const; void remark_pointers_for_instance_klass(InstanceKlass* k, bool should_mark) const; void write_archive(char* serialized_data, AOTClassLocationConfig* cl_config); - void gather_array_klasses(); public: // Do this before and after the archive dump to see if any corruption @@ -132,7 +132,6 @@ public: init_header(); gather_source_objs(); - gather_array_klasses(); reserve_buffer(); log_info(cds, dynamic)("Copying %d klasses and %d symbols", @@ -159,7 +158,6 @@ public: ArchiveBuilder::OtherROAllocMark mark; SystemDictionaryShared::write_to_archive(false); cl_config = AOTClassLocationConfig::dumptime()->write_to_archive(); - DynamicArchive::dump_array_klasses(); serialized_data = ro_region()->top(); WriteClosure wc(ro_region()); @@ -175,8 +173,6 @@ public: write_archive(serialized_data, cl_config); release_header(); - DynamicArchive::post_dump(); - post_dump(); verify_universe("After CDS dynamic dump"); @@ -185,30 +181,6 @@ public: virtual void iterate_roots(MetaspaceClosure* it) { AOTArtifactFinder::all_cached_classes_do(it); SystemDictionaryShared::dumptime_classes_do(it); - iterate_primitive_array_klasses(it); - } - - void iterate_primitive_array_klasses(MetaspaceClosure* it) { - for (int i = T_BOOLEAN; i <= T_LONG; i++) { - assert(is_java_primitive((BasicType)i), "sanity"); - Klass* k = Universe::typeArrayKlass((BasicType)i); // this give you "[I", etc - assert(AOTMetaspace::in_aot_cache_static_region((void*)k), - "one-dimensional primitive array should be in static archive"); - ArrayKlass* ak = ArrayKlass::cast(k); - while (ak != nullptr && ak->in_aot_cache()) { - Klass* next_k = ak->array_klass_or_null(); - if (next_k != nullptr) { - ak = ArrayKlass::cast(next_k); - } else { - ak = nullptr; - } - } - if (ak != nullptr) { - assert(ak->dimension() > 1, "sanity"); - // this is the lowest dimension that's not in the static archive - it->push(&ak); - } - } } }; @@ -367,26 +339,6 @@ void DynamicArchiveBuilder::write_archive(char* serialized_data, AOTClassLocatio log_info(cds, dynamic)("%d klasses; %d symbols", klasses()->length(), symbols()->length()); } -void DynamicArchiveBuilder::gather_array_klasses() { - for (int i = 0; i < klasses()->length(); i++) { - if (klasses()->at(i)->is_objArray_klass()) { - ObjArrayKlass* oak = ObjArrayKlass::cast(klasses()->at(i)); - Klass* elem = oak->element_klass(); - if (AOTMetaspace::in_aot_cache_static_region(elem)) { - // Only capture the array klass whose element_klass is in the static archive. - // During run time, setup (see DynamicArchive::setup_array_klasses()) is needed - // so that the element_klass can find its array klasses from the dynamic archive. - DynamicArchive::append_array_klass(oak); - } else { - // The element_klass and its array klasses are in the same archive. - assert(!AOTMetaspace::in_aot_cache_static_region(oak), - "we should not gather klasses that are already in the static archive"); - } - } - } - log_debug(aot)("Total array klasses gathered for dynamic archive: %d", DynamicArchive::num_array_klasses()); -} - class VM_PopulateDynamicDumpSharedSpace: public VM_Heap_Sync_Operation { DynamicArchiveBuilder _builder; public: @@ -403,76 +355,9 @@ public: } }; -// _array_klasses and _dynamic_archive_array_klasses only hold the array klasses -// which have element klass in the static archive. -GrowableArray* DynamicArchive::_array_klasses = nullptr; -Array* DynamicArchive::_dynamic_archive_array_klasses = nullptr; - void DynamicArchive::serialize(SerializeClosure* soc) { SymbolTable::serialize_shared_table_header(soc, false); SystemDictionaryShared::serialize_dictionary_headers(soc, false); - soc->do_ptr(&_dynamic_archive_array_klasses); -} - -void DynamicArchive::append_array_klass(ObjArrayKlass* ak) { - if (_array_klasses == nullptr) { - _array_klasses = new (mtClassShared) GrowableArray(50, mtClassShared); - } - _array_klasses->append(ak); -} - -void DynamicArchive::dump_array_klasses() { - assert(CDSConfig::is_dumping_dynamic_archive(), "sanity"); - if (_array_klasses != nullptr) { - ArchiveBuilder* builder = ArchiveBuilder::current(); - int num_array_klasses = _array_klasses->length(); - _dynamic_archive_array_klasses = - ArchiveBuilder::new_ro_array(num_array_klasses); - for (int i = 0; i < num_array_klasses; i++) { - builder->write_pointer_in_buffer(_dynamic_archive_array_klasses->adr_at(i), _array_klasses->at(i)); - } - } -} - -void DynamicArchive::setup_array_klasses() { - if (_dynamic_archive_array_klasses != nullptr) { - for (int i = 0; i < _dynamic_archive_array_klasses->length(); i++) { - ObjArrayKlass* oak = _dynamic_archive_array_klasses->at(i); - Klass* elm = oak->element_klass(); - assert(AOTMetaspace::in_aot_cache_static_region((void*)elm), "must be"); - - if (elm->is_instance_klass()) { - assert(InstanceKlass::cast(elm)->array_klasses() == nullptr, "must be"); - InstanceKlass::cast(elm)->set_array_klasses(oak); - } else { - assert(elm->is_array_klass(), "sanity"); - assert(ArrayKlass::cast(elm)->higher_dimension() == nullptr, "must be"); - ArrayKlass::cast(elm)->set_higher_dimension(oak); - } - } - log_debug(aot)("Total array klasses read from dynamic archive: %d", _dynamic_archive_array_klasses->length()); - } -} - -void DynamicArchive::make_array_klasses_shareable() { - if (_array_klasses != nullptr) { - int num_array_klasses = _array_klasses->length(); - for (int i = 0; i < num_array_klasses; i++) { - ObjArrayKlass* k = ArchiveBuilder::current()->get_buffered_addr(_array_klasses->at(i)); - k->remove_unshareable_info(); - } - } -} - -void DynamicArchive::post_dump() { - if (_array_klasses != nullptr) { - delete _array_klasses; - _array_klasses = nullptr; - } -} - -int DynamicArchive::num_array_klasses() { - return _array_klasses != nullptr ? _array_klasses->length() : 0; } void DynamicArchive::dump_impl(bool jcmd_request, const char* archive_name, TRAPS) { diff --git a/src/hotspot/share/cds/dynamicArchive.hpp b/src/hotspot/share/cds/dynamicArchive.hpp index c42c4b7dfde..63a48e252ee 100644 --- a/src/hotspot/share/cds/dynamicArchive.hpp +++ b/src/hotspot/share/cds/dynamicArchive.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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,13 +26,8 @@ #define SHARE_CDS_DYNAMICARCHIVE_HPP #include "cds/filemap.hpp" -#include "classfile/compactHashtable.hpp" #include "memory/allStatic.hpp" -#include "memory/memRegion.hpp" -#include "oops/array.hpp" -#include "oops/oop.hpp" #include "utilities/exceptions.hpp" -#include "utilities/growableArray.hpp" #include "utilities/macros.hpp" #if INCLUDE_CDS @@ -59,22 +54,13 @@ public: }; class DynamicArchive : AllStatic { -private: - static GrowableArray* _array_klasses; - static Array* _dynamic_archive_array_klasses; public: static void dump_for_jcmd(const char* archive_name, TRAPS); static void dump_at_exit(JavaThread* current); static void dump_impl(bool jcmd_request, const char* archive_name, TRAPS); static bool is_mapped() { return FileMapInfo::dynamic_info() != nullptr; } static bool validate(FileMapInfo* dynamic_info); - static void dump_array_klasses(); - static void setup_array_klasses(); - static void append_array_klass(ObjArrayKlass* oak); static void serialize(SerializeClosure* soc); - static void make_array_klasses_shareable(); - static void post_dump(); - static int num_array_klasses(); }; #endif // INCLUDE_CDS #endif // SHARE_CDS_DYNAMICARCHIVE_HPP diff --git a/src/hotspot/share/classfile/classLoader.cpp b/src/hotspot/share/classfile/classLoader.cpp index 12fbda899b9..d9a63cd154b 100644 --- a/src/hotspot/share/classfile/classLoader.cpp +++ b/src/hotspot/share/classfile/classLoader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, 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 @@ -42,6 +42,7 @@ #include "classfile/vmClasses.hpp" #include "classfile/vmSymbols.hpp" #include "compiler/compileBroker.hpp" +#include "cppstdlib/cstdlib.hpp" #include "interpreter/bytecodeStream.hpp" #include "interpreter/oopMapCache.hpp" #include "jimage.hpp" @@ -81,7 +82,6 @@ #include "utilities/utf8.hpp" #include -#include // Entry point in java.dll for path canonicalization diff --git a/src/hotspot/share/classfile/javaClasses.cpp b/src/hotspot/share/classfile/javaClasses.cpp index 77a94c8afa5..dd70d7b49ab 100644 --- a/src/hotspot/share/classfile/javaClasses.cpp +++ b/src/hotspot/share/classfile/javaClasses.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, 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 @@ -4297,10 +4297,6 @@ int jdk_internal_foreign_abi_NativeEntryPoint::_downcall_stub_address_offset; macro(_method_type_offset, k, "methodType", java_lang_invoke_MethodType_signature, false); \ macro(_downcall_stub_address_offset, k, "downcallStubAddress", long_signature, false); -bool jdk_internal_foreign_abi_NativeEntryPoint::is_instance(oop obj) { - return obj != nullptr && is_subclass(obj->klass()); -} - void jdk_internal_foreign_abi_NativeEntryPoint::compute_offsets() { InstanceKlass* k = vmClasses::NativeEntryPoint_klass(); NEP_FIELDS_DO(FIELD_COMPUTE_OFFSET); @@ -4337,10 +4333,6 @@ int jdk_internal_foreign_abi_ABIDescriptor::_scratch2_offset; macro(_scratch1_offset, k, "scratch1", jdk_internal_foreign_abi_VMStorage_signature, false); \ macro(_scratch2_offset, k, "scratch2", jdk_internal_foreign_abi_VMStorage_signature, false); -bool jdk_internal_foreign_abi_ABIDescriptor::is_instance(oop obj) { - return obj != nullptr && is_subclass(obj->klass()); -} - void jdk_internal_foreign_abi_ABIDescriptor::compute_offsets() { InstanceKlass* k = vmClasses::ABIDescriptor_klass(); ABIDescriptor_FIELDS_DO(FIELD_COMPUTE_OFFSET); diff --git a/src/hotspot/share/classfile/javaClasses.hpp b/src/hotspot/share/classfile/javaClasses.hpp index 33dc912404c..a8562a345c8 100644 --- a/src/hotspot/share/classfile/javaClasses.hpp +++ b/src/hotspot/share/classfile/javaClasses.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, 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 @@ -1179,13 +1179,6 @@ class jdk_internal_foreign_abi_NativeEntryPoint: AllStatic { static oop method_type(oop entry); static jlong downcall_stub_address(oop entry); - // Testers - static bool is_subclass(Klass* klass) { - return vmClasses::NativeEntryPoint_klass() != nullptr && - klass->is_subclass_of(vmClasses::NativeEntryPoint_klass()); - } - static bool is_instance(oop obj); - // Accessors for code generation: static int method_type_offset_in_bytes() { return _method_type_offset; } static int downcall_stub_address_offset_in_bytes() { return _downcall_stub_address_offset; } @@ -1216,13 +1209,6 @@ class jdk_internal_foreign_abi_ABIDescriptor: AllStatic { static jint shadowSpace(oop entry); static oop scratch1(oop entry); static oop scratch2(oop entry); - - // Testers - static bool is_subclass(Klass* klass) { - return vmClasses::ABIDescriptor_klass() != nullptr && - klass->is_subclass_of(vmClasses::ABIDescriptor_klass()); - } - static bool is_instance(oop obj); }; class jdk_internal_foreign_abi_VMStorage: AllStatic { diff --git a/src/hotspot/share/classfile/vmIntrinsics.hpp b/src/hotspot/share/classfile/vmIntrinsics.hpp index 6f9c2326a45..07fa294e8e1 100644 --- a/src/hotspot/share/classfile/vmIntrinsics.hpp +++ b/src/hotspot/share/classfile/vmIntrinsics.hpp @@ -415,18 +415,18 @@ class methodHandle; \ do_class(java_lang_StringCoding, "java/lang/StringCoding") \ do_intrinsic(_countPositives, java_lang_StringCoding, countPositives_name, countPositives_signature, F_S) \ - do_name( countPositives_name, "countPositives0") \ + do_name( countPositives_name, "countPositives") \ do_signature(countPositives_signature, "([BII)I") \ \ do_class(sun_nio_cs_iso8859_1_Encoder, "sun/nio/cs/ISO_8859_1$Encoder") \ do_intrinsic(_encodeISOArray, sun_nio_cs_iso8859_1_Encoder, encodeISOArray_name, encodeISOArray_signature, F_S) \ - do_name( encodeISOArray_name, "encodeISOArray0") \ + do_name( encodeISOArray_name, "implEncodeISOArray") \ do_signature(encodeISOArray_signature, "([CI[BII)I") \ \ do_intrinsic(_encodeByteISOArray, java_lang_StringCoding, encodeISOArray_name, indexOfI_signature, F_S) \ \ do_intrinsic(_encodeAsciiArray, java_lang_StringCoding, encodeAsciiArray_name, encodeISOArray_signature, F_S) \ - do_name( encodeAsciiArray_name, "encodeAsciiArray0") \ + do_name( encodeAsciiArray_name, "implEncodeAsciiArray") \ \ do_class(java_math_BigInteger, "java/math/BigInteger") \ do_intrinsic(_multiplyToLen, java_math_BigInteger, multiplyToLen_name, multiplyToLen_signature, F_S) \ diff --git a/src/hotspot/share/cppstdlib/cstdlib.hpp b/src/hotspot/share/cppstdlib/cstdlib.hpp new file mode 100644 index 00000000000..2b58e737882 --- /dev/null +++ b/src/hotspot/share/cppstdlib/cstdlib.hpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2025, 2026, 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. + * + */ + +#ifndef SHARE_CPPSTDLIB_CSTDLIB_HPP +#define SHARE_CPPSTDLIB_CSTDLIB_HPP + +#include "utilities/compilerWarnings.hpp" + +// HotSpot usage for : +// +// Some functions are explicitly forbidden below. That may not be a complete +// list of all the functions we should forbid. +// +// We assume provides definitions in the global namespace, in +// addition to providing them in the std namespace. We prefer to use the names +// in the global namespace. + +BEGIN_ALLOW_FORBIDDEN_FUNCTIONS +#include "utilities/vmassert_uninstall.hpp" + +#include + +#include "utilities/vmassert_reinstall.hpp" // don't reorder +END_ALLOW_FORBIDDEN_FUNCTIONS + +// AIX may define malloc and calloc as macros when certain other features are +// present, causing us all sorts of grief. +// https://www.ibm.com/docs/en/openxl-c-and-cpp-aix/17.1.4?topic=compilers-memory-allocation +// Replace the macro definitions with something we can work with. +// AIX 7.3 no longer uses macro renaming when building with clang, instead +// using the same asm replacement approach as used below. This workaround can +// be removed once earlier versions are no longer supported as build platforms. +#if defined(AIX) && (defined(__VEC__) || defined(__AIXVEC)) +#if defined(malloc) || defined(calloc) +#if !defined(malloc) || !defined(calloc) +#error "Inconsistent alloc macro mappings, expected both to be mapped." +#endif +// Remove the macros. +#undef malloc +#undef calloc +// Implement the mapping using gcc/clang asm name mapping. +extern "C" { +extern void* malloc(size_t) noexcept asm("vec_malloc"); +extern void* calloc(size_t, size_t) noexcept asm("vec_calloc"); +} // extern "C" +// Because the macros are in place when brings names into the std +// namespace, macro replacement causes the expanded names to be added instead +// of the intended names. We can't remove std::vec_malloc and std::vec_calloc, +// but we do add the standard names in case someone uses them. +namespace std { +using ::malloc; +using ::calloc; +} // namespace std +#endif // Macro definition for malloc or calloc +#endif // AIX altivec allocator support + +// Prefer os:: variants of these. +FORBID_IMPORTED_NORETURN_C_FUNCTION(void exit(int), noexcept, "use os::exit") +FORBID_IMPORTED_NORETURN_C_FUNCTION(void _Exit(int), noexcept, "use os::exit") + +// Windows puts _exit in . POSIX puts it in . +// We can't forbid it here when using clang if it's not in - see +// the clang definition for FORBIDDEN_FUNCTION_NORETURN_ATTRIBUTE. +#ifdef _WINDOWS +FORBID_IMPORTED_NORETURN_C_FUNCTION(void _exit(int), /* not noexcept */, "use os::exit") +#endif // _WINDOWS + +// These functions return raw C-heap pointers or, in case of free(), take raw +// C-heap pointers. We generally want allocation to be done through NMT, using +// os::malloc and friends. +FORBID_IMPORTED_C_FUNCTION(void* malloc(size_t), noexcept, "use os::malloc"); +FORBID_IMPORTED_C_FUNCTION(void free(void*), noexcept, "use os::free"); +FORBID_IMPORTED_C_FUNCTION(void* calloc(size_t, size_t), noexcept, "use os::malloc and zero out manually"); +FORBID_IMPORTED_C_FUNCTION(void* realloc(void*, size_t), noexcept, "use os::realloc"); + +// These are not provided (and are unimplementable?) by Windows. +// https://stackoverflow.com/questions/62962839/stdaligned-alloc-missing-from-visual-studio-2019 +// They also aren't useful for a POSIX implementation of NMT. +#ifndef _WINDOWS +FORBID_C_FUNCTION(void* aligned_alloc(size_t, size_t), noexcept, "don't use"); +FORBID_C_FUNCTION(int posix_memalign(void**, size_t, size_t), noexcept, "don't use"); +#endif // !_WINDOWS + +#endif // SHARE_CPPSTDLIB_CSTDLIB_HPP diff --git a/src/hotspot/share/gc/epsilon/epsilonHeap.cpp b/src/hotspot/share/gc/epsilon/epsilonHeap.cpp index e5ae673ef0c..24182c22a23 100644 --- a/src/hotspot/share/gc/epsilon/epsilonHeap.cpp +++ b/src/hotspot/share/gc/epsilon/epsilonHeap.cpp @@ -77,6 +77,7 @@ jint EpsilonHeap::initialize() { void EpsilonHeap::initialize_serviceability() { _pool = new EpsilonMemoryPool(this); _memory_manager.add_pool(_pool); + _monitoring_support->mark_ready(); } GrowableArray EpsilonHeap::memory_managers() { @@ -101,7 +102,7 @@ EpsilonHeap* EpsilonHeap::heap() { return named_heap(CollectedHeap::Epsilon); } -HeapWord* EpsilonHeap::allocate_work(size_t size, bool verbose) { +HeapWord* EpsilonHeap::allocate_work(size_t size) { assert(is_object_aligned(size), "Allocation size should be aligned: %zu", size); HeapWord* res = nullptr; @@ -151,19 +152,23 @@ HeapWord* EpsilonHeap::allocate_work(size_t size, bool verbose) { size_t used = _space->used(); - // Allocation successful, update counters - if (verbose) { - size_t last = _last_counter_update; - if ((used - last >= _step_counter_update) && AtomicAccess::cmpxchg(&_last_counter_update, last, used) == last) { + // Allocation successful, update counters and print status. + // At this point, some diagnostic subsystems might not yet be initialized. + // We pretend the printout happened either way. This keeps allocation path + // from obsessively checking the subsystems' status on every allocation. + size_t last_counter = AtomicAccess::load(&_last_counter_update); + if ((used - last_counter >= _step_counter_update) && + AtomicAccess::cmpxchg(&_last_counter_update, last_counter, used) == last_counter) { + if (_monitoring_support->is_ready()) { _monitoring_support->update_counters(); } } - // ...and print the occupancy line, if needed - if (verbose) { - size_t last = _last_heap_print; - if ((used - last >= _step_heap_print) && AtomicAccess::cmpxchg(&_last_heap_print, last, used) == last) { - print_heap_info(used); + size_t last_heap = AtomicAccess::load(&_last_heap_print); + if ((used - last_heap >= _step_heap_print) && + AtomicAccess::cmpxchg(&_last_heap_print, last_heap, used) == last_heap) { + print_heap_info(used); + if (Metaspace::initialized()) { print_metaspace_info(); } } @@ -265,8 +270,7 @@ HeapWord* EpsilonHeap::mem_allocate(size_t size) { } HeapWord* EpsilonHeap::allocate_loaded_archive_space(size_t size) { - // Cannot use verbose=true because Metaspace is not initialized - return allocate_work(size, /* verbose = */false); + return allocate_work(size); } void EpsilonHeap::collect(GCCause::Cause cause) { diff --git a/src/hotspot/share/gc/epsilon/epsilonHeap.hpp b/src/hotspot/share/gc/epsilon/epsilonHeap.hpp index 4f812bde8b3..9693c63b15c 100644 --- a/src/hotspot/share/gc/epsilon/epsilonHeap.hpp +++ b/src/hotspot/share/gc/epsilon/epsilonHeap.hpp @@ -83,7 +83,7 @@ public: bool requires_barriers(stackChunkOop obj) const override { return false; } // Allocation - HeapWord* allocate_work(size_t size, bool verbose = true); + HeapWord* allocate_work(size_t size); HeapWord* mem_allocate(size_t size) override; HeapWord* allocate_new_tlab(size_t min_size, size_t requested_size, diff --git a/src/hotspot/share/gc/epsilon/epsilonMonitoringSupport.cpp b/src/hotspot/share/gc/epsilon/epsilonMonitoringSupport.cpp index 51d0a8356d2..38be736df74 100644 --- a/src/hotspot/share/gc/epsilon/epsilonMonitoringSupport.cpp +++ b/src/hotspot/share/gc/epsilon/epsilonMonitoringSupport.cpp @@ -96,9 +96,11 @@ public: EpsilonMonitoringSupport::EpsilonMonitoringSupport(EpsilonHeap* heap) { _heap_counters = new EpsilonGenerationCounters(heap); _space_counters = new EpsilonSpaceCounters("Heap", 0, heap->max_capacity(), 0, _heap_counters); + _ready = false; } void EpsilonMonitoringSupport::update_counters() { + assert(is_ready(), "Must be ready"); MemoryService::track_memory_usage(); if (UsePerfData) { @@ -110,3 +112,11 @@ void EpsilonMonitoringSupport::update_counters() { MetaspaceCounters::update_performance_counters(); } } + +bool EpsilonMonitoringSupport::is_ready() { + return AtomicAccess::load_acquire(&_ready); +} + +void EpsilonMonitoringSupport::mark_ready() { + return AtomicAccess::release_store(&_ready, true); +} diff --git a/src/hotspot/share/gc/epsilon/epsilonMonitoringSupport.hpp b/src/hotspot/share/gc/epsilon/epsilonMonitoringSupport.hpp index 67a60d92778..76cdac6df1b 100644 --- a/src/hotspot/share/gc/epsilon/epsilonMonitoringSupport.hpp +++ b/src/hotspot/share/gc/epsilon/epsilonMonitoringSupport.hpp @@ -35,9 +35,12 @@ class EpsilonMonitoringSupport : public CHeapObj { private: EpsilonGenerationCounters* _heap_counters; EpsilonSpaceCounters* _space_counters; + volatile bool _ready; public: EpsilonMonitoringSupport(EpsilonHeap* heap); + bool is_ready(); + void mark_ready(); void update_counters(); }; diff --git a/src/hotspot/share/gc/g1/g1Arguments.cpp b/src/hotspot/share/gc/g1/g1Arguments.cpp index 2be0e008c22..58e76cdd43a 100644 --- a/src/hotspot/share/gc/g1/g1Arguments.cpp +++ b/src/hotspot/share/gc/g1/g1Arguments.cpp @@ -36,6 +36,7 @@ #include "gc/shared/fullGCForwarding.hpp" #include "gc/shared/gcArguments.hpp" #include "gc/shared/workerPolicy.hpp" +#include "runtime/flags/jvmFlagLimit.hpp" #include "runtime/globals.hpp" #include "runtime/globals_extension.hpp" #include "runtime/java.hpp" @@ -190,7 +191,8 @@ void G1Arguments::initialize() { } FLAG_SET_DEFAULT(G1ConcRefinementThreads, 0); } else if (FLAG_IS_DEFAULT(G1ConcRefinementThreads)) { - FLAG_SET_ERGO(G1ConcRefinementThreads, ParallelGCThreads); + const JVMTypedFlagLimit* conc_refinement_threads_limits = JVMFlagLimit::get_range_at(FLAG_MEMBER_ENUM(G1ConcRefinementThreads))->cast(); + FLAG_SET_ERGO(G1ConcRefinementThreads, MIN2(ParallelGCThreads, conc_refinement_threads_limits->max())); } if (FLAG_IS_DEFAULT(ConcGCThreads) || ConcGCThreads == 0) { diff --git a/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.cpp b/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.cpp index d875d9c8b8a..ec5d2393d8c 100644 --- a/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.cpp +++ b/src/hotspot/share/gc/g1/g1YoungGCPostEvacuateTasks.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, 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 @@ -46,7 +46,7 @@ #include "oops/access.inline.hpp" #include "oops/compressedOops.inline.hpp" #include "oops/oop.inline.hpp" -#include "runtime/prefetch.hpp" +#include "runtime/prefetch.inline.hpp" #include "runtime/threads.hpp" #include "runtime/threadSMR.hpp" #include "utilities/bitMap.inline.hpp" diff --git a/src/hotspot/share/gc/serial/cardTableRS.cpp b/src/hotspot/share/gc/serial/cardTableRS.cpp index 80985424a62..a53ab066387 100644 --- a/src/hotspot/share/gc/serial/cardTableRS.cpp +++ b/src/hotspot/share/gc/serial/cardTableRS.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2026, 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 @@ -28,6 +28,7 @@ #include "gc/serial/serialHeap.inline.hpp" #include "gc/shared/space.hpp" #include "memory/iterator.inline.hpp" +#include "runtime/prefetch.inline.hpp" #include "utilities/align.hpp" void CardTableRS::scan_old_to_young_refs(TenuredGeneration* tg, HeapWord* saved_top) { diff --git a/src/hotspot/share/gc/serial/generation.hpp b/src/hotspot/share/gc/serial/generation.hpp index 8c9da3b42b7..ddfd4028a7d 100644 --- a/src/hotspot/share/gc/serial/generation.hpp +++ b/src/hotspot/share/gc/serial/generation.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, 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 @@ -34,7 +34,6 @@ #include "memory/virtualspace.hpp" #include "runtime/mutex.hpp" #include "runtime/perfData.hpp" -#include "runtime/prefetch.inline.hpp" // A Generation models a heap area for similarly-aged objects. // It will contain one ore more spaces holding the actual objects. diff --git a/src/hotspot/share/gc/serial/serialHeap.cpp b/src/hotspot/share/gc/serial/serialHeap.cpp index 08d730bf877..8eafdfdcc82 100644 --- a/src/hotspot/share/gc/serial/serialHeap.cpp +++ b/src/hotspot/share/gc/serial/serialHeap.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, 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 @@ -70,6 +70,7 @@ #include "runtime/init.hpp" #include "runtime/java.hpp" #include "runtime/mutexLocker.hpp" +#include "runtime/prefetch.inline.hpp" #include "runtime/threads.hpp" #include "runtime/vmThread.hpp" #include "services/memoryManager.hpp" diff --git a/src/hotspot/share/gc/shared/barrierSetNMethod.cpp b/src/hotspot/share/gc/shared/barrierSetNMethod.cpp index cb5d6b5a886..ab94bae079a 100644 --- a/src/hotspot/share/gc/shared/barrierSetNMethod.cpp +++ b/src/hotspot/share/gc/shared/barrierSetNMethod.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, 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 @@ -33,6 +33,7 @@ #include "memory/universe.hpp" #include "oops/access.inline.hpp" #include "oops/method.inline.hpp" +#include "runtime/atomic.hpp" #include "runtime/frame.inline.hpp" #include "runtime/javaThread.hpp" #include "runtime/threads.hpp" @@ -196,8 +197,8 @@ int BarrierSetNMethod::nmethod_stub_entry_barrier(address* return_address_ptr) { // Diagnostic option to force deoptimization 1 in 10 times. It is otherwise // a very rare event. if (DeoptimizeNMethodBarriersALot && !nm->is_osr_method()) { - static volatile uint32_t counter=0; - if (AtomicAccess::add(&counter, 1u) % 10 == 0) { + static Atomic counter{0}; + if (counter.add_then_fetch(1u) % 10 == 0) { may_enter = false; } } diff --git a/src/hotspot/share/gc/shared/concurrentGCThread.cpp b/src/hotspot/share/gc/shared/concurrentGCThread.cpp index ac281f82f8a..ed6c1b4d283 100644 --- a/src/hotspot/share/gc/shared/concurrentGCThread.cpp +++ b/src/hotspot/share/gc/shared/concurrentGCThread.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2026, 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,7 +23,7 @@ */ #include "gc/shared/concurrentGCThread.hpp" -#include "runtime/atomicAccess.hpp" +#include "runtime/atomic.hpp" #include "runtime/init.hpp" #include "runtime/jniHandles.hpp" #include "runtime/mutexLocker.hpp" @@ -48,7 +48,7 @@ void ConcurrentGCThread::run() { // Signal thread has terminated MonitorLocker ml(Terminator_lock); - AtomicAccess::release_store(&_has_terminated, true); + _has_terminated.release_store(true); ml.notify_all(); } @@ -57,21 +57,21 @@ void ConcurrentGCThread::stop() { assert(!has_terminated(), "Invalid state"); // Signal thread to terminate - AtomicAccess::release_store_fence(&_should_terminate, true); + _should_terminate.release_store_fence(true); stop_service(); // Wait for thread to terminate MonitorLocker ml(Terminator_lock); - while (!_has_terminated) { + while (!_has_terminated.load_relaxed()) { ml.wait(); } } bool ConcurrentGCThread::should_terminate() const { - return AtomicAccess::load_acquire(&_should_terminate); + return _should_terminate.load_acquire(); } bool ConcurrentGCThread::has_terminated() const { - return AtomicAccess::load_acquire(&_has_terminated); + return _has_terminated.load_acquire(); } diff --git a/src/hotspot/share/gc/shared/concurrentGCThread.hpp b/src/hotspot/share/gc/shared/concurrentGCThread.hpp index 630abeaeb9f..0c764546045 100644 --- a/src/hotspot/share/gc/shared/concurrentGCThread.hpp +++ b/src/hotspot/share/gc/shared/concurrentGCThread.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2026, 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,15 @@ #ifndef SHARE_GC_SHARED_CONCURRENTGCTHREAD_HPP #define SHARE_GC_SHARED_CONCURRENTGCTHREAD_HPP +#include "runtime/atomic.hpp" #include "runtime/javaThread.hpp" #include "runtime/nonJavaThread.hpp" #include "utilities/debug.hpp" class ConcurrentGCThread: public NamedThread { private: - volatile bool _should_terminate; - volatile bool _has_terminated; + Atomic _should_terminate; + Atomic _has_terminated; protected: void create_and_start(ThreadPriority prio = NearMaxPriority); diff --git a/src/hotspot/share/gc/shared/gcLocker.cpp b/src/hotspot/share/gc/shared/gcLocker.cpp index 01d17b1117d..898588e6b06 100644 --- a/src/hotspot/share/gc/shared/gcLocker.cpp +++ b/src/hotspot/share/gc/shared/gcLocker.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, 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 @@ -28,7 +28,7 @@ #include "logging/log.hpp" #include "memory/resourceArea.hpp" #include "memory/universe.hpp" -#include "runtime/atomicAccess.hpp" +#include "runtime/atomic.hpp" #include "runtime/interfaceSupport.inline.hpp" #include "runtime/javaThread.inline.hpp" #include "runtime/safepoint.hpp" @@ -60,16 +60,13 @@ public: }; Monitor* GCLocker::_lock; -volatile bool GCLocker::_is_gc_request_pending; +Atomic GCLocker::_is_gc_request_pending{false}; -DEBUG_ONLY(uint64_t GCLocker::_verify_in_cr_count;) +DEBUG_ONLY(Atomic GCLocker::_verify_in_cr_count{0};) void GCLocker::initialize() { assert(JNICritical_lock != nullptr, "inv"); _lock = JNICritical_lock; - _is_gc_request_pending = false; - - DEBUG_ONLY(_verify_in_cr_count = 0;) } bool GCLocker::is_active() { @@ -84,11 +81,11 @@ bool GCLocker::is_active() { void GCLocker::block() { // _lock is held from the beginning of block() to the end of of unblock(). _lock->lock(); - assert(AtomicAccess::load(&_is_gc_request_pending) == false, "precondition"); + assert(_is_gc_request_pending.load_relaxed() == false, "precondition"); GCLockerTimingDebugLogger logger("Thread blocked to start GC."); - AtomicAccess::store(&_is_gc_request_pending, true); + _is_gc_request_pending.store_relaxed(true); // The _is_gc_request_pending and _jni_active_critical (inside // in_critical_atomic()) variables form a Dekker duality. On the GC side, the @@ -112,14 +109,14 @@ void GCLocker::block() { #ifdef ASSERT // Matching the storestore in GCLocker::exit. OrderAccess::loadload(); - assert(AtomicAccess::load(&_verify_in_cr_count) == 0, "inv"); + assert(_verify_in_cr_count.load_relaxed() == 0, "inv"); #endif } void GCLocker::unblock() { - assert(AtomicAccess::load(&_is_gc_request_pending) == true, "precondition"); + assert(_is_gc_request_pending.load_relaxed() == true, "precondition"); - AtomicAccess::store(&_is_gc_request_pending, false); + _is_gc_request_pending.store_relaxed(false); _lock->unlock(); } @@ -139,7 +136,7 @@ void GCLocker::enter_slow(JavaThread* current_thread) { // Same as fast path. OrderAccess::fence(); - if (!AtomicAccess::load(&_is_gc_request_pending)) { + if (!_is_gc_request_pending.load_relaxed()) { return; } diff --git a/src/hotspot/share/gc/shared/gcLocker.hpp b/src/hotspot/share/gc/shared/gcLocker.hpp index c0e28b66539..be3c0c3593e 100644 --- a/src/hotspot/share/gc/shared/gcLocker.hpp +++ b/src/hotspot/share/gc/shared/gcLocker.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, 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 @@ #include "gc/shared/gcCause.hpp" #include "memory/allStatic.hpp" +#include "runtime/atomic.hpp" #include "runtime/mutex.hpp" // GCLocker provides synchronization between the garbage collector (GC) and @@ -43,11 +44,11 @@ class GCLocker: public AllStatic { static Monitor* _lock; - static volatile bool _is_gc_request_pending; + static Atomic _is_gc_request_pending; #ifdef ASSERT // Debug-only: to track the number of java threads in critical-region. - static uint64_t _verify_in_cr_count; + static Atomic _verify_in_cr_count; #endif static void enter_slow(JavaThread* current_thread); diff --git a/src/hotspot/share/gc/shared/gcLocker.inline.hpp b/src/hotspot/share/gc/shared/gcLocker.inline.hpp index 050b9570280..135bd9eab62 100644 --- a/src/hotspot/share/gc/shared/gcLocker.inline.hpp +++ b/src/hotspot/share/gc/shared/gcLocker.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2026, 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 @@ -38,13 +38,13 @@ void GCLocker::enter(JavaThread* current_thread) { // Matching the fence in GCLocker::block. OrderAccess::fence(); - if (AtomicAccess::load(&_is_gc_request_pending)) { + if (_is_gc_request_pending.load_relaxed()) { current_thread->exit_critical(); // slow-path enter_slow(current_thread); } - DEBUG_ONLY(AtomicAccess::add(&_verify_in_cr_count, (uint64_t)1);) + DEBUG_ONLY(_verify_in_cr_count.add_then_fetch(1u);) } else { current_thread->enter_critical(); } @@ -55,7 +55,7 @@ void GCLocker::exit(JavaThread* current_thread) { #ifdef ASSERT if (current_thread->in_last_critical()) { - AtomicAccess::add(&_verify_in_cr_count, (uint64_t)-1); + _verify_in_cr_count.sub_then_fetch(1u); // Matching the loadload in GCLocker::block. OrderAccess::storestore(); } diff --git a/src/hotspot/share/gc/shared/oopStorage.cpp b/src/hotspot/share/gc/shared/oopStorage.cpp index a1cc3ffa553..21e63f6fc32 100644 --- a/src/hotspot/share/gc/shared/oopStorage.cpp +++ b/src/hotspot/share/gc/shared/oopStorage.cpp @@ -700,7 +700,7 @@ void OopStorage::Block::release_entries(uintx releasing, OopStorage* owner) { // then someone else has made such a claim and the deferred update has not // yet been processed and will include our change, so we don't need to do // anything further. - if (_deferred_updates_next.compare_exchange(nullptr, this) == nullptr) { + if (_deferred_updates_next.compare_set(nullptr, this)) { // Successfully claimed. Push, with self-loop for end-of-list. Block* head = owner->_deferred_updates.load_relaxed(); while (true) { diff --git a/src/hotspot/share/gc/shared/pretouchTask.cpp b/src/hotspot/share/gc/shared/pretouchTask.cpp index cc84c8c449d..58a3a2693ed 100644 --- a/src/hotspot/share/gc/shared/pretouchTask.cpp +++ b/src/hotspot/share/gc/shared/pretouchTask.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, 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 @@ #include "gc/shared/gc_globals.hpp" #include "gc/shared/pretouchTask.hpp" #include "logging/log.hpp" -#include "runtime/atomicAccess.hpp" +#include "runtime/atomic.hpp" #include "runtime/globals.hpp" #include "runtime/os.hpp" #include "utilities/align.hpp" @@ -52,11 +52,11 @@ size_t PretouchTask::chunk_size() { void PretouchTask::work(uint worker_id) { while (true) { - char* cur_start = AtomicAccess::load(&_cur_addr); + char* cur_start = _cur_addr.load_relaxed(); char* cur_end = cur_start + MIN2(_chunk_size, pointer_delta(_end_addr, cur_start, 1)); if (cur_start >= cur_end) { break; - } else if (cur_start == AtomicAccess::cmpxchg(&_cur_addr, cur_start, cur_end)) { + } else if (_cur_addr.compare_set(cur_start, cur_end)) { os::pretouch_memory(cur_start, cur_end, _page_size); } // Else attempt to claim chunk failed, so try again. } diff --git a/src/hotspot/share/gc/shared/pretouchTask.hpp b/src/hotspot/share/gc/shared/pretouchTask.hpp index 7c66c8b717c..6355d61edf7 100644 --- a/src/hotspot/share/gc/shared/pretouchTask.hpp +++ b/src/hotspot/share/gc/shared/pretouchTask.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, 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,11 @@ #define SHARE_GC_SHARED_PRETOUCH_HPP #include "gc/shared/workerThread.hpp" +#include "runtime/atomic.hpp" +#include "utilities/globalDefinitions.hpp" class PretouchTask : public WorkerTask { - char* volatile _cur_addr; + Atomic _cur_addr; char* const _end_addr; size_t _page_size; size_t _chunk_size; diff --git a/src/hotspot/share/gc/shared/suspendibleThreadSet.cpp b/src/hotspot/share/gc/shared/suspendibleThreadSet.cpp index 83783b31ad9..834a3d04c00 100644 --- a/src/hotspot/share/gc/shared/suspendibleThreadSet.cpp +++ b/src/hotspot/share/gc/shared/suspendibleThreadSet.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, 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,7 +30,7 @@ uint SuspendibleThreadSet::_nthreads = 0; uint SuspendibleThreadSet::_nthreads_stopped = 0; -volatile bool SuspendibleThreadSet::_suspend_all = false; +Atomic SuspendibleThreadSet::_suspend_all{false}; double SuspendibleThreadSet::_suspend_all_start = 0.0; static Semaphore* _synchronize_wakeup = nullptr; @@ -96,7 +96,7 @@ void SuspendibleThreadSet::synchronize() { { MonitorLocker ml(STS_lock, Mutex::_no_safepoint_check_flag); assert(!should_yield(), "Only one at a time"); - AtomicAccess::store(&_suspend_all, true); + _suspend_all.store_relaxed(true); if (is_synchronized()) { return; } @@ -127,6 +127,6 @@ void SuspendibleThreadSet::desynchronize() { MonitorLocker ml(STS_lock, Mutex::_no_safepoint_check_flag); assert(should_yield(), "STS not synchronizing"); assert(is_synchronized(), "STS not synchronized"); - AtomicAccess::store(&_suspend_all, false); + _suspend_all.store_relaxed(false); ml.notify_all(); } diff --git a/src/hotspot/share/gc/shared/suspendibleThreadSet.hpp b/src/hotspot/share/gc/shared/suspendibleThreadSet.hpp index 38568c015bc..72fca5302e7 100644 --- a/src/hotspot/share/gc/shared/suspendibleThreadSet.hpp +++ b/src/hotspot/share/gc/shared/suspendibleThreadSet.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, 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,7 +26,7 @@ #define SHARE_GC_SHARED_SUSPENDIBLETHREADSET_HPP #include "memory/allocation.hpp" -#include "runtime/atomicAccess.hpp" +#include "runtime/atomic.hpp" // A SuspendibleThreadSet is a set of threads that can be suspended. // A thread can join and later leave the set, and periodically yield. @@ -43,7 +43,7 @@ class SuspendibleThreadSet : public AllStatic { private: static uint _nthreads; static uint _nthreads_stopped; - static volatile bool _suspend_all; + static Atomic _suspend_all; static double _suspend_all_start; static bool is_synchronized(); @@ -59,7 +59,7 @@ private: public: // Returns true if an suspension is in progress. - static bool should_yield() { return AtomicAccess::load(&_suspend_all); } + static bool should_yield() { return _suspend_all.load_relaxed(); } // Suspends the current thread if a suspension is in progress. static void yield() { diff --git a/src/hotspot/share/gc/shared/taskqueue.hpp b/src/hotspot/share/gc/shared/taskqueue.hpp index 3a751852ab6..4334773a4e9 100644 --- a/src/hotspot/share/gc/shared/taskqueue.hpp +++ b/src/hotspot/share/gc/shared/taskqueue.hpp @@ -183,8 +183,8 @@ protected: _age.store_relaxed(new_age); } - Age cmpxchg_age(Age old_age, Age new_age) { - return _age.compare_exchange(old_age, new_age); + bool par_set_age(Age old_age, Age new_age) { + return _age.compare_set(old_age, new_age); } idx_t age_top_relaxed() const { @@ -345,7 +345,7 @@ protected: using TaskQueueSuper::age_relaxed; using TaskQueueSuper::set_age_relaxed; - using TaskQueueSuper::cmpxchg_age; + using TaskQueueSuper::par_set_age; using TaskQueueSuper::age_top_relaxed; using TaskQueueSuper::increment_index; diff --git a/src/hotspot/share/gc/shared/taskqueue.inline.hpp b/src/hotspot/share/gc/shared/taskqueue.inline.hpp index f115d94740b..55851495a5f 100644 --- a/src/hotspot/share/gc/shared/taskqueue.inline.hpp +++ b/src/hotspot/share/gc/shared/taskqueue.inline.hpp @@ -170,8 +170,7 @@ bool GenericTaskQueue::pop_local_slow(uint localBot, Age oldAge) { if (localBot == oldAge.top()) { // No competing pop_global has yet incremented "top"; we'll try to // install new_age, thus claiming the element. - Age tempAge = cmpxchg_age(oldAge, newAge); - if (tempAge == oldAge) { + if (par_set_age(oldAge, newAge)) { // We win. assert_not_underflow(localBot, age_top_relaxed()); TASKQUEUE_STATS_ONLY(stats.record_pop_slow()); @@ -283,12 +282,12 @@ typename GenericTaskQueue::PopResult GenericTaskQueue::pop_g idx_t new_top = increment_index(oldAge.top()); idx_t new_tag = oldAge.tag() + ((new_top == 0) ? 1 : 0); Age newAge(new_top, new_tag); - Age resAge = cmpxchg_age(oldAge, newAge); + bool result = par_set_age(oldAge, newAge); // Note that using "bottom" here might fail, since a pop_local might // have decremented it. assert_not_underflow(localBot, newAge.top()); - return resAge == oldAge ? PopResult::Success : PopResult::Contended; + return result ? PopResult::Success : PopResult::Contended; } inline int randomParkAndMiller(int *seed0) { diff --git a/src/hotspot/share/gc/shared/workerThread.cpp b/src/hotspot/share/gc/shared/workerThread.cpp index 3a999da59dc..7a9404a195a 100644 --- a/src/hotspot/share/gc/shared/workerThread.cpp +++ b/src/hotspot/share/gc/shared/workerThread.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2026, 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 @@ -42,7 +42,7 @@ WorkerTaskDispatcher::WorkerTaskDispatcher() : void WorkerTaskDispatcher::coordinator_distribute_task(WorkerTask* task, uint num_workers) { // No workers are allowed to read the state variables until they have been signaled. _task = task; - _not_finished = num_workers; + _not_finished.store_relaxed(num_workers); // Dispatch 'num_workers' number of tasks. _start_semaphore.signal(num_workers); @@ -51,9 +51,12 @@ void WorkerTaskDispatcher::coordinator_distribute_task(WorkerTask* task, uint nu _end_semaphore.wait(); // No workers are allowed to read the state variables after the coordinator has been signaled. - assert(_not_finished == 0, "%d not finished workers?", _not_finished); +#ifdef ASSERT + uint not_finished = _not_finished.load_relaxed(); + assert(not_finished == 0, "%u not finished workers?", not_finished); +#endif // ASSERT _task = nullptr; - _started = 0; + _started.store_relaxed(0); } void WorkerTaskDispatcher::worker_run_task() { @@ -61,7 +64,7 @@ void WorkerTaskDispatcher::worker_run_task() { _start_semaphore.wait(); // Get and set worker id. - const uint worker_id = AtomicAccess::fetch_then_add(&_started, 1u); + const uint worker_id = _started.fetch_then_add(1u); WorkerThread::set_worker_id(worker_id); // Run task. @@ -70,7 +73,7 @@ void WorkerTaskDispatcher::worker_run_task() { // Mark that the worker is done with the task. // The worker is not allowed to read the state variables after this line. - const uint not_finished = AtomicAccess::sub(&_not_finished, 1u); + const uint not_finished = _not_finished.sub_then_fetch(1u); // The last worker signals to the coordinator that all work is completed. if (not_finished == 0) { diff --git a/src/hotspot/share/gc/shared/workerThread.hpp b/src/hotspot/share/gc/shared/workerThread.hpp index d4e92797039..a1f7282abe4 100644 --- a/src/hotspot/share/gc/shared/workerThread.hpp +++ b/src/hotspot/share/gc/shared/workerThread.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2026, 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 @@ #include "gc/shared/gcId.hpp" #include "memory/allocation.hpp" +#include "runtime/atomic.hpp" #include "runtime/nonJavaThread.hpp" #include "runtime/semaphore.hpp" #include "utilities/debug.hpp" @@ -58,8 +59,8 @@ class WorkerTaskDispatcher { // The task currently being dispatched to the WorkerThreads. WorkerTask* _task; - volatile uint _started; - volatile uint _not_finished; + Atomic _started; + Atomic _not_finished; // Semaphore used to start the WorkerThreads. Semaphore _start_semaphore; diff --git a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.cpp b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.cpp index 41535f302d7..7a8bd55c795 100644 --- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.cpp +++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.cpp @@ -183,8 +183,8 @@ void ShenandoahAdaptiveHeuristics::record_success_concurrent() { } } -void ShenandoahAdaptiveHeuristics::record_success_degenerated() { - ShenandoahHeuristics::record_success_degenerated(); +void ShenandoahAdaptiveHeuristics::record_degenerated() { + ShenandoahHeuristics::record_degenerated(); // Adjust both trigger's parameters in the case of a degenerated GC because // either of them should have triggered earlier to avoid this case. adjust_margin_of_error(DEGENERATE_PENALTY_SD); diff --git a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.hpp b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.hpp index 66bfc3375a3..1ba18f37c2b 100644 --- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.hpp +++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.hpp @@ -114,7 +114,7 @@ public: virtual void record_cycle_start() override; virtual void record_success_concurrent() override; - virtual void record_success_degenerated() override; + virtual void record_degenerated() override; virtual void record_success_full() override; virtual bool should_start_gc() override; diff --git a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahHeuristics.cpp b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahHeuristics.cpp index 478c5696188..eb740cfac61 100644 --- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahHeuristics.cpp +++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahHeuristics.cpp @@ -243,7 +243,7 @@ void ShenandoahHeuristics::record_success_concurrent() { adjust_penalty(Concurrent_Adjust); } -void ShenandoahHeuristics::record_success_degenerated() { +void ShenandoahHeuristics::record_degenerated() { adjust_penalty(Degenerated_Penalty); } diff --git a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahHeuristics.hpp b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahHeuristics.hpp index 3cd2cb1d171..fb8cfb36353 100644 --- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahHeuristics.hpp +++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahHeuristics.hpp @@ -218,7 +218,7 @@ public: virtual void record_success_concurrent(); - virtual void record_success_degenerated(); + virtual void record_degenerated(); virtual void record_success_full(); diff --git a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahOldHeuristics.cpp b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahOldHeuristics.cpp index 8bf068df0a8..029a4dd98fb 100644 --- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahOldHeuristics.cpp +++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahOldHeuristics.cpp @@ -766,10 +766,10 @@ void ShenandoahOldHeuristics::record_success_concurrent() { this->ShenandoahHeuristics::record_success_concurrent(); } -void ShenandoahOldHeuristics::record_success_degenerated() { +void ShenandoahOldHeuristics::record_degenerated() { // Forget any triggers that occurred while OLD GC was ongoing. If we really need to start another, it will retrigger. clear_triggers(); - this->ShenandoahHeuristics::record_success_degenerated(); + this->ShenandoahHeuristics::record_degenerated(); } void ShenandoahOldHeuristics::record_success_full() { diff --git a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp index 288d3d68e56..f38194c1ee7 100644 --- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp +++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp @@ -201,7 +201,7 @@ public: void record_success_concurrent() override; - void record_success_degenerated() override; + void record_degenerated() override; void record_success_full() override; diff --git a/src/hotspot/share/gc/shenandoah/shenandoahDegeneratedGC.cpp b/src/hotspot/share/gc/shenandoah/shenandoahDegeneratedGC.cpp index cd079d29afe..333bdbc6e72 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahDegeneratedGC.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahDegeneratedGC.cpp @@ -313,8 +313,12 @@ void ShenandoahDegenGC::op_degenerated() { policy->record_degenerated(_generation->is_young(), _abbreviated, progress); if (progress) { heap->notify_gc_progress(); + _generation->heuristics()->record_degenerated(); } else if (!heap->mode()->is_generational() || policy->generational_should_upgrade_degenerated_gc()) { + // Upgrade to full GC, register full-GC impact on heuristics. op_degenerated_futile(); + } else { + _generation->heuristics()->record_degenerated(); } } diff --git a/src/hotspot/share/runtime/prefetch.hpp b/src/hotspot/share/metaprogramming/dependentAlwaysFalse.hpp similarity index 54% rename from src/hotspot/share/runtime/prefetch.hpp rename to src/hotspot/share/metaprogramming/dependentAlwaysFalse.hpp index 601337c14af..b1f9d89df11 100644 --- a/src/hotspot/share/runtime/prefetch.hpp +++ b/src/hotspot/share/metaprogramming/dependentAlwaysFalse.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -22,24 +22,15 @@ * */ -#ifndef SHARE_RUNTIME_PREFETCH_HPP -#define SHARE_RUNTIME_PREFETCH_HPP +#ifndef SHARE_METAPROGRAMMING_DEPENDENTALWAYSFALSE_HPP +#define SHARE_METAPROGRAMMING_DEPENDENTALWAYSFALSE_HPP -#include "memory/allStatic.hpp" +// This provides a workaround for static_assert(false) in discarded or +// otherwise uninstantiated places. Instead use +// static_assert(DependentAlwaysFalse, "...") +// See http://wg21.link/p2593r1. Some, but not all, compiler versions we're +// using have implemented that change as a DR: +// https://cplusplus.github.io/CWG/issues/2518.html +template inline constexpr bool DependentAlwaysFalse = false; -// If calls to prefetch methods are in a loop, the loop should be cloned -// such that if Prefetch{Scan,Copy}Interval and/or PrefetchFieldInterval -// say not to do prefetching, these methods aren't called. At the very -// least, they take up a memory issue slot. They should be implemented -// as inline assembly code: doing an actual call isn't worth the cost. - -class Prefetch : AllStatic { - public: - // Prefetch anticipating read; must not fault, semantically a no-op - static void read(const void* loc, intx interval); - - // Prefetch anticipating write; must not fault, semantically a no-op - static void write(void* loc, intx interval); -}; - -#endif // SHARE_RUNTIME_PREFETCH_HPP +#endif // SHARE_METAPROGRAMMING_DEPENDENTALWAYSFALSE_HPP diff --git a/src/hotspot/share/opto/c2_globals.hpp b/src/hotspot/share/opto/c2_globals.hpp index 7fa3ca638c2..f470049bf7e 100644 --- a/src/hotspot/share/opto/c2_globals.hpp +++ b/src/hotspot/share/opto/c2_globals.hpp @@ -675,9 +675,6 @@ product(bool, PrintIntrinsics, false, DIAGNOSTIC, \ "prints attempted and successful inlining of intrinsics") \ \ - develop(bool, VerifyIntrinsicChecks, false, \ - "Verify in intrinsic that Java level checks work as expected") \ - \ develop(bool, StressReflectiveCode, false, \ "Use inexact types at allocations, etc., to test reflection") \ \ diff --git a/src/hotspot/share/opto/callGenerator.cpp b/src/hotspot/share/opto/callGenerator.cpp index db03dd9d80c..1465da02ac8 100644 --- a/src/hotspot/share/opto/callGenerator.cpp +++ b/src/hotspot/share/opto/callGenerator.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2026, 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 @@ -418,7 +418,8 @@ bool LateInlineMHCallGenerator::do_late_inline_check(Compile* C, JVMState* jvms) C->inline_printer()->record(cg->method(), call_node()->jvms(), InliningResult::FAILURE, "late method handle call resolution"); } - assert(!cg->is_late_inline() || cg->is_mh_late_inline() || AlwaysIncrementalInline || StressIncrementalInlining, "we're doing late inlining"); + assert(!cg->is_late_inline() || cg->is_mh_late_inline() || cg->is_virtual_late_inline() || + AlwaysIncrementalInline || StressIncrementalInlining, "we're doing late inlining"); _inline_cg = cg; return true; } else { diff --git a/src/hotspot/share/opto/callnode.cpp b/src/hotspot/share/opto/callnode.cpp index 4cf72fbde4b..fac8596173f 100644 --- a/src/hotspot/share/opto/callnode.cpp +++ b/src/hotspot/share/opto/callnode.cpp @@ -1031,6 +1031,15 @@ bool CallNode::is_call_to_arraycopystub() const { return false; } +bool CallNode::is_call_to_multianewarray_stub() const { + if (_name != nullptr && + strstr(_name, "multianewarray") != nullptr && + strstr(_name, "C2 runtime") != nullptr) { + return true; + } + return false; +} + //============================================================================= uint CallJavaNode::size_of() const { return sizeof(*this); } bool CallJavaNode::cmp( const Node &n ) const { diff --git a/src/hotspot/share/opto/callnode.hpp b/src/hotspot/share/opto/callnode.hpp index de4b8941359..0bb064efc43 100644 --- a/src/hotspot/share/opto/callnode.hpp +++ b/src/hotspot/share/opto/callnode.hpp @@ -758,6 +758,7 @@ public: virtual uint match_edge(uint idx) const; bool is_call_to_arraycopystub() const; + bool is_call_to_multianewarray_stub() const; virtual void copy_call_debug_info(PhaseIterGVN* phase, SafePointNode* sfpt) {} diff --git a/src/hotspot/share/opto/escape.cpp b/src/hotspot/share/opto/escape.cpp index b067d93176a..7b5c3855a9e 100644 --- a/src/hotspot/share/opto/escape.cpp +++ b/src/hotspot/share/opto/escape.cpp @@ -2066,8 +2066,7 @@ void ConnectionGraph::add_call_node(CallNode* call) { // Use bytecode estimator to record whether the call's return value escapes. ciMethod* meth = call->as_CallJava()->method(); if (meth == nullptr) { - const char* name = call->as_CallStaticJava()->_name; - assert(strncmp(name, "C2 Runtime multianewarray", 25) == 0, "TODO: add failed case check"); + assert(call->as_CallStaticJava()->is_call_to_multianewarray_stub(), "TODO: add failed case check"); // Returns a newly allocated non-escaped object. add_java_object(call, PointsToNode::NoEscape); set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of multinewarray")); @@ -2775,8 +2774,7 @@ int ConnectionGraph::find_init_values_phantom(JavaObjectNode* pta) { assert(pta->arraycopy_dst() || alloc->as_CallStaticJava(), "sanity"); #ifdef ASSERT if (!pta->arraycopy_dst() && alloc->as_CallStaticJava()->method() == nullptr) { - const char* name = alloc->as_CallStaticJava()->_name; - assert(strncmp(name, "C2 Runtime multianewarray", 25) == 0, "sanity"); + assert(alloc->as_CallStaticJava()->is_call_to_multianewarray_stub(), "sanity"); } #endif // Non-escaped allocation returned from Java or runtime call have unknown values in fields. diff --git a/src/hotspot/share/opto/library_call.cpp b/src/hotspot/share/opto/library_call.cpp index a057f66a989..2c2a7c020b8 100644 --- a/src/hotspot/share/opto/library_call.cpp +++ b/src/hotspot/share/opto/library_call.cpp @@ -940,11 +940,7 @@ inline Node* LibraryCallKit::generate_limit_guard(Node* offset, } // Emit range checks for the given String.value byte array -void LibraryCallKit::generate_string_range_check(Node* array, - Node* offset, - Node* count, - bool char_count, - bool halt_on_oob) { +void LibraryCallKit::generate_string_range_check(Node* array, Node* offset, Node* count, bool char_count) { if (stopped()) { return; // already stopped } @@ -962,17 +958,10 @@ void LibraryCallKit::generate_string_range_check(Node* array, generate_limit_guard(offset, count, load_array_length(array), bailout); if (bailout->req() > 1) { - if (halt_on_oob) { - bailout = _gvn.transform(bailout)->as_Region(); - Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr)); - Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic")); - C->root()->add_req(halt); - } else { - PreserveJVMState pjvms(this); - set_control(_gvn.transform(bailout)); - uncommon_trap(Deoptimization::Reason_intrinsic, - Deoptimization::Action_maybe_recompile); - } + PreserveJVMState pjvms(this); + set_control(_gvn.transform(bailout)); + uncommon_trap(Deoptimization::Reason_intrinsic, + Deoptimization::Action_maybe_recompile); } } @@ -1130,7 +1119,6 @@ bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) { //------------------------------inline_countPositives------------------------------ -// int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len) bool LibraryCallKit::inline_countPositives() { if (too_many_traps(Deoptimization::Reason_intrinsic)) { return false; @@ -1142,14 +1130,13 @@ bool LibraryCallKit::inline_countPositives() { Node* offset = argument(1); Node* len = argument(2); - if (VerifyIntrinsicChecks) { - ba = must_be_not_null(ba, true); - generate_string_range_check(ba, offset, len, false, true); - if (stopped()) { - return true; - } - } + ba = must_be_not_null(ba, true); + // Range checks + generate_string_range_check(ba, offset, len, false); + if (stopped()) { + return true; + } Node* ba_start = array_element_address(ba, offset, T_BYTE); Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len); set_result(_gvn.transform(result)); @@ -6184,9 +6171,6 @@ CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* no } //-------------inline_encodeISOArray----------------------------------- -// int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len) -// int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len) -// int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len) // encode char[] to byte[] in ISO_8859_1 or ASCII bool LibraryCallKit::inline_encodeISOArray(bool ascii) { assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters"); @@ -6197,14 +6181,8 @@ bool LibraryCallKit::inline_encodeISOArray(bool ascii) { Node *dst_offset = argument(3); Node *length = argument(4); - // Cast source & target arrays to not-null - if (VerifyIntrinsicChecks) { - src = must_be_not_null(src, true); - dst = must_be_not_null(dst, true); - if (stopped()) { - return true; - } - } + src = must_be_not_null(src, true); + dst = must_be_not_null(dst, true); const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr(); const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr(); @@ -6221,15 +6199,6 @@ bool LibraryCallKit::inline_encodeISOArray(bool ascii) { return false; } - // Check source & target bounds - if (VerifyIntrinsicChecks) { - generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, true); - generate_string_range_check(dst, dst_offset, length, false, true); - if (stopped()) { - return true; - } - } - Node* src_start = array_element_address(src, src_offset, T_CHAR); Node* dst_start = array_element_address(dst, dst_offset, dst_elem); // 'src_start' points to src array + scaled offset diff --git a/src/hotspot/share/opto/library_call.hpp b/src/hotspot/share/opto/library_call.hpp index bfe29814dec..00ba4c795f1 100644 --- a/src/hotspot/share/opto/library_call.hpp +++ b/src/hotspot/share/opto/library_call.hpp @@ -163,8 +163,7 @@ class LibraryCallKit : public GraphKit { Node* array_length, RegionNode* region); void generate_string_range_check(Node* array, Node* offset, - Node* length, bool char_count, - bool halt_on_oob = false); + Node* length, bool char_count); Node* current_thread_helper(Node* &tls_output, ByteSize handle_offset, bool is_immutable); Node* generate_current_thread(Node* &tls_output); diff --git a/src/hotspot/share/opto/superword.cpp b/src/hotspot/share/opto/superword.cpp index 35b46d22732..31cc8fa0460 100644 --- a/src/hotspot/share/opto/superword.cpp +++ b/src/hotspot/share/opto/superword.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2026, 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 @@ -2482,6 +2482,11 @@ static bool can_subword_truncate(Node* in, const Type* type) { return false; } + // Since casts specifically change the type of a node, stay on the safe side and do not truncate them. + if (in->is_ConstraintCast()) { + return false; + } + // Cannot be truncated: switch (opc) { case Op_AbsI: diff --git a/src/hotspot/share/opto/vectorization.cpp b/src/hotspot/share/opto/vectorization.cpp index f81ee1b7ddb..1755b0453eb 100644 --- a/src/hotspot/share/opto/vectorization.cpp +++ b/src/hotspot/share/opto/vectorization.cpp @@ -187,7 +187,10 @@ VStatus VLoopAnalyzer::setup_submodules_helper() { return body_status; } - _memory_slices.find_memory_slices(); + VStatus slices_status = _memory_slices.find_memory_slices(); + if (!slices_status.is_success()) { + return slices_status; + } // If there is no memory slice detected, it means there is no store. // If there is no reduction and no store, then we give up, because @@ -207,9 +210,11 @@ VStatus VLoopAnalyzer::setup_submodules_helper() { } // There are 2 kinds of slices: -// - No memory phi: only loads. All have the same input memory state from before the loop. +// - No memory phi: only loads. +// - Usually, all loads have the same input memory state from before the loop. +// - Only rarely this is not the case, and we just bail out for now. // - With memory phi. Chain of memory operations inside the loop. -void VLoopMemorySlices::find_memory_slices() { +VStatus VLoopMemorySlices::find_memory_slices() { Compile* C = _vloop.phase()->C; // We iterate over the body, which is topologically sorted. Hence, if there is a phi // in a slice, we will find it first, and the loads and stores afterwards. @@ -228,8 +233,15 @@ void VLoopMemorySlices::find_memory_slices() { PhiNode* head = _heads.at(alias_idx); if (head == nullptr) { // We did not find a phi on this slice yet -> must be a slice with only loads. - assert(_inputs.at(alias_idx) == nullptr || _inputs.at(alias_idx) == load->in(1), - "not yet touched or the same input"); + // For now, we can only handle slices with a single memory input before the loop, + // so if we find multiple, we bail out of auto vectorization. If this becomes + // too restrictive in the fututure, we could consider tracking multiple inputs. + // Different memory inputs can for example happen if one load has its memory state + // optimized, and the other load fails to have it optimized, for example because + // it does not end up on the IGVN worklist any more. + if (_inputs.at(alias_idx) != nullptr && _inputs.at(alias_idx) != load->in(1)) { + return VStatus::make_failure(FAILURE_DIFFERENT_MEMORY_INPUT); + } _inputs.at_put(alias_idx, load->in(1)); } // else: the load belongs to a slice with a phi that already set heads and inputs. #ifdef ASSERT @@ -243,6 +255,7 @@ void VLoopMemorySlices::find_memory_slices() { } } NOT_PRODUCT( if (_vloop.is_trace_memory_slices()) { print(); } ) + return VStatus::make_success(); } #ifndef PRODUCT diff --git a/src/hotspot/share/opto/vectorization.hpp b/src/hotspot/share/opto/vectorization.hpp index 9308712f78a..b187435c04d 100644 --- a/src/hotspot/share/opto/vectorization.hpp +++ b/src/hotspot/share/opto/vectorization.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023, Arm Limited. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -504,6 +504,8 @@ private: // class VLoopMemorySlices : public StackObj { private: + static constexpr char const* FAILURE_DIFFERENT_MEMORY_INPUT = "Load only slice has multiple memory inputs"; + const VLoop& _vloop; const VLoopBody& _body; @@ -521,7 +523,7 @@ public: const GrowableArray& inputs() const { return _inputs; } const GrowableArray& heads() const { return _heads; } - void find_memory_slices(); + VStatus find_memory_slices(); void get_slice_in_reverse_order(PhiNode* head, MemNode* tail, GrowableArray& slice) const; bool same_memory_slice(MemNode* m1, MemNode* m2) const; diff --git a/src/hotspot/share/runtime/atomic.hpp b/src/hotspot/share/runtime/atomic.hpp index 0c335913b5c..f708e9c18ca 100644 --- a/src/hotspot/share/runtime/atomic.hpp +++ b/src/hotspot/share/runtime/atomic.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ #define SHARE_RUNTIME_ATOMIC_HPP #include "cppstdlib/type_traits.hpp" +#include "metaprogramming/dependentAlwaysFalse.hpp" #include "metaprogramming/primitiveConversions.hpp" #include "runtime/atomicAccess.hpp" #include "utilities/globalDefinitions.hpp" @@ -74,6 +75,7 @@ // v.release_store(x) -> void // v.release_store_fence(x) -> void // v.compare_exchange(x, y [, o]) -> T +// v.compare_set(x, y [, o]) -> bool // v.exchange(x [, o]) -> T // // (2) All atomic types are default constructible. @@ -266,6 +268,11 @@ public: return AtomicAccess::cmpxchg(value_ptr(), compare_value, new_value, order); } + bool compare_set(T compare_value, T new_value, + atomic_memory_order order = memory_order_conservative) { + return compare_exchange(compare_value, new_value, order) == compare_value; + } + T exchange(T new_value, atomic_memory_order order = memory_order_conservative) { return AtomicAccess::xchg(this->value_ptr(), new_value, order); @@ -478,6 +485,13 @@ public: order)); } + bool compare_set(T compare_value, T new_value, + atomic_memory_order order = memory_order_conservative) { + return _value.compare_set(decay(compare_value), + decay(new_value), + order); + } + T exchange(T new_value, atomic_memory_order order = memory_order_conservative) { return recover(_value.exchange(decay(new_value), order)); } diff --git a/src/hotspot/share/runtime/prefetch.inline.hpp b/src/hotspot/share/runtime/prefetch.inline.hpp index 4cc1d93f613..18630f71a62 100644 --- a/src/hotspot/share/runtime/prefetch.inline.hpp +++ b/src/hotspot/share/runtime/prefetch.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, 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,9 +25,24 @@ #ifndef SHARE_RUNTIME_PREFETCH_INLINE_HPP #define SHARE_RUNTIME_PREFETCH_INLINE_HPP -#include "runtime/prefetch.hpp" - +#include "memory/allStatic.hpp" #include "utilities/macros.hpp" + +// If calls to prefetch methods are in a loop, the loop should be cloned +// such that if Prefetch{Scan,Copy}Interval and/or PrefetchFieldInterval +// say not to do prefetching, these methods aren't called. At the very +// least, they take up a memory issue slot. They should be implemented +// as inline assembly code: doing an actual call isn't worth the cost. + +class Prefetch : AllStatic { + public: + // Prefetch anticipating read; must not fault, semantically a no-op + static void read(const void* loc, intx interval); + + // Prefetch anticipating write; must not fault, semantically a no-op + static void write(void* loc, intx interval); +}; + #include OS_CPU_HEADER_INLINE(prefetch) #endif // SHARE_RUNTIME_PREFETCH_INLINE_HPP diff --git a/src/hotspot/share/runtime/stubDeclarations.hpp b/src/hotspot/share/runtime/stubDeclarations.hpp index f9080364dc4..c478eda3e7c 100644 --- a/src/hotspot/share/runtime/stubDeclarations.hpp +++ b/src/hotspot/share/runtime/stubDeclarations.hpp @@ -191,8 +191,7 @@ // // C2 stub blob/field names // -// C2 stubs are provided with names in the format "C2 Runtime -// _blob". +// C2 stubs are provided with names in the format "_blob (C2 runtime)". // // A stub creation method OptoRuntime::generate(ciEnv* env) is // generated which invokes the C2 compiler to generate each stub in diff --git a/src/hotspot/share/runtime/stubInfo.cpp b/src/hotspot/share/runtime/stubInfo.cpp index 47a31fe7967..ee90631145a 100644 --- a/src/hotspot/share/runtime/stubInfo.cpp +++ b/src/hotspot/share/runtime/stubInfo.cpp @@ -479,7 +479,7 @@ void StubInfo::process_stubgen_entry(StubGroup& group_cursor, #define PROCESS_SHARED_BLOB(name, type) \ process_shared_blob(_group_cursor, _blob_cursor, \ _stub_cursor, _entry_cursor, \ - "Shared Runtime " # name "_blob", \ + #name "_blob (shared runtime)", \ BlobId:: JOIN3(shared, name, id), \ StubId:: JOIN3(shared, name, id), \ EntryId:: JOIN3(shared, name, id), \ @@ -488,7 +488,7 @@ void StubInfo::process_stubgen_entry(StubGroup& group_cursor, #define PROCESS_C1_BLOB(name) \ process_c1_blob(_group_cursor, _blob_cursor, \ _stub_cursor, _entry_cursor, \ - "C1 Runtime " # name "_blob", \ + #name "_blob (C1 runtime)", \ BlobId:: JOIN3(c1, name, id), \ StubId:: JOIN3(c1, name, id), \ EntryId:: JOIN3(c1, name, id)); \ @@ -496,7 +496,7 @@ void StubInfo::process_stubgen_entry(StubGroup& group_cursor, #define PROCESS_C2_BLOB(name, type) \ process_c2_blob(_group_cursor, _blob_cursor, \ _stub_cursor, _entry_cursor, \ - "C2 Runtime " # name "_blob", \ + #name "_blob (C2 runtime)", \ BlobId:: JOIN3(c2, name, id), \ StubId:: JOIN3(c2, name, id), \ EntryId:: JOIN3(c2, name, id)); \ @@ -504,7 +504,7 @@ void StubInfo::process_stubgen_entry(StubGroup& group_cursor, #define PROCESS_C2_STUB(name, fancy_jump, pass_tls, return_pc) \ process_c2_blob(_group_cursor, _blob_cursor, \ _stub_cursor, _entry_cursor, \ - "C2 Runtime " # name "_blob", \ + #name "_blob (C2 runtime)", \ BlobId:: JOIN3(c2, name, id), \ StubId:: JOIN3(c2, name, id), \ EntryId:: JOIN3(c2, name, id)); \ @@ -512,20 +512,20 @@ void StubInfo::process_stubgen_entry(StubGroup& group_cursor, #define PROCESS_STUBGEN_BLOB(blob) \ process_stubgen_blob(_group_cursor, _blob_cursor, \ _stub_cursor, _entry_cursor, \ - "Stub Generator " # blob "_blob", \ + #blob "_blob (stub gen)", \ BlobId:: JOIN3(stubgen, blob, id)); \ #define PROCESS_STUBGEN_STUB(blob, stub) \ process_stubgen_stub(_group_cursor, _blob_cursor, \ _stub_cursor, _entry_cursor, \ - "Stub Generator " # stub "_stub", \ + #stub "_stub (stub gen)", \ BlobId:: JOIN3(stubgen, blob, id), \ StubId:: JOIN3(stubgen, stub, id)); \ #define PROCESS_STUBGEN_ENTRY(blob, stub, field_name, getter_name) \ process_stubgen_entry(_group_cursor, _blob_cursor, \ _stub_cursor, _entry_cursor, \ - "Stub Generator " # field_name "_entry", \ + #field_name "_entry (stub gen)", \ BlobId:: JOIN3(stubgen, blob, id), \ StubId:: JOIN3(stubgen, stub, id), \ EntryId:: JOIN3(stubgen, field_name, id), \ @@ -535,7 +535,7 @@ void StubInfo::process_stubgen_entry(StubGroup& group_cursor, init_funcion) \ process_stubgen_entry(_group_cursor, _blob_cursor, \ _stub_cursor, _entry_cursor, \ - "Stub Generator " # field_name "_entry", \ + #field_name "_entry (stub gen)", \ BlobId:: JOIN3(stubgen, blob, id), \ StubId:: JOIN3(stubgen, stub, id), \ EntryId:: JOIN3(stubgen, field_name, id), \ @@ -545,7 +545,7 @@ void StubInfo::process_stubgen_entry(StubGroup& group_cursor, count) \ process_stubgen_entry(_group_cursor, _blob_cursor, \ _stub_cursor, _entry_cursor, \ - "Stub Generator " # field_name "_entry", \ + #field_name "_entry (stub gen)", \ BlobId:: JOIN3(stubgen, blob, id), \ StubId:: JOIN3(stubgen, stub, id), \ EntryId:: JOIN3(stubgen, field_name, id), \ @@ -567,7 +567,7 @@ void StubInfo::process_stubgen_entry(StubGroup& group_cursor, init_function) \ process_stubgen_entry(_group_cursor, _blob_cursor, \ _stub_cursor, _entry_cursor, \ - "Stub Generator " # arch_name "_" # field_name "_entry", \ + #arch_name "_" # field_name "_entry (stub gen)",\ BlobId:: JOIN3(stubgen, blob, id), \ StubId:: JOIN3(stubgen, stub, id), \ EntryId:: JOIN4(stubgen, arch_name, \ diff --git a/src/hotspot/share/utilities/byteswap.hpp b/src/hotspot/share/utilities/byteswap.hpp index 371095bce49..9fc367c784e 100644 --- a/src/hotspot/share/utilities/byteswap.hpp +++ b/src/hotspot/share/utilities/byteswap.hpp @@ -1,4 +1,5 @@ /* + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023, 2024, Google and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -141,7 +142,7 @@ struct ByteswapImpl : public ByteswapFallbackImpl {}; *****************************************************************************/ #elif defined(TARGET_COMPILER_visCPP) -#include +#include "cppstdlib/cstdlib.hpp" #pragma intrinsic(_byteswap_ushort) #pragma intrinsic(_byteswap_ulong) diff --git a/src/hotspot/share/utilities/concurrentHashTable.hpp b/src/hotspot/share/utilities/concurrentHashTable.hpp index 1a50ecabc3e..d2317847307 100644 --- a/src/hotspot/share/utilities/concurrentHashTable.hpp +++ b/src/hotspot/share/utilities/concurrentHashTable.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, 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 @@ -70,7 +70,7 @@ class ConcurrentHashTable : public CHeapObj { class Node { private: DEBUG_ONLY(size_t _saved_hash); - Node * volatile _next; + Atomic _next; VALUE _value; public: Node(const VALUE& value, Node* next = nullptr) @@ -80,8 +80,8 @@ class ConcurrentHashTable : public CHeapObj { } Node* next() const; - void set_next(Node* node) { _next = node; } - Node* const volatile * next_ptr() { return &_next; } + void set_next(Node* node) { _next.store_relaxed(node); } + const Atomic* next_ptr() const { return &_next; } #ifdef ASSERT size_t saved_hash() const { return _saved_hash; } void set_saved_hash(size_t hash) { _saved_hash = hash; } @@ -123,7 +123,7 @@ class ConcurrentHashTable : public CHeapObj { // unlocked -> locked -> redirect // Locked state only applies to an updater. // Reader only check for redirect. - Node * volatile _first; + Atomic _first; static const uintptr_t STATE_LOCK_BIT = 0x1; static const uintptr_t STATE_REDIRECT_BIT = 0x2; @@ -157,20 +157,25 @@ class ConcurrentHashTable : public CHeapObj { // A bucket is only one pointer with the embedded state. Bucket() : _first(nullptr) {}; + NONCOPYABLE(Bucket); + + // Copy bucket's first entry to this. + void assign(const Bucket& bucket); + // Get the first pointer unmasked. Node* first() const; // Get a pointer to the const first pointer. Do not deference this // pointer, the pointer pointed to _may_ contain an embedded state. Such // pointer should only be used as input to release_assign_node_ptr. - Node* const volatile * first_ptr() { return &_first; } + const Atomic* first_ptr() const { return &_first; } // This is the only place where a pointer to a Node pointer that potentially // is _first should be changed. Otherwise we destroy the embedded state. We // only give out pointer to const Node pointer to avoid accidental // assignment, thus here we must cast const part away. Method is not static // due to an assert. - void release_assign_node_ptr(Node* const volatile * dst, Node* node) const; + void release_assign_node_ptr(const Atomic* dst, Node* node) const; // This method assigns this buckets last Node next ptr to input Node. void release_assign_last_node_next(Node* node); diff --git a/src/hotspot/share/utilities/concurrentHashTable.inline.hpp b/src/hotspot/share/utilities/concurrentHashTable.inline.hpp index b96a487324c..62d2dd29dab 100644 --- a/src/hotspot/share/utilities/concurrentHashTable.inline.hpp +++ b/src/hotspot/share/utilities/concurrentHashTable.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, 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 @@ -63,7 +63,7 @@ inline typename ConcurrentHashTable::Node* ConcurrentHashTable:: Node::next() const { - return AtomicAccess::load_acquire(&_next); + return _next.load_acquire(); } // Bucket @@ -72,19 +72,26 @@ inline typename ConcurrentHashTable::Node* ConcurrentHashTable:: Bucket::first_raw() const { - return AtomicAccess::load_acquire(&_first); + return _first.load_acquire(); } template inline void ConcurrentHashTable:: Bucket::release_assign_node_ptr( - typename ConcurrentHashTable::Node* const volatile * dst, + const Atomic::Node*>* dst, typename ConcurrentHashTable::Node* node) const { // Due to this assert this methods is not static. assert(is_locked(), "Must be locked."); - Node** tmp = (Node**)dst; - AtomicAccess::release_store(tmp, clear_set_state(node, *dst)); + Atomic* tmp = const_cast*>(dst); + tmp->release_store(clear_set_state(node, dst->load_relaxed())); +} + +template +inline void ConcurrentHashTable:: + Bucket::assign(const Bucket& bucket) +{ + _first.store_relaxed(bucket._first.load_relaxed()); } template @@ -93,7 +100,7 @@ ConcurrentHashTable:: Bucket::first() const { // We strip the states bit before returning the ptr. - return clear_state(AtomicAccess::load_acquire(&_first)); + return clear_state(_first.load_acquire()); } template @@ -134,9 +141,9 @@ inline void ConcurrentHashTable:: typename ConcurrentHashTable::Node* node) { assert(is_locked(), "Must be locked."); - Node* const volatile * ret = first_ptr(); - while (clear_state(*ret) != nullptr) { - ret = clear_state(*ret)->next_ptr(); + const Atomic* ret = first_ptr(); + while (clear_state(ret->load_relaxed()) != nullptr) { + ret = clear_state(ret->load_relaxed())->next_ptr(); } release_assign_node_ptr(ret, node); } @@ -150,7 +157,7 @@ inline bool ConcurrentHashTable:: if (is_locked()) { return false; } - if (AtomicAccess::cmpxchg(&_first, expect, node) == expect) { + if (_first.compare_set(expect, node)) { return true; } return false; @@ -165,7 +172,7 @@ inline bool ConcurrentHashTable:: } // We will expect a clean first pointer. Node* tmp = first(); - if (AtomicAccess::cmpxchg(&_first, tmp, set_state(tmp, STATE_LOCK_BIT)) == tmp) { + if (_first.compare_set(tmp, set_state(tmp, STATE_LOCK_BIT))) { return true; } return false; @@ -178,7 +185,7 @@ inline void ConcurrentHashTable:: assert(is_locked(), "Must be locked."); assert(!have_redirect(), "Unlocking a bucket after it has reached terminal state."); - AtomicAccess::release_store(&_first, clear_state(first())); + _first.release_store(clear_state(first())); } template @@ -186,7 +193,7 @@ inline void ConcurrentHashTable:: Bucket::redirect() { assert(is_locked(), "Must be locked."); - AtomicAccess::release_store(&_first, set_state(_first, STATE_REDIRECT_BIT)); + _first.release_store(set_state(_first.load_relaxed(), STATE_REDIRECT_BIT)); } // InternalTable @@ -413,8 +420,8 @@ inline void ConcurrentHashTable:: bucket->lock(); size_t odd_index = even_index + _table->_size; - _new_table->get_buckets()[even_index] = *bucket; - _new_table->get_buckets()[odd_index] = *bucket; + _new_table->get_buckets()[even_index].assign(*bucket); + _new_table->get_buckets()[odd_index].assign(*bucket); // Moves lockers go to new table, where they will wait until unlock() below. bucket->redirect(); /* Must release stores above */ @@ -445,7 +452,7 @@ inline bool ConcurrentHashTable:: { Bucket* bucket = get_bucket_locked(thread, lookup_f.get_hash()); assert(bucket->is_locked(), "Must be locked."); - Node* const volatile * rem_n_prev = bucket->first_ptr(); + const Atomic* rem_n_prev = bucket->first_ptr(); Node* rem_n = bucket->first(); while (rem_n != nullptr) { if (lookup_f.equals(rem_n->value())) { @@ -534,7 +541,7 @@ inline void ConcurrentHashTable:: size_t dels = 0; Node* ndel[StackBufferSize]; - Node* const volatile * rem_n_prev = bucket->first_ptr(); + const Atomic* rem_n_prev = bucket->first_ptr(); Node* rem_n = bucket->first(); while (rem_n != nullptr) { if (lookup_f.is_dead(rem_n->value())) { @@ -643,8 +650,8 @@ inline bool ConcurrentHashTable:: return false; } Node* delete_me = nullptr; - Node* const volatile * even = new_table->get_bucket(even_index)->first_ptr(); - Node* const volatile * odd = new_table->get_bucket(odd_index)->first_ptr(); + const Atomic* even = new_table->get_bucket(even_index)->first_ptr(); + const Atomic* odd = new_table->get_bucket(odd_index)->first_ptr(); while (aux != nullptr) { bool dead_hash = false; size_t aux_hash = CONFIG::get_hash(*aux->value(), &dead_hash); @@ -742,11 +749,11 @@ inline void ConcurrentHashTable:: b_old_even->lock(); b_old_odd->lock(); - _new_table->get_buckets()[bucket_it] = *b_old_even; + _new_table->get_buckets()[bucket_it].assign(*b_old_even); // Put chains together. _new_table->get_bucket(bucket_it)-> - release_assign_last_node_next(*(b_old_odd->first_ptr())); + release_assign_last_node_next(b_old_odd->first_ptr()->load_relaxed()); b_old_even->redirect(); b_old_odd->redirect(); @@ -981,7 +988,7 @@ inline size_t ConcurrentHashTable:: size_t num_del, Node** ndel, GrowableArrayCHeap& extra) { size_t dels = 0; - Node* const volatile * rem_n_prev = bucket->first_ptr(); + const Atomic* rem_n_prev = bucket->first_ptr(); Node* rem_n = bucket->first(); while (rem_n != nullptr) { if (eval_f(rem_n->value())) { diff --git a/src/hotspot/share/utilities/forbiddenFunctions.hpp b/src/hotspot/share/utilities/forbiddenFunctions.hpp index 47becd7b4c7..9d1b88e6233 100644 --- a/src/hotspot/share/utilities/forbiddenFunctions.hpp +++ b/src/hotspot/share/utilities/forbiddenFunctions.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2026, 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,12 +32,6 @@ #include #include -// Workaround for noreturn functions: exit, _exit, _Exit - see the clang -// definition of FORBIDDEN_FUNCTION_NORETURN_ATTRIBUTE. -#ifdef __clang__ -#include -#endif - #ifdef _WINDOWS #include "forbiddenFunctions_windows.hpp" #else @@ -49,12 +43,6 @@ // or have security concerns, either with preferred alternatives, or to be // avoided entirely. -FORBID_IMPORTED_NORETURN_C_FUNCTION(void exit(int), noexcept, "use os::exit") -FORBID_IMPORTED_NORETURN_C_FUNCTION(void _Exit(int), noexcept, "use os::exit") - -// Windows puts _exit in , POSIX in . -FORBID_IMPORTED_NORETURN_C_FUNCTION(void _exit(int), /* not noexcept */, "use os::exit") - FORBID_IMPORTED_C_FUNCTION(char* strerror(int), noexcept, "use os::strerror"); FORBID_IMPORTED_C_FUNCTION(char* strtok(char*, const char*), noexcept, "use strtok_r"); @@ -70,13 +58,8 @@ FORBID_C_FUNCTION(int vsprintf(char*, const char*, va_list), noexcept, "use os:: FORBID_C_FUNCTION(int vsnprintf(char*, size_t, const char*, va_list), noexcept, "use os::vsnprintf"); PRAGMA_DIAG_POP -// All of the following functions return raw C-heap pointers (sometimes as an -// option, e.g. realpath or getwd) or, in case of free(), take raw C-heap -// pointers. We generally want allocation to be done through NMT. -FORBID_IMPORTED_C_FUNCTION(void* malloc(size_t size), noexcept, "use os::malloc"); -FORBID_IMPORTED_C_FUNCTION(void free(void *ptr), noexcept, "use os::free"); -FORBID_IMPORTED_C_FUNCTION(void* calloc(size_t nmemb, size_t size), noexcept, "use os::malloc and zero out manually"); -FORBID_IMPORTED_C_FUNCTION(void* realloc(void *ptr, size_t size), noexcept, "use os::realloc"); +// All of the following functions return raw C-heap pointers. We generally +// want allocation to be done through NMT. FORBID_IMPORTED_C_FUNCTION(char* strdup(const char *s), noexcept, "use os::strdup"); FORBID_IMPORTED_C_FUNCTION(wchar_t* wcsdup(const wchar_t *s), noexcept, "don't use"); diff --git a/src/hotspot/share/utilities/globalDefinitions.hpp b/src/hotspot/share/utilities/globalDefinitions.hpp index 3284fd3bd15..54602297759 100644 --- a/src/hotspot/share/utilities/globalDefinitions.hpp +++ b/src/hotspot/share/utilities/globalDefinitions.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, 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 @@ -1374,14 +1374,6 @@ template int primitive_compare(const K& k0, const K& k1) { template std::add_rvalue_reference_t declval() noexcept; -// This provides a workaround for static_assert(false) in discarded or -// otherwise uninstantiated places. Instead use -// static_assert(DependentAlwaysFalse, "...") -// See http://wg21.link/p2593r1. Some, but not all, compiler versions we're -// using have implemented that change as a DR: -// https://cplusplus.github.io/CWG/issues/2518.html -template inline constexpr bool DependentAlwaysFalse = false; - // Quickly test to make sure IEEE-754 subnormal numbers are correctly // handled. bool IEEE_subnormal_handling_OK(); diff --git a/src/hotspot/share/utilities/globalDefinitions_gcc.hpp b/src/hotspot/share/utilities/globalDefinitions_gcc.hpp index f82f9b1386a..302a62de6c1 100644 --- a/src/hotspot/share/utilities/globalDefinitions_gcc.hpp +++ b/src/hotspot/share/utilities/globalDefinitions_gcc.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2026, 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 @@ -31,6 +31,8 @@ // globally used constants & types, class (forward) // declarations and a few frequently used utility functions. +#include "cppstdlib/cstdlib.hpp" + #include #include #include @@ -44,15 +46,6 @@ #include #include #include -#include -// In stdlib.h on AIX malloc is defined as a macro causing -// compiler errors when resolving them in different depths as it -// happens in the log tags. This avoids the macro. -#if (defined(__VEC__) || defined(__AIXVEC)) && defined(AIX) \ - && defined(__open_xl_version__) && __open_xl_version__ >= 17 - #undef malloc - extern void *malloc(size_t) asm("vec_malloc"); -#endif #include #include #include diff --git a/src/hotspot/share/utilities/globalDefinitions_visCPP.hpp b/src/hotspot/share/utilities/globalDefinitions_visCPP.hpp index b9d25096cd5..dfd6f2f1880 100644 --- a/src/hotspot/share/utilities/globalDefinitions_visCPP.hpp +++ b/src/hotspot/share/utilities/globalDefinitions_visCPP.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, 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 @@ -34,6 +34,8 @@ // Need this on windows to get the math constants (e.g., M_PI). #define _USE_MATH_DEFINES +#include "cppstdlib/cstdlib.hpp" + # include # include # include // for _isnan @@ -45,7 +47,6 @@ # include // for offsetof # include # include -# include # include # include # include diff --git a/src/hotspot/share/utilities/lockFreeStack.hpp b/src/hotspot/share/utilities/lockFreeStack.hpp index 3f63482a268..871e697f404 100644 --- a/src/hotspot/share/utilities/lockFreeStack.hpp +++ b/src/hotspot/share/utilities/lockFreeStack.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ #ifndef SHARE_UTILITIES_LOCKFREESTACK_HPP #define SHARE_UTILITIES_LOCKFREESTACK_HPP +#include "metaprogramming/dependentAlwaysFalse.hpp" #include "runtime/atomic.hpp" #include "runtime/atomicAccess.hpp" #include "utilities/debug.hpp" diff --git a/src/hotspot/share/utilities/parseInteger.hpp b/src/hotspot/share/utilities/parseInteger.hpp index 3e3eafada87..8840275a8cb 100644 --- a/src/hotspot/share/utilities/parseInteger.hpp +++ b/src/hotspot/share/utilities/parseInteger.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2022 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,6 +26,7 @@ #ifndef SHARE_UTILITIES_PARSE_INTEGER_HPP #define SHARE_UTILITIES_PARSE_INTEGER_HPP +#include "cppstdlib/cstdlib.hpp" #include "cppstdlib/limits.hpp" #include "metaprogramming/enableIf.hpp" #include "utilities/debug.hpp" @@ -33,7 +34,6 @@ #include "utilities/macros.hpp" #include -#include // ************************************************************************* // ** Attention compatibility! ** diff --git a/src/hotspot/share/utilities/permitForbiddenFunctions.hpp b/src/hotspot/share/utilities/permitForbiddenFunctions.hpp index 1ba42f8e386..71719ac8a76 100644 --- a/src/hotspot/share/utilities/permitForbiddenFunctions.hpp +++ b/src/hotspot/share/utilities/permitForbiddenFunctions.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2026, 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 @@ #ifndef SHARE_UTILITIES_PERMITFORBIDDENFUNCTIONS_HPP #define SHARE_UTILITIES_PERMITFORBIDDENFUNCTIONS_HPP +#include "cppstdlib/cstdlib.hpp" #include "utilities/compilerWarnings.hpp" #include "utilities/globalDefinitions.hpp" @@ -34,6 +35,9 @@ #include "permitForbiddenFunctions_posix.hpp" #endif +#include +#include + // Provide wrappers for some functions otherwise forbidden from use in HotSpot. // // There may be special circumstances where an otherwise forbidden function @@ -53,7 +57,6 @@ namespace permit_forbidden_function { BEGIN_ALLOW_FORBIDDEN_FUNCTIONS [[noreturn]] inline void exit(int status) { ::exit(status); } -[[noreturn]] inline void _exit(int status) { ::_exit(status); } ATTRIBUTE_PRINTF(3, 0) inline int vsnprintf(char* str, size_t size, const char* format, va_list ap) { diff --git a/src/hotspot/share/utilities/waitBarrier_generic.cpp b/src/hotspot/share/utilities/waitBarrier_generic.cpp index b268b10c757..0892feab699 100644 --- a/src/hotspot/share/utilities/waitBarrier_generic.cpp +++ b/src/hotspot/share/utilities/waitBarrier_generic.cpp @@ -181,7 +181,7 @@ void GenericWaitBarrier::Cell::disarm(int32_t expected_tag) { tag, waiters); int64_t new_state = encode(0, waiters); - if (_state.compare_exchange(state, new_state) == state) { + if (_state.compare_set(state, new_state)) { // Successfully disarmed. break; } @@ -218,7 +218,7 @@ void GenericWaitBarrier::Cell::wait(int32_t expected_tag) { tag, waiters); int64_t new_state = encode(tag, waiters + 1); - if (_state.compare_exchange(state, new_state) == state) { + if (_state.compare_set(state, new_state)) { // Success! Proceed to wait. break; } @@ -247,7 +247,7 @@ void GenericWaitBarrier::Cell::wait(int32_t expected_tag) { tag, waiters); int64_t new_state = encode(tag, waiters - 1); - if (_state.compare_exchange(state, new_state) == state) { + if (_state.compare_set(state, new_state)) { // Success! break; } diff --git a/src/java.base/share/classes/java/lang/Math.java b/src/java.base/share/classes/java/lang/Math.java index 0f39ecf0a8a..55659bed57b 100644 --- a/src/java.base/share/classes/java/lang/Math.java +++ b/src/java.base/share/classes/java/lang/Math.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 2026, 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 @@ -2378,6 +2378,20 @@ public final class Math { */ @IntrinsicCandidate public static double fma(double a, double b, double c) { + // Implementation note: this method is intentionally coded in + // a straightforward manner relying on BigDecimal for the + // heavy-lifting of the numerical computation. It would be + // possible for the computation to be done solely using binary + // floating-point and integer operations, at the cost of more + // complicated logic. Since most processors have hardware + // support for fma and this method is an intrinsic candidate, + // the software implementation below would only be used on + // processors without native fma support (and also possibly on + // processors with native fma support while running in the + // interpreter). Therefore, the direct performance of the code + // is less of a concern than the code's simplicity, + // maintainability, and testability. + /* * Infinity and NaN arithmetic is not quite the same with two * roundings as opposed to just one so the simple expression @@ -2492,6 +2506,8 @@ public final class Math { */ @IntrinsicCandidate public static float fma(float a, float b, float c) { + // See implementation note in fma(double, double, double). + if (Float.isFinite(a) && Float.isFinite(b) && Float.isFinite(c)) { if (a == 0.0 || b == 0.0) { return a * b + c; // Handled signed zero cases diff --git a/src/java.base/share/classes/java/lang/String.java b/src/java.base/share/classes/java/lang/String.java index d7aef113e15..d3eda052740 100644 --- a/src/java.base/share/classes/java/lang/String.java +++ b/src/java.base/share/classes/java/lang/String.java @@ -1111,7 +1111,7 @@ public final class String int sp = 0; int sl = len; while (sp < sl) { - int ret = StringCoding.encodeISOArray(val, sp, dst, dp, len); + int ret = StringCoding.implEncodeISOArray(val, sp, dst, dp, len); sp = sp + ret; dp = dp + ret; if (ret != len) { diff --git a/src/java.base/share/classes/java/lang/StringCoding.java b/src/java.base/share/classes/java/lang/StringCoding.java index 545f216b755..c02af28c37d 100644 --- a/src/java.base/share/classes/java/lang/StringCoding.java +++ b/src/java.base/share/classes/java/lang/StringCoding.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2024, Alibaba Group Holding Limited. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,11 +26,8 @@ package java.lang; -import jdk.internal.util.Preconditions; import jdk.internal.vm.annotation.IntrinsicCandidate; -import java.util.function.BiFunction; - /** * Utility class for string encoding and decoding. */ @@ -41,7 +38,7 @@ class StringCoding { /** * Count the number of leading non-zero ascii chars in the range. */ - static int countNonZeroAscii(String s) { + public static int countNonZeroAscii(String s) { byte[] value = s.value(); if (s.isLatin1()) { return countNonZeroAsciiLatin1(value, 0, value.length); @@ -53,7 +50,7 @@ class StringCoding { /** * Count the number of non-zero ascii chars in the range. */ - private static int countNonZeroAsciiLatin1(byte[] ba, int off, int len) { + public static int countNonZeroAsciiLatin1(byte[] ba, int off, int len) { int limit = off + len; for (int i = off; i < limit; i++) { if (ba[i] <= 0) { @@ -66,7 +63,7 @@ class StringCoding { /** * Count the number of leading non-zero ascii chars in the range. */ - private static int countNonZeroAsciiUTF16(byte[] ba, int off, int strlen) { + public static int countNonZeroAsciiUTF16(byte[] ba, int off, int strlen) { int limit = off + strlen; for (int i = off; i < limit; i++) { char c = StringUTF16.charAt(ba, i); @@ -77,7 +74,7 @@ class StringCoding { return strlen; } - static boolean hasNegatives(byte[] ba, int off, int len) { + public static boolean hasNegatives(byte[] ba, int off, int len) { return countPositives(ba, off, len) != len; } @@ -88,24 +85,9 @@ class StringCoding { * bytes in the range. If there are negative bytes, the implementation must return * a value that is less than or equal to the index of the first negative byte * in the range. - * - * @param ba a byte array - * @param off the index of the first byte to start reading from - * @param len the total number of bytes to read - * @throws NullPointerException if {@code ba} is null - * @throws ArrayIndexOutOfBoundsException if the provided sub-range is - * {@linkplain Preconditions#checkFromIndexSize(int, int, int, BiFunction) out of bounds} */ - static int countPositives(byte[] ba, int off, int len) { - Preconditions.checkFromIndexSize( - off, len, - ba.length, // Implicit null check on `ba` - Preconditions.AIOOBE_FORMATTER); - return countPositives0(ba, off, len); - } - @IntrinsicCandidate - private static int countPositives0(byte[] ba, int off, int len) { + public static int countPositives(byte[] ba, int off, int len) { int limit = off + len; for (int i = off; i < limit; i++) { if (ba[i] < 0) { @@ -115,37 +97,9 @@ class StringCoding { return len; } - /** - * Encodes as many ISO-8859-1 codepoints as possible from the source byte - * array containing characters encoded in UTF-16, into the destination byte - * array, assuming that the encoding is ISO-8859-1 compatible. - * - * @param sa the source byte array containing characters encoded in UTF-16 - * @param sp the index of the character (not byte!) from the source array to start reading from - * @param da the target byte array - * @param dp the index of the target array to start writing to - * @param len the maximum number of characters (not bytes!) to be encoded - * @return the total number of characters (not bytes!) successfully encoded - * @throws NullPointerException if any of the provided arrays is null - */ - static int encodeISOArray(byte[] sa, int sp, - byte[] da, int dp, int len) { - // This method should tolerate invalid arguments, matching the lenient behavior of the VM intrinsic. - // Hence, using operator expressions instead of `Preconditions`, which throw on failure. - int sl; - if ((sp | dp | len) < 0 || - // Halving the length of `sa` to obtain the number of characters: - sp >= (sl = sa.length >>> 1) || // Implicit null check on `sa` - dp >= da.length) { // Implicit null check on `da` - return 0; - } - int minLen = Math.min(len, Math.min(sl - sp, da.length - dp)); - return encodeISOArray0(sa, sp, da, dp, minLen); - } - @IntrinsicCandidate - private static int encodeISOArray0(byte[] sa, int sp, - byte[] da, int dp, int len) { + public static int implEncodeISOArray(byte[] sa, int sp, + byte[] da, int dp, int len) { int i = 0; for (; i < len; i++) { char c = StringUTF16.getChar(sa, sp++); @@ -156,35 +110,10 @@ class StringCoding { return i; } - /** - * Encodes as many ASCII codepoints as possible from the source - * character array into the destination byte array, assuming that - * the encoding is ASCII compatible. - * - * @param sa the source character array - * @param sp the index of the source array to start reading from - * @param da the target byte array - * @param dp the index of the target array to start writing to - * @param len the maximum number of characters to be encoded - * @return the total number of characters successfully encoded - * @throws NullPointerException if any of the provided arrays is null - */ - static int encodeAsciiArray(char[] sa, int sp, - byte[] da, int dp, int len) { - // This method should tolerate invalid arguments, matching the lenient behavior of the VM intrinsic. - // Hence, using operator expressions instead of `Preconditions`, which throw on failure. - if ((sp | dp | len) < 0 || - sp >= sa.length || // Implicit null check on `sa` - dp >= da.length) { // Implicit null check on `da` - return 0; - } - int minLen = Math.min(len, Math.min(sa.length - sp, da.length - dp)); - return encodeAsciiArray0(sa, sp, da, dp, minLen); - } - @IntrinsicCandidate - static int encodeAsciiArray0(char[] sa, int sp, - byte[] da, int dp, int len) { + public static int implEncodeAsciiArray(char[] sa, int sp, + byte[] da, int dp, int len) + { int i = 0; for (; i < len; i++) { char c = sa[sp++]; diff --git a/src/java.base/share/classes/java/lang/System.java b/src/java.base/share/classes/java/lang/System.java index 5c2b47afe3d..f3a57c34165 100644 --- a/src/java.base/share/classes/java/lang/System.java +++ b/src/java.base/share/classes/java/lang/System.java @@ -55,6 +55,7 @@ import java.util.Properties; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.Executor; +import java.util.concurrent.ScheduledExecutorService; import java.util.function.Supplier; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; @@ -2176,8 +2177,8 @@ public final class System { return String.decodeASCII(src, srcOff, dst, dstOff, len); } - public int encodeASCII(char[] sa, int sp, byte[] da, int dp, int len) { - return StringCoding.encodeAsciiArray(sa, sp, da, dp, len); + public int uncheckedEncodeASCII(char[] src, int srcOff, byte[] dst, int dstOff, int len) { + return StringCoding.implEncodeAsciiArray(src, srcOff, dst, dstOff, len); } public InputStream initialSystemIn() { diff --git a/src/java.base/share/classes/java/lang/VirtualThread.java b/src/java.base/share/classes/java/lang/VirtualThread.java index 514bf07e665..93862db9105 100644 --- a/src/java.base/share/classes/java/lang/VirtualThread.java +++ b/src/java.base/share/classes/java/lang/VirtualThread.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, 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 @@ -89,15 +89,19 @@ final class VirtualThread extends BaseVirtualThread { * * RUNNING -> PARKING // Thread parking with LockSupport.park * PARKING -> PARKED // cont.yield successful, parked indefinitely - * PARKING -> PINNED // cont.yield failed, parked indefinitely on carrier * PARKED -> UNPARKED // unparked, may be scheduled to continue - * PINNED -> RUNNING // unparked, continue execution on same carrier * UNPARKED -> RUNNING // continue execution after park * + * PARKING -> RUNNING // cont.yield failed, need to park on carrier + * RUNNING -> PINNED // park on carrier + * PINNED -> RUNNING // unparked, continue execution on same carrier + * * RUNNING -> TIMED_PARKING // Thread parking with LockSupport.parkNanos * TIMED_PARKING -> TIMED_PARKED // cont.yield successful, timed-parked - * TIMED_PARKING -> TIMED_PINNED // cont.yield failed, timed-parked on carrier * TIMED_PARKED -> UNPARKED // unparked, may be scheduled to continue + * + * TIMED_PARKING -> RUNNING // cont.yield failed, need to park on carrier + * RUNNING -> TIMED_PINNED // park on carrier * TIMED_PINNED -> RUNNING // unparked, continue execution on same carrier * * RUNNING -> BLOCKING // blocking on monitor enter @@ -108,7 +112,7 @@ final class VirtualThread extends BaseVirtualThread { * RUNNING -> WAITING // transitional state during wait on monitor * WAITING -> WAIT // waiting on monitor * WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner - * WAIT -> UNBLOCKED // timed-out/interrupted + * WAIT -> UNBLOCKED // interrupted * * RUNNING -> TIMED_WAITING // transition state during timed-waiting on monitor * TIMED_WAITING -> TIMED_WAIT // timed-waiting on monitor @@ -856,16 +860,20 @@ final class VirtualThread extends BaseVirtualThread { * Re-enables this virtual thread for scheduling. If this virtual thread is parked * then its task is scheduled to continue, otherwise its next call to {@code park} or * {@linkplain #parkNanos(long) parkNanos} is guaranteed not to block. + * @param lazySubmit to use lazySubmit if possible * @throws RejectedExecutionException if the scheduler cannot accept a task */ - @Override - void unpark() { + private void unpark(boolean lazySubmit) { if (!getAndSetParkPermit(true) && currentThread() != this) { int s = state(); // unparked while parked if ((s == PARKED || s == TIMED_PARKED) && compareAndSetState(s, UNPARKED)) { - submitRunContinuation(); + if (lazySubmit) { + lazySubmitRunContinuation(); + } else { + submitRunContinuation(); + } return; } @@ -888,6 +896,11 @@ final class VirtualThread extends BaseVirtualThread { } } + @Override + void unpark() { + unpark(false); + } + /** * Invoked by unblocker thread to unblock this virtual thread. */ @@ -904,11 +917,7 @@ final class VirtualThread extends BaseVirtualThread { */ private void parkTimeoutExpired() { assert !VirtualThread.currentThread().isVirtual(); - if (!getAndSetParkPermit(true) - && (state() == TIMED_PARKED) - && compareAndSetState(TIMED_PARKED, UNPARKED)) { - lazySubmitRunContinuation(); - } + unpark(true); } /** diff --git a/src/java.base/share/classes/java/security/Security.java b/src/java.base/share/classes/java/security/Security.java index 6969fe8a8e1..30a22b05742 100644 --- a/src/java.base/share/classes/java/security/Security.java +++ b/src/java.base/share/classes/java/security/Security.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2026, 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 @@ -34,6 +34,7 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; @@ -112,7 +113,7 @@ public final class Security { private static Path currentPath; - private static final Set activePaths = new HashSet<>(); + private static final List activePaths = new ArrayList<>(); static void loadAll() { // first load the master properties file to @@ -262,30 +263,40 @@ public final class Security { } } + private static void checkCyclicInclude(Path path) { + for (Path activePath : activePaths) { + try { + if (Files.isSameFile(path, activePath)) { + throw new InternalError( + "Cyclic include of '" + path + "'"); + } + } catch (IOException e) { + if (sdebug != null) { + sdebug.println("skipped exception when checking for " + + "cyclic inclusion of " + path + ":"); + e.printStackTrace(); + } + } + } + } + private static void loadFromPath(Path path, LoadingMode mode) throws IOException { - boolean isRegularFile = Files.isRegularFile(path); - if (isRegularFile) { - path = path.toRealPath(); - } else if (Files.isDirectory(path)) { + if (Files.isDirectory(path)) { throw new IOException("Is a directory"); - } else { - path = path.toAbsolutePath(); - } - if (activePaths.contains(path)) { - throw new InternalError("Cyclic include of '" + path + "'"); } try (InputStream is = Files.newInputStream(path)) { + checkCyclicInclude(path); reset(mode); Path previousPath = currentPath; - currentPath = isRegularFile ? path : null; + currentPath = Files.isRegularFile(path) ? path : null; activePaths.add(path); try { debugLoad(true, path); props.load(is); debugLoad(false, path); } finally { - activePaths.remove(path); + activePaths.removeLast(); currentPath = previousPath; } } diff --git a/src/java.base/share/classes/java/util/concurrent/StructuredTaskScope.java b/src/java.base/share/classes/java/util/concurrent/StructuredTaskScope.java index 01bf1158bf6..66ba2c29bb3 100644 --- a/src/java.base/share/classes/java/util/concurrent/StructuredTaskScope.java +++ b/src/java.base/share/classes/java/util/concurrent/StructuredTaskScope.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, 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 @@ -1081,10 +1081,9 @@ public sealed interface StructuredTaskScope * does not throw then the {@code Joiner}'s {@code result()} method is invoked to * get the result or throw. * - *

This method may only be invoked by the scope owner. Once the result or - * exception outcome is obtained, this method may not be invoked again. The only - * case where the method may be called again is where {@code InterruptedException} - * is thrown while waiting. + *

This method may only be invoked by the scope owner. It may only be invoked once + * to get the result, exception or timeout outcome, unless the previous invocation + * resulted in an {@code InterruptedException} being thrown. * * @return the result * @throws WrongThreadException if the current thread is not the scope owner @@ -1093,8 +1092,11 @@ public sealed interface StructuredTaskScope * exception from {@link Joiner#result() Joiner.result()} as the cause * @throws TimeoutException if a timeout is set, the timeout expires before or while * waiting, and {@link Joiner#onTimeout() Joiner.onTimeout()} throws this exception - * @throws InterruptedException if interrupted while waiting + * @throws InterruptedException if the current thread is interrupted before or + * while waiting. The current thread's interrupted status is cleared when this + * exception is thrown. * @since 25 + * @see Thread##thread-interruption Thread Interruption */ R join() throws InterruptedException; diff --git a/src/java.base/share/classes/java/util/zip/GZIPInputStream.java b/src/java.base/share/classes/java/util/zip/GZIPInputStream.java index ab7ea53793f..ebcb9e3204c 100644 --- a/src/java.base/share/classes/java/util/zip/GZIPInputStream.java +++ b/src/java.base/share/classes/java/util/zip/GZIPInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2026, 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 @@ -79,7 +79,11 @@ public class GZIPInputStream extends InflaterInputStream { super(in, createInflater(in, size), size); usesDefaultInflater = true; try { - readHeader(in); + // we don't expect the stream to be at EOF + // and if it is, then we want readHeader to + // raise an exception, so we pass "true" for + // the "failOnEOF" param. + readHeader(in, true); } catch (IOException ioe) { this.inf.end(); throw ioe; @@ -190,12 +194,40 @@ public class GZIPInputStream extends InflaterInputStream { /* * Reads GZIP member header and returns the total byte number * of this member header. + * If failOnEOF is false and if the given InputStream has already + * reached EOF when this method was invoked, then this method returns + * -1 (indicating that there's no GZIP member header). + * In all other cases of malformed header or EOF being detected + * when reading the header, this method will throw an IOException. */ - private int readHeader(InputStream this_in) throws IOException { + private int readHeader(InputStream this_in, boolean failOnEOF) throws IOException { CheckedInputStream in = new CheckedInputStream(this_in, crc); crc.reset(); + + int magic; + if (!failOnEOF) { + // read an unsigned short value representing the GZIP magic header. + // this is the same as calling readUShort(in), except that here, + // when reading the first byte, we don't raise an EOFException + // if the stream has already reached EOF. + + // read unsigned byte + int b = in.read(); + if (b == -1) { // EOF + crc.reset(); + return -1; // represents no header bytes available + } + checkUnexpectedByte(b); + // read the next unsigned byte to form the unsigned + // short. we throw the usual EOFException/ZipException + // from this point on if there is no more data or + // the data doesn't represent a header. + magic = (readUByte(in) << 8) | b; + } else { + magic = readUShort(in); + } // Check header magic - if (readUShort(in) != GZIP_MAGIC) { + if (magic != GZIP_MAGIC) { throw new ZipException("Not in GZIP format"); } // Check compression method @@ -261,7 +293,11 @@ public class GZIPInputStream extends InflaterInputStream { // try concatenated case int m = 8; // this.trailer try { - m += readHeader(in); // next.header + int numNextHeaderBytes = readHeader(in, false); // next.header (if available) + if (numNextHeaderBytes == -1) { + return true; // end of stream reached + } + m += numNextHeaderBytes; } catch (IOException ze) { return true; // ignore any malformed, do nothing } @@ -295,14 +331,18 @@ public class GZIPInputStream extends InflaterInputStream { if (b == -1) { throw new EOFException(); } - if (b < -1 || b > 255) { - // Report on this.in, not argument in; see read{Header, Trailer}. - throw new IOException(this.in.getClass().getName() - + ".read() returned value out of range -1..255: " + b); - } + checkUnexpectedByte(b); return b; } + private void checkUnexpectedByte(final int b) throws IOException { + if (b < -1 || b > 255) { + // report the InputStream type which returned this unexpected byte + throw new IOException(this.in.getClass().getName() + + ".read() returned value out of range -1..255: " + b); + } + } + private byte[] tmpbuf = new byte[128]; /* diff --git a/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java b/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java index 86e5f317dc7..c5c45ca3553 100644 --- a/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java +++ b/src/java.base/share/classes/jdk/internal/access/JavaLangAccess.java @@ -448,19 +448,15 @@ public interface JavaLangAccess { PrintStream initialSystemErr(); /** - * Encodes as many ASCII codepoints as possible from the source - * character array into the destination byte array, assuming that - * the encoding is ASCII compatible. + * Encodes as many ASCII codepoints as possible from the source array into + * the destination byte array, assuming that the encoding is ASCII + * compatible. + *

+ * WARNING: This method does not perform any bound checks. * - * @param sa the source character array - * @param sp the index of the source array to start reading from - * @param da the target byte array - * @param dp the index of the target array to start writing to - * @param len the total number of characters to be encoded - * @return the total number of characters successfully encoded - * @throws NullPointerException if any of the provided arrays is null + * @return the number of bytes successfully encoded, or 0 if none */ - int encodeASCII(char[] sa, int sp, byte[] da, int dp, int len); + int uncheckedEncodeASCII(char[] src, int srcOff, byte[] dst, int dstOff, int len); /** * Set the cause of Throwable diff --git a/src/java.base/share/classes/jdk/internal/jimage/BasicImageReader.java b/src/java.base/share/classes/jdk/internal/jimage/BasicImageReader.java index 6807928b2c2..10aa0397f0c 100644 --- a/src/java.base/share/classes/jdk/internal/jimage/BasicImageReader.java +++ b/src/java.base/share/classes/jdk/internal/jimage/BasicImageReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, 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 @@ -220,14 +220,6 @@ public class BasicImageReader implements AutoCloseable { return slice(buffer, offset, size).order(byteOrder).asIntBuffer(); } - public static void releaseByteBuffer(ByteBuffer buffer) { - Objects.requireNonNull(buffer); - - if (!MAP_ALL) { - ImageBufferCache.releaseBuffer(buffer); - } - } - public String getName() { return name; } @@ -362,13 +354,15 @@ public class BasicImageReader implements AutoCloseable { if (offset < 0 || Integer.MAX_VALUE <= offset) { throw new IndexOutOfBoundsException("Bad offset: " + offset); } + int checkedOffset = (int) offset; if (size < 0 || Integer.MAX_VALUE <= size) { - throw new IndexOutOfBoundsException("Bad size: " + size); + throw new IllegalArgumentException("Bad size: " + size); } + int checkedSize = (int) size; if (MAP_ALL) { - ByteBuffer buffer = slice(memoryMap, (int)offset, (int)size); + ByteBuffer buffer = slice(memoryMap, checkedOffset, checkedSize); buffer.order(ByteOrder.BIG_ENDIAN); return buffer; @@ -376,21 +370,18 @@ public class BasicImageReader implements AutoCloseable { if (channel == null) { throw new InternalError("Image file channel not open"); } - - ByteBuffer buffer = ImageBufferCache.getBuffer(size); + ByteBuffer buffer = ByteBuffer.allocate(checkedSize); int read; try { - read = channel.read(buffer, offset); + read = channel.read(buffer, checkedOffset); buffer.rewind(); } catch (IOException ex) { - ImageBufferCache.releaseBuffer(buffer); throw new RuntimeException(ex); } - if (read != size) { - ImageBufferCache.releaseBuffer(buffer); + if (read != checkedSize) { throw new RuntimeException("Short read: " + read + - " instead of " + size + " bytes"); + " instead of " + checkedSize + " bytes"); } return buffer; @@ -406,17 +397,12 @@ public class BasicImageReader implements AutoCloseable { public byte[] getResource(ImageLocation loc) { ByteBuffer buffer = getResourceBuffer(loc); - - if (buffer != null) { - byte[] bytes = getBufferBytes(buffer); - ImageBufferCache.releaseBuffer(buffer); - - return bytes; - } - - return null; + return buffer != null ? getBufferBytes(buffer) : null; } + /** + * Returns the content of jimage location in a newly allocated byte buffer. + */ public ByteBuffer getResourceBuffer(ImageLocation loc) { Objects.requireNonNull(loc); long offset = loc.getContentOffset() + indexSize; @@ -437,10 +423,8 @@ public class BasicImageReader implements AutoCloseable { return readBuffer(offset, uncompressedSize); } else { ByteBuffer buffer = readBuffer(offset, compressedSize); - if (buffer != null) { byte[] bytesIn = getBufferBytes(buffer); - ImageBufferCache.releaseBuffer(buffer); byte[] bytesOut; try { diff --git a/src/java.base/share/classes/jdk/internal/jimage/ImageBufferCache.java b/src/java.base/share/classes/jdk/internal/jimage/ImageBufferCache.java deleted file mode 100644 index c2cc4a028be..00000000000 --- a/src/java.base/share/classes/jdk/internal/jimage/ImageBufferCache.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2014, 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * 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. - */ -package jdk.internal.jimage; - -import java.lang.ref.WeakReference; -import java.nio.ByteBuffer; -import java.util.AbstractMap; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Map; - -/** - * @implNote This class needs to maintain JDK 8 source compatibility. - * - * It is used internally in the JDK to implement jimage/jrtfs access, - * but also compiled and delivered as part of the jrt-fs.jar to support access - * to the jimage file provided by the shipped JDK by tools running on JDK 8. - */ -class ImageBufferCache { - private static final int MAX_CACHED_BUFFERS = 3; - private static final int LARGE_BUFFER = 0x10000; - - /* - * We used to have a class BufferReference extending from WeakReference. - * BufferReference class had an instance field called "capacity". This field was - * used to make DECREASING_CAPACITY_NULLS_LAST comparator stable in the presence - * of GC clearing the WeakReference concurrently. - * - * But this scheme results in metaspace leak. The thread local is alive till the - * the thread is alive. And so ImageBufferCache$BufferReference class was kept alive. - * Because this class and ImageBufferCache$BufferReference are all loaded by a URL - * class loader from jrt-fs.jar, the class loader and so all the classes loaded by it - * were alive! - * - * Solution is to avoid using a URL loader loaded class type with thread local. All we - * need is a pair of WeakReference, Integer (saved capacity for stability - * of comparator). We use Map.Entry as pair implementation. With this, all types used - * with thread local are bootstrap types and so no metaspace leak. - */ - @SuppressWarnings("unchecked") - private static final ThreadLocal, Integer>[]> CACHE = - new ThreadLocal, Integer>[]>() { - @Override - protected Map.Entry, Integer>[] initialValue() { - // 1 extra slot to simplify logic of releaseBuffer() - return (Map.Entry, Integer>[])new Map.Entry[MAX_CACHED_BUFFERS + 1]; - } - }; - - private static ByteBuffer allocateBuffer(long size) { - return ByteBuffer.allocateDirect((int)((size + 0xFFF) & ~0xFFF)); - } - - static ByteBuffer getBuffer(long size) { - if (size < 0 || Integer.MAX_VALUE < size) { - throw new IndexOutOfBoundsException("size"); - } - - ByteBuffer result = null; - - if (size > LARGE_BUFFER) { - result = allocateBuffer(size); - } else { - Map.Entry, Integer>[] cache = CACHE.get(); - - // buffers are ordered by decreasing capacity - // cache[MAX_CACHED_BUFFERS] is always null - for (int i = MAX_CACHED_BUFFERS - 1; i >= 0; i--) { - Map.Entry, Integer> reference = cache[i]; - - if (reference != null) { - ByteBuffer buffer = getByteBuffer(reference); - - if (buffer != null && size <= buffer.capacity()) { - cache[i] = null; - result = buffer; - result.rewind(); - break; - } - } - } - - if (result == null) { - result = allocateBuffer(size); - } - } - - result.limit((int)size); - - return result; - } - - static void releaseBuffer(ByteBuffer buffer) { - if (buffer.capacity() > LARGE_BUFFER) { - return; - } - - Map.Entry, Integer>[] cache = CACHE.get(); - - // expunge cleared BufferRef(s) - for (int i = 0; i < MAX_CACHED_BUFFERS; i++) { - Map.Entry, Integer> reference = cache[i]; - if (reference != null && getByteBuffer(reference) == null) { - cache[i] = null; - } - } - - // insert buffer back with new BufferRef wrapping it - cache[MAX_CACHED_BUFFERS] = newCacheEntry(buffer); - Arrays.sort(cache, DECREASING_CAPACITY_NULLS_LAST); - // squeeze the smallest one out - cache[MAX_CACHED_BUFFERS] = null; - } - - private static Map.Entry, Integer> newCacheEntry(ByteBuffer bb) { - return new AbstractMap.SimpleEntry, Integer>( - new WeakReference(bb), bb.capacity()); - } - - private static int getCapacity(Map.Entry, Integer> e) { - return e == null? 0 : e.getValue(); - } - - private static ByteBuffer getByteBuffer(Map.Entry, Integer> e) { - return e == null? null : e.getKey().get(); - } - - private static Comparator, Integer>> DECREASING_CAPACITY_NULLS_LAST = - new Comparator, Integer>>() { - @Override - public int compare(Map.Entry, Integer> br1, - Map.Entry, Integer> br2) { - return Integer.compare(getCapacity(br1), getCapacity(br2)); - } - }; -} diff --git a/src/java.base/share/classes/jdk/internal/jimage/ImageReader.java b/src/java.base/share/classes/jdk/internal/jimage/ImageReader.java index e062e1629ff..c36e265ee2f 100644 --- a/src/java.base/share/classes/jdk/internal/jimage/ImageReader.java +++ b/src/java.base/share/classes/jdk/internal/jimage/ImageReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, 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 @@ -190,20 +190,7 @@ public final class ImageReader implements AutoCloseable { } /** - * Releases a (possibly cached) {@link ByteBuffer} obtained via - * {@link #getResourceBuffer(Node)}. - * - *

Note that no testing is performed to check whether the buffer about - * to be released actually came from a call to {@code getResourceBuffer()}. - */ - public static void releaseByteBuffer(ByteBuffer buffer) { - BasicImageReader.releaseByteBuffer(buffer); - } - - /** - * Returns the content of a resource node in a possibly cached byte buffer. - * Callers of this method must call {@link #releaseByteBuffer(ByteBuffer)} - * when they are finished with it. + * Returns the content of a resource node in a newly allocated byte buffer. */ public ByteBuffer getResourceBuffer(Node node) { requireOpen(); diff --git a/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java b/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java index 370c151af84..afebb89168c 100644 --- a/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java +++ b/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, 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 @@ -467,12 +467,6 @@ public final class SystemModuleFinders { .map(reader::getResourceBuffer); } - @Override - public void release(ByteBuffer bb) { - Objects.requireNonNull(bb); - ImageReader.releaseByteBuffer(bb); - } - @Override public Stream list() throws IOException { if (closed) diff --git a/src/java.base/share/classes/jdk/internal/util/ByteArray.java b/src/java.base/share/classes/jdk/internal/util/ByteArray.java index 94395df2c34..92b9dbbef19 100644 --- a/src/java.base/share/classes/jdk/internal/util/ByteArray.java +++ b/src/java.base/share/classes/jdk/internal/util/ByteArray.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, 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 @@ -241,7 +241,7 @@ public final class ByteArray { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length] + * the range [0, array.length - 1] * @see #getBoolean(byte[], int) */ public static void setBoolean(byte[] array, int offset, boolean value) { @@ -328,7 +328,7 @@ public final class ByteArray { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length - 2] + * the range [0, array.length - 4] * @see #getFloat(byte[], int) */ public static void setFloat(byte[] array, int offset, float value) { @@ -350,7 +350,7 @@ public final class ByteArray { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length - 2] + * the range [0, array.length - 4] * @see #getFloatRaw(byte[], int) */ public static void setFloatRaw(byte[] array, int offset, float value) { @@ -368,7 +368,7 @@ public final class ByteArray { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length - 4] + * the range [0, array.length - 8] * @see #getLong(byte[], int) */ public static void setLong(byte[] array, int offset, long value) { @@ -387,7 +387,7 @@ public final class ByteArray { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length - 2] + * the range [0, array.length - 8] * @see #getDouble(byte[], int) */ public static void setDouble(byte[] array, int offset, double value) { @@ -409,7 +409,7 @@ public final class ByteArray { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length - 2] + * the range [0, array.length - 8] * @see #getDoubleRaw(byte[], int) */ public static void setDoubleRaw(byte[] array, int offset, double value) { diff --git a/src/java.base/share/classes/jdk/internal/util/ByteArrayLittleEndian.java b/src/java.base/share/classes/jdk/internal/util/ByteArrayLittleEndian.java index fcd7ca2b9bf..cc50686429b 100644 --- a/src/java.base/share/classes/jdk/internal/util/ByteArrayLittleEndian.java +++ b/src/java.base/share/classes/jdk/internal/util/ByteArrayLittleEndian.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, 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 @@ -241,7 +241,7 @@ public final class ByteArrayLittleEndian { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length] + * the range [0, array.length - 1] * @see #getBoolean(byte[], int) */ public static void setBoolean(byte[] array, int offset, boolean value) { @@ -328,7 +328,7 @@ public final class ByteArrayLittleEndian { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length - 2] + * the range [0, array.length - 4] * @see #getFloat(byte[], int) */ public static void setFloat(byte[] array, int offset, float value) { @@ -350,7 +350,7 @@ public final class ByteArrayLittleEndian { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length - 2] + * the range [0, array.length - 4] * @see #getFloatRaw(byte[], int) */ public static void setFloatRaw(byte[] array, int offset, float value) { @@ -368,7 +368,7 @@ public final class ByteArrayLittleEndian { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length - 4] + * the range [0, array.length - 8] * @see #getLong(byte[], int) */ public static void setLong(byte[] array, int offset, long value) { @@ -387,7 +387,7 @@ public final class ByteArrayLittleEndian { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length - 2] + * the range [0, array.length - 8] * @see #getDouble(byte[], int) */ public static void setDouble(byte[] array, int offset, double value) { @@ -409,7 +409,7 @@ public final class ByteArrayLittleEndian { * @param offset where setting (writing) in the array should begin * @param value value to set in the array * @throws IndexOutOfBoundsException if the provided {@code offset} is outside - * the range [0, array.length - 2] + * the range [0, array.length - 8] * @see #getDoubleRaw(byte[], int) */ public static void setDoubleRaw(byte[] array, int offset, double value) { diff --git a/src/java.base/share/classes/sun/nio/cs/CESU_8.java b/src/java.base/share/classes/sun/nio/cs/CESU_8.java index 409b375ec88..11f21f56139 100644 --- a/src/java.base/share/classes/sun/nio/cs/CESU_8.java +++ b/src/java.base/share/classes/sun/nio/cs/CESU_8.java @@ -445,7 +445,7 @@ class CESU_8 extends Unicode int dl = dst.arrayOffset() + dst.limit(); // Handle ASCII-only prefix - int n = JLA.encodeASCII(sa, sp, da, dp, Math.min(sl - sp, dl - dp)); + int n = JLA.uncheckedEncodeASCII(sa, sp, da, dp, Math.min(sl - sp, dl - dp)); sp += n; dp += n; diff --git a/src/java.base/share/classes/sun/nio/cs/DoubleByte.java b/src/java.base/share/classes/sun/nio/cs/DoubleByte.java index 0969669a35b..2a4dbdc95ed 100644 --- a/src/java.base/share/classes/sun/nio/cs/DoubleByte.java +++ b/src/java.base/share/classes/sun/nio/cs/DoubleByte.java @@ -600,7 +600,7 @@ public class DoubleByte { try { if (isASCIICompatible) { - int n = JLA.encodeASCII(sa, sp, da, dp, Math.min(dl - dp, sl - sp)); + int n = JLA.uncheckedEncodeASCII(sa, sp, da, dp, Math.min(dl - dp, sl - sp)); sp += n; dp += n; } diff --git a/src/java.base/share/classes/sun/nio/cs/ISO_8859_1.java b/src/java.base/share/classes/sun/nio/cs/ISO_8859_1.java index ff5970e92a8..39215bfa93d 100644 --- a/src/java.base/share/classes/sun/nio/cs/ISO_8859_1.java +++ b/src/java.base/share/classes/sun/nio/cs/ISO_8859_1.java @@ -35,6 +35,7 @@ import java.util.Objects; import jdk.internal.access.JavaLangAccess; import jdk.internal.access.SharedSecrets; +import jdk.internal.util.Preconditions; import jdk.internal.vm.annotation.IntrinsicCandidate; public class ISO_8859_1 @@ -141,34 +142,20 @@ public class ISO_8859_1 private final Surrogate.Parser sgp = new Surrogate.Parser(); - /** - * Encodes as many ISO-8859-1 codepoints as possible from the source - * character array into the destination byte array, assuming that - * the encoding is ISO-8859-1 compatible. - * - * @param sa the source character array - * @param sp the index of the source array to start reading from - * @param da the target byte array - * @param dp the index of the target array to start writing to - * @param len the maximum number of characters to be encoded - * @return the total number of characters successfully encoded - * @throws NullPointerException if any of the provided arrays is null - */ + // Method possible replaced with a compiler intrinsic. private static int encodeISOArray(char[] sa, int sp, byte[] da, int dp, int len) { - // This method should tolerate invalid arguments, matching the lenient behavior of the VM intrinsic. - // Hence, using operator expressions instead of `Preconditions`, which throw on failure. - if ((sp | dp | len) < 0 || - sp >= sa.length || // Implicit null check on `sa` - dp >= da.length) { // Implicit null check on `da` + if (len <= 0) { return 0; } - int minLen = Math.min(len, Math.min(sa.length - sp, da.length - dp)); - return encodeISOArray0(sa, sp, da, dp, minLen); + encodeISOArrayCheck(sa, sp, da, dp, len); + return implEncodeISOArray(sa, sp, da, dp, len); } @IntrinsicCandidate - private static int encodeISOArray0(char[] sa, int sp, byte[] da, int dp, int len) { + private static int implEncodeISOArray(char[] sa, int sp, + byte[] da, int dp, int len) + { int i = 0; for (; i < len; i++) { char c = sa[sp++]; @@ -179,6 +166,17 @@ public class ISO_8859_1 return i; } + private static void encodeISOArrayCheck(char[] sa, int sp, + byte[] da, int dp, int len) { + Objects.requireNonNull(sa); + Objects.requireNonNull(da); + Preconditions.checkIndex(sp, sa.length, Preconditions.AIOOBE_FORMATTER); + Preconditions.checkIndex(dp, da.length, Preconditions.AIOOBE_FORMATTER); + + Preconditions.checkIndex(sp + len - 1, sa.length, Preconditions.AIOOBE_FORMATTER); + Preconditions.checkIndex(dp + len - 1, da.length, Preconditions.AIOOBE_FORMATTER); + } + private CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) { diff --git a/src/java.base/share/classes/sun/nio/cs/SingleByte.java b/src/java.base/share/classes/sun/nio/cs/SingleByte.java index a5bf06cb251..59887b944d3 100644 --- a/src/java.base/share/classes/sun/nio/cs/SingleByte.java +++ b/src/java.base/share/classes/sun/nio/cs/SingleByte.java @@ -217,7 +217,7 @@ public class SingleByte int len = Math.min(dl - dp, sl - sp); if (isASCIICompatible) { - int n = JLA.encodeASCII(sa, sp, da, dp, len); + int n = JLA.uncheckedEncodeASCII(sa, sp, da, dp, len); sp += n; dp += n; len -= n; diff --git a/src/java.base/share/classes/sun/nio/cs/US_ASCII.java b/src/java.base/share/classes/sun/nio/cs/US_ASCII.java index 3886978d209..bb84ab1bd4b 100644 --- a/src/java.base/share/classes/sun/nio/cs/US_ASCII.java +++ b/src/java.base/share/classes/sun/nio/cs/US_ASCII.java @@ -159,7 +159,7 @@ public class US_ASCII assert (dp <= dl); dp = (dp <= dl ? dp : dl); - int n = JLA.encodeASCII(sa, sp, da, dp, Math.min(sl - sp, dl - dp)); + int n = JLA.uncheckedEncodeASCII(sa, sp, da, dp, Math.min(sl - sp, dl - dp)); sp += n; dp += n; diff --git a/src/java.base/share/classes/sun/nio/cs/UTF_8.java b/src/java.base/share/classes/sun/nio/cs/UTF_8.java index d2d6d7e485d..54e479f838a 100644 --- a/src/java.base/share/classes/sun/nio/cs/UTF_8.java +++ b/src/java.base/share/classes/sun/nio/cs/UTF_8.java @@ -452,7 +452,7 @@ public final class UTF_8 extends Unicode { int dl = dst.arrayOffset() + dst.limit(); // Handle ASCII-only prefix - int n = JLA.encodeASCII(sa, sp, da, dp, Math.min(sl - sp, dl - dp)); + int n = JLA.uncheckedEncodeASCII(sa, sp, da, dp, Math.min(sl - sp, dl - dp)); sp += n; dp += n; diff --git a/src/java.base/share/classes/sun/security/ec/ECDSAOperations.java b/src/java.base/share/classes/sun/security/ec/ECDSAOperations.java index f58d7d8f2d7..7badcf42d9c 100644 --- a/src/java.base/share/classes/sun/security/ec/ECDSAOperations.java +++ b/src/java.base/share/classes/sun/security/ec/ECDSAOperations.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -68,7 +68,7 @@ public class ECDSAOperations { public ECDSAOperations(ECOperations ecOps, ECPoint basePoint) { this.ecOps = ecOps; - this.basePoint = toAffinePoint(basePoint, ecOps.getField()); + this.basePoint = AffinePoint.fromECPoint(basePoint, ecOps.getField()); } public ECOperations getEcOperations() { @@ -79,14 +79,6 @@ public class ECDSAOperations { return ecOps.multiply(basePoint, scalar).asAffine(); } - public static AffinePoint toAffinePoint(ECPoint point, - IntegerFieldModuloP field) { - - ImmutableIntegerModuloP affineX = field.getElement(point.getAffineX()); - ImmutableIntegerModuloP affineY = field.getElement(point.getAffineY()); - return new AffinePoint(affineX, affineY); - } - public static Optional forParameters(ECParameterSpec ecParams) { Optional curveOps = diff --git a/src/java.base/share/classes/sun/security/util/Password.java b/src/java.base/share/classes/sun/security/util/Password.java index e358bcd95de..02cdcaf53fd 100644 --- a/src/java.base/share/classes/sun/security/util/Password.java +++ b/src/java.base/share/classes/sun/security/util/Password.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, 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,6 +32,7 @@ import java.util.Arrays; import jdk.internal.access.SharedSecrets; import jdk.internal.io.JdkConsoleImpl; +import jdk.internal.misc.VM; /** * A utility class for reading passwords @@ -65,7 +66,9 @@ public class Password { } consoleBytes = ConsoleHolder.convertToBytes(consoleEntered); in = new ByteArrayInputStream(consoleBytes); - } else if (System.in.available() == 0) { + } else if (in == System.in && VM.isBooted() + && System.in.available() == 0) { + // Warn if reading password from System.in but it's empty. // This may be running in an IDE Run Window or in JShell, // which acts like an interactive console and echoes the // entered password. In this case, print a warning that @@ -73,6 +76,7 @@ public class Password { // it's more likely the input comes from a pipe, such as // "echo password |" or "cat password_file |" where input // will be silently consumed without echoing to the screen. + // Warn only if VM is booted and ResourcesMgr is available. System.err.print(ResourcesMgr.getString ("warning.input.may.be.visible.on.screen")); } diff --git a/src/java.base/share/classes/sun/security/util/Pem.java b/src/java.base/share/classes/sun/security/util/Pem.java index a9b2908bcc9..c49dcaa912f 100644 --- a/src/java.base/share/classes/sun/security/util/Pem.java +++ b/src/java.base/share/classes/sun/security/util/Pem.java @@ -59,6 +59,9 @@ public class Pem { // Pattern matching for stripping whitespace. private static final Pattern STRIP_WHITESPACE_PATTERN; + // Pattern matching for inserting line breaks. + private static final Pattern LINE_WRAP_64_PATTERN; + // Lazy initialized PBES2 OID value private static ObjectIdentifier PBES2OID; @@ -72,6 +75,7 @@ public class Pem { PBE_PATTERN = Pattern.compile("^PBEWith.*And.*", Pattern.CASE_INSENSITIVE); STRIP_WHITESPACE_PATTERN = Pattern.compile("\\s+"); + LINE_WRAP_64_PATTERN = Pattern.compile("(.{64})"); } public static final String CERTIFICATE = "CERTIFICATE"; @@ -359,7 +363,7 @@ public class Pem { * @return PEM in a string */ public static String pemEncoded(PEM pem) { - String p = pem.content().replaceAll("(.{64})", "$1\r\n"); + String p = LINE_WRAP_64_PATTERN.matcher(pem.content()).replaceAll("$1\r\n"); return pemEncoded(pem.type(), p); } diff --git a/src/java.base/share/classes/sun/security/validator/CADistrustPolicy.java b/src/java.base/share/classes/sun/security/validator/CADistrustPolicy.java index 9c64402c123..44c9ed2d075 100644 --- a/src/java.base/share/classes/sun/security/validator/CADistrustPolicy.java +++ b/src/java.base/share/classes/sun/security/validator/CADistrustPolicy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, 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 @@ -83,6 +83,22 @@ enum CADistrustPolicy { } CamerfirmaTLSPolicy.checkDistrust(chain); } + }, + + /** + * Distrust TLS Server certificates anchored by the Chunghwa ePKI root CA + * and issued after March 17, 2026. If enabled, this policy is currently + * enforced by the PKIX and SunX509 TrustManager implementations + * of the SunJSSE provider implementation. + */ + CHUNGHWA_TLS { + void checkDistrust(String variant, X509Certificate[] chain) + throws ValidatorException { + if (!variant.equals(Validator.VAR_TLS_SERVER)) { + return; + } + ChunghwaTLSPolicy.checkDistrust(chain); + } }; /** diff --git a/src/java.base/share/classes/sun/security/validator/ChunghwaTLSPolicy.java b/src/java.base/share/classes/sun/security/validator/ChunghwaTLSPolicy.java new file mode 100644 index 00000000000..114f5043fbf --- /dev/null +++ b/src/java.base/share/classes/sun/security/validator/ChunghwaTLSPolicy.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2026, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ +package sun.security.validator; + +import java.security.cert.X509Certificate; +import java.time.LocalDate; +import java.time.Month; +import java.time.ZoneOffset; +import java.util.Date; +import java.util.Map; +import java.util.Set; + +import sun.security.util.Debug; +import sun.security.x509.X509CertImpl; + +/** + * This class checks if Chunghwa issued TLS Server certificates should be + * restricted. + */ +final class ChunghwaTLSPolicy { + + private static final Debug debug = Debug.getInstance("certpath"); + + // SHA-256 certificate fingerprint of distrusted root for TLS + // cacerts alias: chunghwaepkirootca + // DN: OU=ePKI Root Certification Authority, + // O="Chunghwa Telecom Co., Ltd.", C=TW + private static final String FINGERPRINT = + "C0A6F4DC63A24BFDCF54EF2A6A082A0A72DE35803E2FF5FF527AE5D87206DFD5"; + + // Any TLS Server certificate that is anchored by the Chunghwa + // root above and is issued after this date will be distrusted. + private static final LocalDate MARCH_17_2026 = + LocalDate.of(2026, Month.MARCH, 17); + + /** + * This method assumes the eeCert is a TLS Server Cert and chains back to + * the anchor. + * + * @param chain the end-entity's certificate chain. The end entity cert + * is at index 0, the trust anchor at index n-1. + * @throws ValidatorException if the certificate is distrusted + */ + static void checkDistrust(X509Certificate[] chain) + throws ValidatorException { + X509Certificate anchor = chain[chain.length-1]; + String fp = fingerprint(anchor); + if (fp == null) { + throw new ValidatorException("Cannot generate fingerprint for " + + "trust anchor of TLS server certificate"); + } + if (FINGERPRINT.equalsIgnoreCase(fp)) { + Date notBefore = chain[0].getNotBefore(); + LocalDate ldNotBefore = LocalDate.ofInstant(notBefore.toInstant(), + ZoneOffset.UTC); + // reject if certificate is issued after March 17, 2026 + checkNotBefore(ldNotBefore, MARCH_17_2026, anchor); + } + } + + private static String fingerprint(X509Certificate cert) { + return X509CertImpl.getFingerprint("SHA-256", cert, debug); + } + + // Check whether the certificate's notBeforeDate is after the + // distrust date for the anchor (root CA). Throw ValidatorException + // if it is after the distrust date. + private static void checkNotBefore(LocalDate notBeforeDate, + LocalDate distrustDate, X509Certificate anchor) + throws ValidatorException { + if (notBeforeDate.isAfter(distrustDate)) { + throw new ValidatorException + ("TLS Server certificate issued after " + distrustDate + + " and anchored by a distrusted legacy Chunghwa root CA: " + + anchor.getSubjectX500Principal(), + ValidatorException.T_UNTRUSTED_CERT, anchor); + } + } + + private ChunghwaTLSPolicy() {} +} diff --git a/src/java.base/share/conf/security/java.security b/src/java.base/share/conf/security/java.security index 3d26c1dcd96..b5cbce413b2 100644 --- a/src/java.base/share/conf/security/java.security +++ b/src/java.base/share/conf/security/java.security @@ -1437,6 +1437,9 @@ jdk.sasl.disabledMechanisms= # CAMERFIRMA_TLS : Distrust TLS Server certificates anchored by # a Camerfirma root CA and issued after April 15, 2025. # +# CHUNGHWA_TLS : Distrust TLS Server certificates anchored by +# a Chunghwa root CA and issued after March 17, 2026. +# # Leading and trailing whitespace surrounding each value are ignored. # Unknown values are ignored. If the property is commented out or set to the # empty String, no policies are enforced. @@ -1448,7 +1451,8 @@ jdk.sasl.disabledMechanisms= # jdk.certpath.disabledAlgorithms; those restrictions are still enforced even # if this property is not enabled. # -jdk.security.caDistrustPolicies=SYMANTEC_TLS,ENTRUST_TLS,CAMERFIRMA_TLS +jdk.security.caDistrustPolicies=SYMANTEC_TLS,ENTRUST_TLS,CAMERFIRMA_TLS,\ + CHUNGHWA_TLS # # FilePermission path canonicalization diff --git a/src/java.base/share/data/tzdata/VERSION b/src/java.base/share/data/tzdata/VERSION index 4bd54efbcdc..ce25e7653b0 100644 --- a/src/java.base/share/data/tzdata/VERSION +++ b/src/java.base/share/data/tzdata/VERSION @@ -21,4 +21,4 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -tzdata2025b +tzdata2025c diff --git a/src/java.base/share/data/tzdata/africa b/src/java.base/share/data/tzdata/africa index 8098f4bea9d..cf1247ee3ab 100644 --- a/src/java.base/share/data/tzdata/africa +++ b/src/java.base/share/data/tzdata/africa @@ -27,9 +27,9 @@ # 2009-05-17 by Arthur David Olson. # This file is by no means authoritative; if you think you know better, -# go ahead and edit the file (and please send any changes to -# tz@iana.org for general use in the future). For more, please see -# the file CONTRIBUTING in the tz distribution. +# go ahead and edit the file, and please send any changes to +# the public mailing list tz@iana.org for general use in the future. +# For more, please see the file CONTRIBUTING in the tz distribution. # From Paul Eggert (2018-05-27): # @@ -138,8 +138,9 @@ Zone Atlantic/Cape_Verde -1:34:04 - LMT 1912 Jan 01 2:00u # Praia -1:00 - %z # Chad +# Fort-Lamy was renamed to N’Djamena on 1973-04-06. # Zone NAME STDOFF RULES FORMAT [UNTIL] -Zone Africa/Ndjamena 1:00:12 - LMT 1912 Jan 1 # N'Djamena +Zone Africa/Ndjamena 1:00:12 - LMT 1912 Jan 1 # Fort-Lamy 1:00 - WAT 1979 Oct 14 1:00 1:00 WAST 1980 Mar 8 1:00 - WAT diff --git a/src/java.base/share/data/tzdata/antarctica b/src/java.base/share/data/tzdata/antarctica index 87787d31cfe..b3c186851f1 100644 --- a/src/java.base/share/data/tzdata/antarctica +++ b/src/java.base/share/data/tzdata/antarctica @@ -26,13 +26,10 @@ # This file is in the public domain, so clarified as of # 2009-05-17 by Arthur David Olson. -# From Paul Eggert (1999-11-15): -# To keep things manageable, we list only locations occupied year-round; see -# COMNAP - Stations and Bases -# http://www.comnap.aq/comnap/comnap.nsf/P/Stations/ -# and -# Summary of the Peri-Antarctic Islands (1998-07-23) -# http://www.spri.cam.ac.uk/bob/periant.htm +# From Paul Eggert (2025-08-16): +# To keep things manageable, list only locations occupied year-round; see +# Antarctic Facilities Information +# https://www.comnap.aq/antarctic-facilities-information # for information. # Unless otherwise specified, we have no time zone information. @@ -167,6 +164,7 @@ Zone Antarctica/Mawson 0 - -00 1954 Feb 13 # China - year-round bases # Great Wall, King George Island, -6213-05858, since 1985-02-20 # Zhongshan, Larsemann Hills, Prydz Bay, -6922+07623, since 1989-02-26 +# Qinling, Inexpressible I, Terra Nova Bay, -7456+16343, since 2024-02-07 # France - year-round bases (also see "France & Italy") # diff --git a/src/java.base/share/data/tzdata/asia b/src/java.base/share/data/tzdata/asia index 55b13134f9c..005abd01793 100644 --- a/src/java.base/share/data/tzdata/asia +++ b/src/java.base/share/data/tzdata/asia @@ -27,9 +27,9 @@ # 2009-05-17 by Arthur David Olson. # This file is by no means authoritative; if you think you know better, -# go ahead and edit the file (and please send any changes to -# tz@iana.org for general use in the future). For more, please see -# the file CONTRIBUTING in the tz distribution. +# go ahead and edit the file, and please send any changes to +# the public mailing list tz@iana.org for general use in the future. +# For more, please see the file CONTRIBUTING in the tz distribution. # From Paul Eggert (2019-07-11): # diff --git a/src/java.base/share/data/tzdata/australasia b/src/java.base/share/data/tzdata/australasia index d659d1fb4b1..638789f42da 100644 --- a/src/java.base/share/data/tzdata/australasia +++ b/src/java.base/share/data/tzdata/australasia @@ -960,9 +960,9 @@ Zone Pacific/Efate 11:13:16 - LMT 1912 Jan 13 # Vila # NOTES # This file is by no means authoritative; if you think you know better, -# go ahead and edit the file (and please send any changes to -# tz@iana.org for general use in the future). For more, please see -# the file CONTRIBUTING in the tz distribution. +# go ahead and edit the file, and please send any changes to +# the public mailing list tz@iana.org for general use in the future. +# For more, please see the file CONTRIBUTING in the tz distribution. # From Paul Eggert (2018-11-18): # @@ -2011,6 +2011,7 @@ Zone Pacific/Efate 11:13:16 - LMT 1912 Jan 13 # Vila # From Paul Eggert (2018-11-19): # The 1921-01-15 introduction of standard time is in Shanks; it is also in # "Standard Time Throughout the World", US National Bureau of Standards (1935), +# https://nvlpubs.nist.gov/nistpubs/Legacy/circ/nbscircular406.pdf # page 3, which does not give the UT offset. In response to a comment by # Phake Nick I set the Nauru time of occupation by Japan to # 1942-08-29/1945-09-08 by using dates from: @@ -2078,9 +2079,10 @@ Zone Pacific/Efate 11:13:16 - LMT 1912 Jan 13 # Vila # https://webspace.science.uu.nl/~gent0113/idl/idl_alaska_samoa.htm # Although Shanks & Pottenger says they both switched to UT -11:30 -# in 1911, and to -11 in 1950. many earlier sources give -11 +# in 1911, and to -11 in 1950, many earlier sources give -11 # for American Samoa, e.g., the US National Bureau of Standards # circular "Standard Time Throughout the World", 1932. +# https://nvlpubs.nist.gov/nistpubs/Legacy/circ/nbscircular399.pdf # Assume American Samoa switched to -11 in 1911, not 1950, # and that after 1950 they agreed until (western) Samoa skipped a # day in 2011. Assume also that the Samoas follow the US and New diff --git a/src/java.base/share/data/tzdata/europe b/src/java.base/share/data/tzdata/europe index 7ba6c679609..b82ca6f67bb 100644 --- a/src/java.base/share/data/tzdata/europe +++ b/src/java.base/share/data/tzdata/europe @@ -27,9 +27,9 @@ # 2009-05-17 by Arthur David Olson. # This file is by no means authoritative; if you think you know better, -# go ahead and edit the file (and please send any changes to -# tz@iana.org for general use in the future). For more, please see -# the file CONTRIBUTING in the tz distribution. +# go ahead and edit the file, and please send any changes to +# the public mailing list tz@iana.org for general use in the future. +# For more, please see the file CONTRIBUTING in the tz distribution. # From Paul Eggert (2017-02-10): # @@ -65,7 +65,7 @@ # . He writes: # "It is requested that corrections and additions to these tables # may be sent to Mr. John Milne, Royal Geographical Society, -# Savile Row, London." Nowadays please email them to tz@iana.org. +# Savile Row, London." Nowadays please see the file CONTRIBUTING. # # Byalokoz EL. New Counting of Time in Russia since July 1, 1919. # This Russian-language source was consulted by Vladimir Karpinsky; see @@ -77,7 +77,7 @@ # Десятая гос. тип., 1919. # http://resolver.gpntb.ru/purl?docushare/dsweb/Get/Resource-2011/Byalokoz__E.L.__Novyy__schet__vremeni__v__techenie__sutok__izd__2(1).pdf # -# Brazil's Divisão Serviço da Hora (DSHO), +# Brazil's Divisão de Serviços da Hora (DISHO) # History of Summer Time # # (1998-09-21, in Portuguese) @@ -937,7 +937,7 @@ Rule Belgium 1922 1927 - Oct Sat>=1 23:00s 0 - Rule Belgium 1923 only - Apr 21 23:00s 1:00 S Rule Belgium 1924 only - Mar 29 23:00s 1:00 S Rule Belgium 1925 only - Apr 4 23:00s 1:00 S -# DSH writes that a royal decree of 1926-02-22 specified the Sun following 3rd +# DISHO writes that a royal decree of 1926-02-22 specified the Sun following 3rd # Sat in Apr (except if it's Easter, in which case it's one Sunday earlier), # to Sun following 1st Sat in Oct, and that a royal decree of 1928-09-15 # changed the transition times to 02:00 GMT. @@ -1333,6 +1333,13 @@ Zone Europe/Helsinki 1:39:49 - LMT 1878 May 31 # France # Monaco +# From Robert H. van Gent (2025-07-21): +# The most recent issue of the Annuaire [par le Bureau des Longitudes] +# on Gallica (2021) ... lists information for France +# https://gallica.bnf.fr/ark:/12148/bpt6k9127672b/f52.item +# From Paul Eggert (2025-07-21): +# Go with the 2020 Annuaire (published 2021) except as noted below. + # From Ciro Discepolo (2000-12-20): # # Henri Le Corre, Régimes horaires pour le monde entier, Éditions @@ -1394,7 +1401,6 @@ Zone Europe/Helsinki 1:39:49 - LMT 1878 May 31 # problems in Algiers, Monaco and Tunis. # -# Shank & Pottenger seem to use '24:00' ambiguously; resolve it with Whitman. # Rule NAME FROM TO - IN ON AT SAVE LETTER/S Rule France 1916 only - Jun 14 23:00s 1:00 S Rule France 1916 1919 - Oct Sun>=1 23:00s 0 - @@ -1406,9 +1412,25 @@ Rule France 1920 only - Oct 23 23:00s 0 - Rule France 1921 only - Mar 14 23:00s 1:00 S Rule France 1921 only - Oct 25 23:00s 0 - Rule France 1922 only - Mar 25 23:00s 1:00 S -# DSH writes that a law of 1923-05-24 specified 3rd Sat in Apr at 23:00 to 1st -# Sat in Oct at 24:00; and that in 1930, because of Easter, the transitions -# were Apr 12 and Oct 5. Go with Shanks & Pottenger. +# From Robert H. van Gent (2025-07-22): +# There is a curious history behind the erroneous date for the start of +# daylight saving in France in 1923 as listed in the current issues of +# the Annuaire du Bureau des Longitudes. [See:] +# https://lists.iana.org/hyperkitty/list/tz@iana.org/message/MYQEJMSXO2AIEZ3UIXZKMTTAIPY7KNT2/ +# From Brian Inglis (2025-07-23): +# Légifrance JORF No. 0073 du 15 mars 1922 +# https://www.legifrance.gouv.fr/jorf/jo/id/JORFCONT000000008324 +# Légifrance JORF No. 0139 du 25 mai 1923 +# https://www.legifrance.gouv.fr/jorf/jo/id/JORFCONT000000008416 +# From Paul Eggert (2025-07-23): +# The latter specifies March's last Saturday at 23:00 to October's first +# Saturday at 24:00, except that if neighboring allies agree the dates +# can be moved to April's third Saturday and September's third Saturday. +# Apparently spring 1923 was tricky. DISHO writes that in 1930, +# because of Easter, the transitions were Apr 12 and Oct 5. +# Use the 2020 Annuaire dates, except for spring 1923 where +# Shanks & Pottenger's May 26 matches the dates given in the 1924 and +# 1961-2001 issues of the Annuaire. Rule France 1922 1938 - Oct Sat>=1 23:00s 0 - Rule France 1923 only - May 26 23:00s 1:00 S Rule France 1924 only - Mar 29 23:00s 1:00 S @@ -2119,12 +2141,10 @@ Zone Europe/Warsaw 1:24:00 - LMT 1880 # all clocks therefore having to be advanced or set back correspondingly ... # Rule NAME FROM TO - IN ON AT SAVE LETTER/S -# From Tim Parenti (2024-07-01), per Paul Eggert (1999-01-30): -# DSH writes in their history that Decreto 1469 of 1915-03-30 established -# summer time and that, "despite" this, the change to the clocks was not done -# every year, depending on what Spain did, because of railroad schedules. -# In fact, that decree had nothing to do with DST; rather, it regulated the -# sending of time signals. But we do see linkage to Spain in the 1920s below. +# From Tim Parenti (2024-07-01): +# Decreto 1469 of 1915-03-30 ... had nothing to do with DST; +# rather it regulated the sending of time signals. +# But we do see linkage to Spain in the 1920s below. # https://dre.pt/dr/detalhe/decreto/1469-1915-285721 # https://dre.pt/application/conteudo/285721 # diff --git a/src/java.base/share/data/tzdata/iso3166.tab b/src/java.base/share/data/tzdata/iso3166.tab index 7fa350ecbe3..ddcc841fe97 100644 --- a/src/java.base/share/data/tzdata/iso3166.tab +++ b/src/java.base/share/data/tzdata/iso3166.tab @@ -26,22 +26,22 @@ # This file is in the public domain, so clarified as of # 2009-05-17 by Arthur David Olson. # -# From Paul Eggert (2023-09-06): +# From Paul Eggert (2025-07-01): # This file contains a table of two-letter country codes. Columns are -# separated by a single tab. Lines beginning with '#' are comments. +# separated by a single tab. Lines beginning with ‘#’ are comments. # All text uses UTF-8 encoding. The columns of the table are as follows: # # 1. ISO 3166-1 alpha-2 country code, current as of -# ISO/TC 46 N1108 (2023-04-05). See: ISO/TC 46 Documents +# ISO/TC 46 N1127 (2024-02-29). See: ISO/TC 46 Documents # https://www.iso.org/committee/48750.html?view=documents # 2. The usual English name for the coded region. This sometimes # departs from ISO-listed names, sometimes so that sorted subsets -# of names are useful (e.g., "Samoa (American)" and "Samoa -# (western)" rather than "American Samoa" and "Samoa"), +# of names are useful (e.g., “Samoa (American)” and “Samoa +# (western)” rather than “American Samoa” and “Samoa”), # sometimes to avoid confusion among non-experts (e.g., -# "Czech Republic" and "Turkey" rather than "Czechia" and "Türkiye"), -# and sometimes to omit needless detail or churn (e.g., "Netherlands" -# rather than "Netherlands (the)" or "Netherlands (Kingdom of the)"). +# “Czech Republic” and “Turkey” rather than “Czechia” and “Türkiye”), +# and sometimes to omit needless detail or churn (e.g., “Netherlands” +# rather than “Netherlands (the)” or “Netherlands (Kingdom of the)”). # # The table is sorted by country code. # @@ -94,7 +94,7 @@ CD Congo (Dem. Rep.) CF Central African Rep. CG Congo (Rep.) CH Switzerland -CI Côte d'Ivoire +CI Côte d’Ivoire CK Cook Islands CL Chile CM Cameroon diff --git a/src/java.base/share/data/tzdata/leapseconds b/src/java.base/share/data/tzdata/leapseconds index 042a32b052c..9426b40f07e 100644 --- a/src/java.base/share/data/tzdata/leapseconds +++ b/src/java.base/share/data/tzdata/leapseconds @@ -28,7 +28,8 @@ # This file is generated automatically from the data in the public-domain # NIST/IERS format leap-seconds.list file, which can be copied from # -# or, in a variant with different comments, from +# or via a less-secure protocol and with different comments and +# less volatile last-modified and expiration timestamps, from # . # For more about leap-seconds.list, please see # The NTP Timescale and Leap Seconds @@ -92,11 +93,17 @@ Leap 2016 Dec 31 23:59:60 + S # Any additional leap seconds will come after this. # This Expires line is commented out for now, # so that pre-2020a zic implementations do not reject this file. -#Expires 2025 Dec 28 00:00:00 +#Expires 2026 Jun 28 00:00:00 -# POSIX timestamps for the data in this file: -#updated 1736208000 (2025-01-07 00:00:00 UTC) -#expires 1766880000 (2025-12-28 00:00:00 UTC) +# Here are POSIX timestamps for the data in this file. +# "#updated" gives the last time the leap seconds data changed +# or, if this file was derived from the IERS leap-seconds.list, +# the last time that file changed in any way. +# "#expires" gives the first time this file might be wrong; +# if this file was derived from the IERS leap-seconds.list, +# this is typically a bit less than one year after "updated". +#updated 1751846400 (2025-07-07 00:00:00 UTC) +#expires 1782604800 (2026-06-28 00:00:00 UTC) # Updated through IERS Bulletin C (https://hpiers.obspm.fr/iers/bul/bulc/bulletinc.dat) -# File expires on 28 December 2025 +# File expires on 28 June 2026 diff --git a/src/java.base/share/data/tzdata/northamerica b/src/java.base/share/data/tzdata/northamerica index 21f178ee8cb..f20879e9063 100644 --- a/src/java.base/share/data/tzdata/northamerica +++ b/src/java.base/share/data/tzdata/northamerica @@ -29,9 +29,9 @@ # also includes Central America and the Caribbean # This file is by no means authoritative; if you think you know better, -# go ahead and edit the file (and please send any changes to -# tz@iana.org for general use in the future). For more, please see -# the file CONTRIBUTING in the tz distribution. +# go ahead and edit the file, and please send any changes to +# the public mailing list tz@iana.org for general use in the future. +# For more, please see the file CONTRIBUTING in the tz distribution. # From Paul Eggert (1999-03-22): # A reliable and entertaining source about time zones is @@ -1241,6 +1241,16 @@ Zone America/Menominee -5:50:27 - LMT 1885 Sep 18 12:00 # _Los Angeles Times_ (1998-11-10), A1, A10; it cites # Jimmy Skaggs, _The Great Guano Rush_ (1994). +# From Rob van Gent (2025-07-23): +# Another useful source for historical time zone information appears to be +# a series of circulars with the title "Standard Time Throughout the World" +# issued between 1925 and 1950 by the U.S. Bureau of Standards. +# I found the following issues online: +# https://nvlpubs.nist.gov/nistpubs/Legacy/circ/nbscircular280.pdf (1925) +# https://nvlpubs.nist.gov/nistpubs/Legacy/circ/nbscircular399.pdf (1932) +# https://nvlpubs.nist.gov/nistpubs/Legacy/circ/nbscircular406.pdf (1935) +# https://nvlpubs.nist.gov/nistpubs/Legacy/circ/nbscircular496.pdf (1950) + ################################################################################ @@ -2457,12 +2467,35 @@ Zone America/Dawson -9:17:40 - LMT 1900 Aug 20 # on the same dates or with a difference of one day. # So it may be easier to implement these changes as DST with rule CA # during this whole period. + +# From Alois Treindl (2025-07-29): +# I did a quick newspaper archive research on https://hndm.iib.unam.mx/ +# and found that Periódico Oficial del Estado de Baja California Norte +# (1973-04-20) states clearly that DST was observed from last Sunday +# in April to last Sunday in October.... I have a few more data from the +# official bulletin for DST begin or end in Baja California 1964 1967 1969 +# 1972 1973 (already sent) 1974 1975 1976 I do not know whether it is safe to +# assume that it also applied in the years where I did not yet find proof. +# The 1974 end of DST contains a reference to an Acuerdo of 1973-dec-20 which +# I could not find.... One might assume that Baja California, which followed +# US-CA in all these other yours, did the same. # -# From Paul Eggert (2024-08-18): -# For now, maintain the slightly-different history for Baja California, +# From Paul Eggert (2025-08-04): +# Assume that Tijuana agreed with San Diego from 1953 through 1996, +# as this agrees with Alois Treindl's data and with Shanks. +# For now, keep the slightly-different 1948/1952 history for Baja California, # as we have no information on whether 1948/1952 clocks in Tijuana followed # the decrees or followed San Diego. +# From Mark Schapiro, writing in The Nation (2002-10-28): +# https://www.thenation.com/article/archive/sowing-disaster/ +# When Mexican clocks were turned back for daylight saving time in the spring, +# the Zapotecs refused to make the adjustment, insisting that they live in +# "God's time," not in what they derisively call "Fox time," referring to +# President Vicente Fox in far-off Mexico City. +# From Paul Eggert (2025-08-04): +# Unfortunately we have no data to track this informal practice. + # From Alan Perry (1996-02-15): # A guy from our Mexico subsidiary finally found the Presidential Decree # outlining the timezone changes in Mexico. @@ -2728,7 +2761,7 @@ Zone America/Mexico_City -6:36:36 - LMT 1922 Jan 1 7:00u # Chihuahua (near US border - western side) # This includes the municipios of Janos, Ascensión, Juárez, Guadalupe, and # Práxedis G Guerrero. -# http://gaceta.diputados.gob.mx/PDF/65/2a022/nov/20221124-VII.pdf +# https://gaceta.diputados.gob.mx/PDF/65/2022/nov/20221124-VII.pdf Zone America/Ciudad_Juarez -7:05:56 - LMT 1922 Jan 1 7:00u -7:00 - MST 1927 Jun 10 -6:00 - CST 1930 Nov 15 @@ -2743,7 +2776,7 @@ Zone America/Ciudad_Juarez -7:05:56 - LMT 1922 Jan 1 7:00u # Chihuahua (near US border - eastern side) # This includes the municipios of Coyame del Sotol, Ojinaga, and Manuel # Benavides. -# http://gaceta.diputados.gob.mx/PDF/65/2a022/nov/20221124-VII.pdf +# https://gaceta.diputados.gob.mx/PDF/65/2022/nov/20221124-VII.pdf Zone America/Ojinaga -6:57:40 - LMT 1922 Jan 1 7:00u -7:00 - MST 1927 Jun 10 -6:00 - CST 1930 Nov 15 @@ -2840,9 +2873,7 @@ Zone America/Tijuana -7:48:04 - LMT 1922 Jan 1 7:00u -8:00 1:00 PDT 1951 Sep 30 2:00 -8:00 - PST 1952 Apr 27 2:00 -8:00 1:00 PDT 1952 Sep 28 2:00 - -8:00 - PST 1954 - -8:00 CA P%sT 1961 - -8:00 - PST 1976 + -8:00 CA P%sT 1967 -8:00 US P%sT 1996 -8:00 Mexico P%sT 2001 -8:00 US P%sT 2002 Feb 20 diff --git a/src/java.base/share/data/tzdata/southamerica b/src/java.base/share/data/tzdata/southamerica index ca3c338591f..f932d5a72a1 100644 --- a/src/java.base/share/data/tzdata/southamerica +++ b/src/java.base/share/data/tzdata/southamerica @@ -27,9 +27,9 @@ # 2009-05-17 by Arthur David Olson. # This file is by no means authoritative; if you think you know better, -# go ahead and edit the file (and please send any changes to -# tz@iana.org for general use in the future). For more, please see -# the file CONTRIBUTING in the tz distribution. +# go ahead and edit the file, and please send any changes to +# the public mailing list tz@iana.org for general use in the future. +# For more, please see the file CONTRIBUTING in the tz distribution. # From Paul Eggert (2016-12-05): # diff --git a/src/java.base/unix/native/libjava/io_util_md.c b/src/java.base/unix/native/libjava/io_util_md.c index 2e81cbd05c2..bcac334191c 100644 --- a/src/java.base/unix/native/libjava/io_util_md.c +++ b/src/java.base/unix/native/libjava/io_util_md.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2025, 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 @@ #include "jvm.h" #include "io_util.h" #include "io_util_md.h" +#include #include #include @@ -75,20 +76,26 @@ FD handleOpen(const char *path, int oflag, int mode) { FD fd; RESTARTABLE(open(path, oflag, mode), fd); - if (fd != -1) { - struct stat buf; - int result; - RESTARTABLE(fstat(fd, &buf), result); - if (result != -1) { - if (S_ISDIR(buf.st_mode)) { - close(fd); - errno = EISDIR; - fd = -1; - } - } else { + // No further checking is needed if the file is not a + // directory or open returned an error + if (fd == -1 || ((oflag & O_ACCMODE) != O_RDONLY) != 0) { + return fd; + } + + // FileInputStream is specified to throw if the + // file is a directory + struct stat buf; + int result; + RESTARTABLE(fstat(fd, &buf), result); + if (result != -1) { + if (S_ISDIR(buf.st_mode)) { close(fd); + errno = EISDIR; fd = -1; } + } else { + close(fd); + fd = -1; } return fd; } diff --git a/src/java.compiler/share/classes/javax/lang/model/element/AnnotationMirror.java b/src/java.compiler/share/classes/javax/lang/model/element/AnnotationMirror.java index 2d92504edb6..2ffed3f7942 100644 --- a/src/java.compiler/share/classes/javax/lang/model/element/AnnotationMirror.java +++ b/src/java.compiler/share/classes/javax/lang/model/element/AnnotationMirror.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, 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 @@ -36,6 +36,8 @@ import javax.lang.model.type.DeclaredType; * method. There is no guarantee that any particular annotation will * always be represented by the same object. * + * @jls 9.6 Annotation Interfaces + * @jls 9.7 Annotations * @since 1.6 */ public interface AnnotationMirror { diff --git a/src/java.compiler/share/classes/javax/lang/model/element/AnnotationValue.java b/src/java.compiler/share/classes/javax/lang/model/element/AnnotationValue.java index 77521dac191..71594d31150 100644 --- a/src/java.compiler/share/classes/javax/lang/model/element/AnnotationValue.java +++ b/src/java.compiler/share/classes/javax/lang/model/element/AnnotationValue.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, 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,16 @@ package javax.lang.model.element; /** * Represents a value of an annotation interface element. - * A value is of one of the following types: - *

  • a wrapper class (such as {@link Integer}) for a primitive type - *
  • {@code String} - *
  • {@code TypeMirror} - *
  • {@code VariableElement} (representing an enum constant) - *
  • {@code AnnotationMirror} + * A value is of one of the following types (JLS {@jls 9.6.1}): + *
    • a {@linkplain java.lang##wrapperClass wrapper class} to hold a + * primitive type, such as an {@code Integer} object to hold an + * {@code int} + *
    • {@code String} representing a {@code String} + *
    • {@link javax.lang.model.type.TypeMirror TypeMirror} representing a {@code Class} literal + *
    • {@link VariableElement} representing an enum constant + *
    • {@link AnnotationMirror} representing an annotation *
    • {@code List} - * (representing the elements, in declared order, if the value is an array) + * representing the elements, in declared order, if the value is an array *
    * * @since 1.6 diff --git a/src/java.compiler/share/classes/javax/lang/model/element/ExecutableElement.java b/src/java.compiler/share/classes/javax/lang/model/element/ExecutableElement.java index 18923463248..cc0924fda61 100644 --- a/src/java.compiler/share/classes/javax/lang/model/element/ExecutableElement.java +++ b/src/java.compiler/share/classes/javax/lang/model/element/ExecutableElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, 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 @@ -37,6 +37,13 @@ import javax.lang.model.type.*; * clause, among other restrictions; see JLS {@jls 9.6.1} for details. * * @see ExecutableType + * @jls 8.4 Method Declarations + * @jls 8.6 Instance Initializers + * @jls 8.7 Static Initializers + * @jls 8.8 Constructor Declarations + * @jls 9.4 Method Declarations + * @jls 9.6.1 Annotation Interface Elements + * * @since 1.6 */ public interface ExecutableElement extends Element, Parameterizable { diff --git a/src/java.compiler/share/classes/javax/lang/model/element/PackageElement.java b/src/java.compiler/share/classes/javax/lang/model/element/PackageElement.java index 651bbe70eee..79b1fb84683 100644 --- a/src/java.compiler/share/classes/javax/lang/model/element/PackageElement.java +++ b/src/java.compiler/share/classes/javax/lang/model/element/PackageElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, 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 @@ -58,6 +58,8 @@ import javax.lang.model.type.TypeMirror; *
* * @see javax.lang.model.util.Elements#getPackageOf + * @jls 7.4 Package Declarations + * * @since 1.6 */ public interface PackageElement extends Element, QualifiedNameable { @@ -87,6 +89,7 @@ public interface PackageElement extends Element, QualifiedNameable { * @return the fully qualified name of this package, or an * empty name if this is an unnamed package * @jls 6.7 Fully Qualified Names and Canonical Names + * @jls 7.4.1 Named Packages */ Name getQualifiedName(); diff --git a/src/java.compiler/share/classes/javax/lang/model/element/Parameterizable.java b/src/java.compiler/share/classes/javax/lang/model/element/Parameterizable.java index cf0bbdfba37..a4280fbcf29 100644 --- a/src/java.compiler/share/classes/javax/lang/model/element/Parameterizable.java +++ b/src/java.compiler/share/classes/javax/lang/model/element/Parameterizable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2026, 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,10 @@ import java.util.List; /** * A mixin interface for an element that has type parameters. * + * @jls 4.5 Parameterized Types + * @jls 8.4.4 Generic Methods + * @jls 8.8.4 Generic Constructors + * * @since 1.7 */ public interface Parameterizable extends Element { diff --git a/src/java.compiler/share/classes/javax/lang/model/element/QualifiedNameable.java b/src/java.compiler/share/classes/javax/lang/model/element/QualifiedNameable.java index 1b0316f893f..555d90c1b13 100644 --- a/src/java.compiler/share/classes/javax/lang/model/element/QualifiedNameable.java +++ b/src/java.compiler/share/classes/javax/lang/model/element/QualifiedNameable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2026, 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 @@ -28,6 +28,10 @@ package javax.lang.model.element; /** * A mixin interface for an element that has a qualified name. * + * @jls 6.5.3.2 Qualified Package Names + * @jls 6.5.5.2 Qualified Type Names + * @jls 6.7 Fully Qualified Names and Canonical Names + * * @since 1.7 */ public interface QualifiedNameable extends Element { diff --git a/src/java.compiler/share/classes/javax/lang/model/element/TypeElement.java b/src/java.compiler/share/classes/javax/lang/model/element/TypeElement.java index abf95bcefad..3dcc8e8c7fd 100644 --- a/src/java.compiler/share/classes/javax/lang/model/element/TypeElement.java +++ b/src/java.compiler/share/classes/javax/lang/model/element/TypeElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, 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 @@ -80,7 +80,16 @@ import javax.lang.model.util.*; * javax.lang.model.util.Elements#getAllTypeElements(CharSequence) * queried for} in the configured environment * + * * @see DeclaredType + * @jls 8.1 Class Declarations + * @jls 8.5 Member Class and Interface Declarations + * @jls 8.9 Enum Classes + * @jls 8.10 Record Classes + * @jls 9.1 Interface Declarations + * @jls 9.5 Member Class and Interface Declarations + * @jls 9.6 Annotation Interfaces + * * @since 1.6 */ public interface TypeElement extends Element, Parameterizable, QualifiedNameable { diff --git a/src/java.compiler/share/classes/javax/lang/model/element/TypeParameterElement.java b/src/java.compiler/share/classes/javax/lang/model/element/TypeParameterElement.java index cbaa8969126..abd06a3e038 100644 --- a/src/java.compiler/share/classes/javax/lang/model/element/TypeParameterElement.java +++ b/src/java.compiler/share/classes/javax/lang/model/element/TypeParameterElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, 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 @@ -35,6 +35,11 @@ import javax.lang.model.type.TypeVariable; * A type parameter declares a {@link TypeVariable}. * * @see TypeVariable + * @jls 8.1.2 Generic Classes and Type Parameters + * @jls 8.4.4 Generic Methods + * @jls 8.8.4 Generic Constructors + * @jls 9.1.2 Generic Interfaces and Type Parameters + * * @since 1.6 */ public interface TypeParameterElement extends Element { diff --git a/src/java.compiler/share/classes/javax/lang/model/element/VariableElement.java b/src/java.compiler/share/classes/javax/lang/model/element/VariableElement.java index 4d2b2582901..b8f42c46b1e 100644 --- a/src/java.compiler/share/classes/javax/lang/model/element/VariableElement.java +++ b/src/java.compiler/share/classes/javax/lang/model/element/VariableElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, 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 @@ -34,6 +34,14 @@ import javax.lang.model.type.TypeKind; * parameter, local variable, resource variable, or exception * parameter. * + * @jls 8.3 Field Declaration + * @jls 8.9.1 Enum Constants + * @jls 8.4.1 Formal Parameters + * @jls 8.8.1 Formal Parameters + * @jls 14.4 Local Variable Declarations + * @jls 14.20 The {@code try} statement + * @jls 14.20.3 {@code try}-with-resources + * @since 1.6 */ public interface VariableElement extends Element { diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java index da1785a9a63..5e68cc7a82c 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java @@ -35,8 +35,6 @@ import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.UIResource; -import sun.awt.AppContext; - import sun.lwawt.macosx.CPlatformWindow; import sun.swing.SwingUtilities2; @@ -150,13 +148,34 @@ final class AquaUtils { protected abstract T create(); } - abstract static class RecyclableSingleton { - final T get() { - return AppContext.getSoftReferenceValue(this, () -> getInstance()); - } + abstract static class LazySingleton { + T instance; - void reset() { - AppContext.getAppContext().remove(this); + final T get() { + if (instance == null) { + instance = getInstance(); + } + return instance; + } + + abstract T getInstance(); + } + + abstract static class RecyclableSingleton { + + SoftReference ref; + + final T get() { + T instance; + if (ref != null) { + instance = ref.get(); + if (instance != null) { + return instance; + } + } + instance = getInstance(); + ref = new SoftReference<>(instance); + return instance; } abstract T getInstance(); @@ -197,11 +216,11 @@ final class AquaUtils { protected abstract V getInstance(K key); } - private static final RecyclableSingleton enableAnimations = new RecyclableSingleton() { + private static final LazySingleton enableAnimations = new LazySingleton() { @Override protected Boolean getInstance() { - final String sizeProperty = System.getProperty(ANIMATIONS_PROPERTY); - return !"false".equals(sizeProperty); // should be true by default + final String animationsProperty = System.getProperty(ANIMATIONS_PROPERTY); + return !"false".equals(animationsProperty); // should be true by default } }; private static boolean animationsEnabled() { diff --git a/src/java.desktop/share/classes/java/awt/font/FontRenderContext.java b/src/java.desktop/share/classes/java/awt/font/FontRenderContext.java index e6cac8fe4a9..60e7e6e5ebd 100644 --- a/src/java.desktop/share/classes/java/awt/font/FontRenderContext.java +++ b/src/java.desktop/share/classes/java/awt/font/FontRenderContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2026, 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 @@ -62,19 +62,18 @@ import java.awt.geom.AffineTransform; * @see java.awt.Graphics2D#getFontRenderContext() * @see java.awt.font.LineMetrics */ - public class FontRenderContext { - private transient AffineTransform tx; - private transient Object aaHintValue; - private transient Object fmHintValue; - private transient boolean defaulting; + private final transient AffineTransform tx; + private final transient Object aaHintValue; + private final transient Object fmHintValue; + private final transient boolean defaulting; /** * Constructs a new {@code FontRenderContext} * object. - * */ protected FontRenderContext() { + tx = null; aaHintValue = VALUE_TEXT_ANTIALIAS_DEFAULT; fmHintValue = VALUE_FRACTIONALMETRICS_DEFAULT; defaulting = true; @@ -105,6 +104,8 @@ public class FontRenderContext { boolean usesFractionalMetrics) { if (tx != null && !tx.isIdentity()) { this.tx = new AffineTransform(tx); + } else { + this.tx = null; } if (isAntiAliased) { aaHintValue = VALUE_TEXT_ANTIALIAS_ON; @@ -116,6 +117,7 @@ public class FontRenderContext { } else { fmHintValue = VALUE_FRACTIONALMETRICS_OFF; } + defaulting = false; } /** @@ -145,6 +147,8 @@ public class FontRenderContext { public FontRenderContext(AffineTransform tx, Object aaHint, Object fmHint){ if (tx != null && !tx.isIdentity()) { this.tx = new AffineTransform(tx); + } else { + this.tx = null; } try { if (KEY_TEXT_ANTIALIASING.isCompatibleValue(aaHint)) { @@ -164,6 +168,7 @@ public class FontRenderContext { } catch (Exception e) { throw new IllegalArgumentException("FM hint:" +fmHint); } + defaulting = false; } /** diff --git a/src/java.desktop/share/classes/java/awt/font/TextLine.java b/src/java.desktop/share/classes/java/awt/font/TextLine.java index 6db1bc72360..57b9c0c642a 100644 --- a/src/java.desktop/share/classes/java/awt/font/TextLine.java +++ b/src/java.desktop/share/classes/java/awt/font/TextLine.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2026, 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 @@ -396,10 +396,7 @@ final class TextLine { BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = im.createGraphics(); - g2d.setColor(Color.WHITE); - g2d.fillRect(0, 0, im.getWidth(), im.getHeight()); - - g2d.setColor(Color.BLACK); + g2d.setColor(Color.WHITE); // white over transparent black bg draw(g2d, rx + MARGIN - bounds.x, ry + MARGIN - bounds.y); result = computePixelBounds(im); @@ -428,7 +425,7 @@ final class TextLine { loop: while (++t < h) { im.getRGB(0, t, buf.length, 1, buf, 0, w); // w ignored for (int i = 0; i < buf.length; i++) { - if (buf[i] != -1) { + if (buf[i] != 0) { break loop; } } @@ -441,7 +438,7 @@ final class TextLine { loop: while (--b > t) { im.getRGB(0, b, buf.length, 1, buf, 0, w); // w ignored for (int i = 0; i < buf.length; ++i) { - if (buf[i] != -1) { + if (buf[i] != 0) { break loop; } } @@ -454,7 +451,7 @@ final class TextLine { loop: while (++l < r) { for (int i = t; i < b; ++i) { int v = im.getRGB(l, i); - if (v != -1) { + if (v != 0) { break loop; } } @@ -466,7 +463,7 @@ final class TextLine { loop: while (--r > l) { for (int i = t; i < b; ++i) { int v = im.getRGB(r, i); - if (v != -1) { + if (v != 0) { break loop; } } diff --git a/src/java.desktop/share/classes/sun/awt/AppContext.java b/src/java.desktop/share/classes/sun/awt/AppContext.java index 39df737badb..01b1dd09887 100644 --- a/src/java.desktop/share/classes/sun/awt/AppContext.java +++ b/src/java.desktop/share/classes/sun/awt/AppContext.java @@ -47,7 +47,6 @@ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; /** * The AppContext is a table referenced by ThreadGroup which stores @@ -735,24 +734,6 @@ public final class AppContext { } return changeSupport.getPropertyChangeListeners(propertyName); } - - public static T getSoftReferenceValue(Object key, - Supplier supplier) { - - final AppContext appContext = AppContext.getAppContext(); - @SuppressWarnings("unchecked") - SoftReference ref = (SoftReference) appContext.get(key); - if (ref != null) { - final T object = ref.get(); - if (object != null) { - return object; - } - } - final T object = supplier.get(); - ref = new SoftReference<>(object); - appContext.put(key, ref); - return object; - } } final class MostRecentKeyValue { diff --git a/src/java.desktop/share/classes/sun/awt/image/ImageCache.java b/src/java.desktop/share/classes/sun/awt/image/ImageCache.java index eed1aa5bdb7..b7ac69923da 100644 --- a/src/java.desktop/share/classes/sun/awt/image/ImageCache.java +++ b/src/java.desktop/share/classes/sun/awt/image/ImageCache.java @@ -29,7 +29,6 @@ import java.awt.*; import java.lang.ref.*; import java.util.*; import java.util.concurrent.locks.*; -import sun.awt.AppContext; /** * ImageCache - A fixed pixel count sized cache of Images keyed by arbitrary @@ -37,8 +36,6 @@ import sun.awt.AppContext; * dropped by the GC if heap memory gets tight. When our size hits max pixel * count least recently requested images are removed first. * - * The ImageCache must be used from the thread with an AppContext only. - * */ public final class ImageCache { @@ -56,9 +53,10 @@ public final class ImageCache { // Reference queue for tracking lost softreferences to images in the cache private final ReferenceQueue referenceQueue = new ReferenceQueue<>(); + private static final ImageCache instance = new ImageCache(); + public static ImageCache getInstance() { - return AppContext.getSoftReferenceValue(ImageCache.class, - () -> new ImageCache()); + return instance; } ImageCache(final int maxPixelCount) { diff --git a/src/java.desktop/share/classes/sun/awt/image/PNGImageDecoder.java b/src/java.desktop/share/classes/sun/awt/image/PNGImageDecoder.java index 357ad3be43f..08909b802c5 100644 --- a/src/java.desktop/share/classes/sun/awt/image/PNGImageDecoder.java +++ b/src/java.desktop/share/classes/sun/awt/image/PNGImageDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2026, 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 @@ -302,8 +302,16 @@ public class PNGImageDecoder extends ImageDecoder int bitsPerPixel = samplesPerPixel*bitDepth; int bytesPerPixel = (bitsPerPixel+7)>>3; int pass, passLimit; - if(interlaceMethod==0) { pass = -1; passLimit = 0; } - else { pass = 0; passLimit = 7; } + boolean isDirectByteCopy; + if(interlaceMethod==0) { + pass = -1; + passLimit = 0; + isDirectByteCopy = bPixels != null && bitDepth == 8; + } else { + pass = 0; + passLimit = 7; + isDirectByteCopy = false; + } while(++pass<=passLimit) { int row = startingRow[pass]; int rowInc = rowIncrement[pass]; @@ -334,7 +342,11 @@ public class PNGImageDecoder extends ImageDecoder int spos=0; int pixel = 0; while (col < width) { - if(wPixels !=null) { + if (isDirectByteCopy) { + System.arraycopy(rowByteBuffer, spos, bPixels, col + rowOffset, width); + spos += width; + break; + } else if(wPixels !=null) { switch(combinedType) { case COLOR|ALPHA|(8<<3): wPixels[col+rowOffset] = diff --git a/src/jdk.charsets/share/classes/sun/nio/cs/ext/EUC_JP.java.template b/src/jdk.charsets/share/classes/sun/nio/cs/ext/EUC_JP.java.template index f3d03a9e9c7..4fc0b2796ee 100644 --- a/src/jdk.charsets/share/classes/sun/nio/cs/ext/EUC_JP.java.template +++ b/src/jdk.charsets/share/classes/sun/nio/cs/ext/EUC_JP.java.template @@ -309,7 +309,7 @@ public class EUC_JP try { if (enc0201.isASCIICompatible()) { - int n = JLA.encodeASCII(sa, sp, da, dp, Math.min(dl - dp, sl - sp)); + int n = JLA.uncheckedEncodeASCII(sa, sp, da, dp, Math.min(dl - dp, sl - sp)); sp += n; dp += n; } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java index 3a8b4e5dbea..773c573c201 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java @@ -37,11 +37,7 @@ import java.util.Set; import java.util.stream.Stream; import com.sun.tools.javac.main.Option; -import com.sun.tools.javac.tree.JCTree.*; -import com.sun.tools.javac.util.Assert; import com.sun.tools.javac.util.Context; -import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; -import com.sun.tools.javac.util.JCDiagnostic.LintWarning; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Names; import com.sun.tools.javac.util.Options; @@ -178,6 +174,14 @@ public class Lint { /** * Categories of warnings that can be generated by the compiler. + * Each lint category has a logical name (a string), which is the string used e.g. in a {@code SuppressWarning} annotation. + * To ensure automation, the enum field name for a lint category string {@code C} should be obtained by: + *
    + *
  1. capitalize all the letters in {@code C}, and
  2. + *
  3. replacing any occurrence of {@code -} with {@code _}
  4. + *
+ * For instance, the lint category string {@code dangling-doc-comments} corresponds to the enum field + * {@code DANGLING_DOC_COMMENTS}. */ public enum LintCategory { /** @@ -320,7 +324,7 @@ public class Lint { /** * Warn about unchecked operations on raw types. */ - RAW("rawtypes"), + RAWTYPES("rawtypes"), /** * Warn about use of deprecated-for-removal items. diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Instrumentation.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Instrumentation.java index dbafca4ed3c..e06d361b203 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Instrumentation.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Instrumentation.java @@ -58,7 +58,13 @@ final class Instrumentation { } public void addMethod(long methodId, String name, String signature, int modification) { - modificationMap.put(name + signature, new Method(methodId, Modification.valueOf(modification), className + "::" + name)); + Method method = new Method( + methodId, + Modification.valueOf(modification), + name.equals(""), + className + "::" + name + ); + modificationMap.put(name + signature, method); } public List getMethods() { @@ -71,7 +77,7 @@ final class Instrumentation { ClassModel classModel = classFile.parse(bytecode); byte[] generated = classFile.build(classModel.thisClass().asSymbol(), classBuilder -> { for (var ce : classModel) { - if (modifyClassElement(classBuilder, ce)) { + if (modifyClassElement(classModel, classBuilder, ce)) { modified[0] = true; } else { classBuilder.with(ce); @@ -93,7 +99,7 @@ final class Instrumentation { } } - private boolean modifyClassElement(ClassBuilder classBuilder, ClassElement ce) { + private boolean modifyClassElement(ClassModel classModel, ClassBuilder classBuilder, ClassElement ce) { if (ce instanceof MethodModel mm) { String method = mm.methodName().stringValue(); String signature = mm.methodType().stringValue(); @@ -102,15 +108,15 @@ final class Instrumentation { if (tm != null) { Modification m = tm.modification(); if (m.tracing() || m.timing()) { - return modifyMethod(classBuilder, mm, tm); + return modifyMethod(classModel, classBuilder, mm, tm); } } } return false; } - private boolean modifyMethod(ClassBuilder classBuilder, MethodModel m, Method method) { - var code = m.code(); + private boolean modifyMethod(ClassModel classModel, ClassBuilder classBuilder, MethodModel methodModel, Method method) { + var code = methodModel.code(); if (code.isPresent()) { if (classLoader == null && ExcludeList.containsMethod(method.name())) { String msg = "Risk of recursion, skipping bytecode generation of " + method.name(); @@ -118,9 +124,9 @@ final class Instrumentation { return false; } MethodTransform s = MethodTransform.ofStateful( - () -> MethodTransform.transformingCode(new Transform(method)) + () -> MethodTransform.transformingCode(new Transform(classModel, code.get(), method)) ); - classBuilder.transformMethod(m, s); + classBuilder.transformMethod(methodModel, s); return true; } return false; diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Method.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Method.java index d685083153d..d85e458e9d5 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Method.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Method.java @@ -31,7 +31,7 @@ import jdk.jfr.internal.Logger; /** * Class that holds information about an instrumented method. */ -record Method(long methodId, Modification modification, String name) { +record Method(long methodId, Modification modification, boolean constructor, String name) { @Override public String toString() { return name + (modification.timing() ? " +timing" : " -timing") + (modification.tracing() ? " +tracing" : " -tracing") + " (Method ID: " + String.format("0x%08X)", methodId); diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Transform.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Transform.java index cd65a119cee..377eede7925 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Transform.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/tracing/Transform.java @@ -24,13 +24,19 @@ */ package jdk.jfr.internal.tracing; +import java.lang.classfile.ClassModel; import java.lang.classfile.CodeBuilder; import java.lang.classfile.CodeElement; +import java.lang.classfile.CodeModel; import java.lang.classfile.CodeTransform; +import java.lang.classfile.Label; import java.lang.classfile.TypeKind; +import java.lang.classfile.instruction.InvokeInstruction; import java.lang.classfile.instruction.ReturnInstruction; import java.lang.classfile.instruction.ThrowInstruction; import java.lang.constant.ClassDesc; +import java.util.ArrayList; +import java.util.List; import jdk.jfr.internal.util.Bytecode; import jdk.jfr.internal.util.Bytecode.MethodDesc; @@ -43,59 +49,208 @@ import jdk.jfr.tracing.MethodTracer; * The method ID is determined by native code. */ final class Transform implements CodeTransform { + private static class TryBlock { + Label start; + Label end; + } private static final ClassDesc METHOD_TRACER_CLASS = ClassDesc.of(MethodTracer.class.getName()); private static final MethodDesc TRACE_METHOD = MethodDesc.of("trace", "(JJ)V"); private static final MethodDesc TIMING_METHOD = MethodDesc.of("timing", "(JJ)V"); private static final MethodDesc TRACE_TIMING_METHOD = MethodDesc.of("traceTiming", "(JJ)V"); private static final MethodDesc TIMESTAMP_METHOD = MethodDesc.of("timestamp", "()J"); + private final List tryBlocks = new ArrayList<>(); + private final boolean simplifiedInstrumentation; + private final ClassModel classModel; private final Method method; private int timestampSlot = -1; - Transform(Method method) { + Transform(ClassModel classModel, CodeModel model, Method method) { this.method = method; + this.classModel = classModel; + // The JVMS (not the JLS) allows multiple mutually exclusive super/this. + // invocations in a constructor body as long as only one lies on any given + // execution path. For example, this is valid bytecode: + // + // Foo(boolean value) { + // if (value) { + // staticMethodThatMayThrow(); + // super(); + // } else { + // try { + // if (value == 0) { + // throw new Exception(""); + // } + // } catch (Throwable t) { + // throw t; + // } + // super(); + // } + // } + // + // If such a method is found, instrumentation falls back to instrumenting only + // RET and ATHROW. This can cause exceptions to be missed or counted twice. + // + // An effect of this heuristic is that constructors like the one below + // will also trigger simplified instrumentation. + // + // class Bar { + // } + // + // class Foo extends Bar { + // Foo() { + // new Bar(); + // } + // } + // + // java.lang.Object:: with zero constructor invocations should use simplified instrumentation + this.simplifiedInstrumentation = method.constructor() && constructorInvocations(model.elementList()) != 1; + } + + private int constructorInvocations(List elementList) { + int count = 0; + for (CodeElement e : elementList) { + if (isConstructorInvocation(e)) { + count++; + } + } + return count; + } + + private boolean isConstructorInvocation(CodeElement element) { + if (element instanceof InvokeInstruction inv && inv.name().equalsString("")) { + if (classModel.thisClass().equals(inv.owner())) { + return true; + } + if (classModel.superclass().isPresent()) { + return classModel.superclass().get().equals(inv.owner()); + } + } + return false; } @Override - public final void accept(CodeBuilder builder, CodeElement element) { + public void accept(CodeBuilder builder, CodeElement element) { + if (simplifiedInstrumentation) { + acceptSimplifiedInstrumentation(builder, element); + return; + } + if (method.constructor()) { + acceptConstructor(builder, element, isConstructorInvocation(element)); + } else { + acceptMethod(builder, element); + } + } + + @Override + public void atEnd(CodeBuilder builder) { + endTryBlock(builder); + for (TryBlock block : tryBlocks) { + addCatchHandler(block, builder); + } + } + + private void acceptConstructor(CodeBuilder builder, CodeElement element, boolean isConstructorInvocation) { + if (timestampSlot == -1) { + timestampSlot = invokeTimestamp(builder); + builder.lstore(timestampSlot); + if (!isConstructorInvocation) { + beginTryBlock(builder); + } + } + if (isConstructorInvocation) { + endTryBlock(builder); + builder.with(element); + beginTryBlock(builder); + return; + } + if (element instanceof ReturnInstruction) { + addTracing(builder); + } + builder.with(element); + } + + private void endTryBlock(CodeBuilder builder) { + if (tryBlocks.isEmpty()) { + return; + } + TryBlock last = tryBlocks.getLast(); + if (last.end == null) { + last.end = builder.newBoundLabel(); + } + } + + private void beginTryBlock(CodeBuilder builder) { + TryBlock block = new TryBlock(); + block.start = builder.newBoundLabel(); + tryBlocks.add(block); + } + + private void acceptSimplifiedInstrumentation(CodeBuilder builder, CodeElement element) { if (timestampSlot == -1) { timestampSlot = invokeTimestamp(builder); builder.lstore(timestampSlot); } if (element instanceof ReturnInstruction || element instanceof ThrowInstruction) { - builder.lload(timestampSlot); - builder.ldc(method.methodId()); - Modification modification = method.modification(); - boolean objectInit = method.name().equals("java.lang.Object::"); - String suffix = objectInit ? "ObjectInit" : ""; - if (modification.timing()) { - if (modification.tracing()) { - invokeTraceTiming(builder, suffix); - } else { - invokeTiming(builder, suffix); - } - } else { - if (modification.tracing()) { - invokeTrace(builder, suffix); - } - } + addTracing(builder); } builder.with(element); } - public static void invokeTiming(CodeBuilder builder, String suffix) { + private void acceptMethod(CodeBuilder builder, CodeElement element) { + if (timestampSlot == -1) { + timestampSlot = invokeTimestamp(builder); + builder.lstore(timestampSlot); + beginTryBlock(builder); + } + if (element instanceof ReturnInstruction) { + addTracing(builder); + } + builder.with(element); + } + + private void addCatchHandler(TryBlock block, CodeBuilder builder) { + Label catchHandler = builder.newBoundLabel(); + int exceptionSlot = builder.allocateLocal(TypeKind.REFERENCE); + builder.astore(exceptionSlot); + addTracing(builder); + builder.aload(exceptionSlot); + builder.athrow(); + builder.exceptionCatchAll(block.start, block.end, catchHandler); + } + + private void addTracing(CodeBuilder builder) { + builder.lload(timestampSlot); + builder.ldc(method.methodId()); + Modification modification = method.modification(); + boolean objectInit = method.name().equals("java.lang.Object::"); + String suffix = objectInit ? "ObjectInit" : ""; + if (modification.timing()) { + if (modification.tracing()) { + invokeTraceTiming(builder, suffix); + } else { + invokeTiming(builder, suffix); + } + } else { + if (modification.tracing()) { + invokeTrace(builder, suffix); + } + } + } + + private static void invokeTiming(CodeBuilder builder, String suffix) { builder.invokestatic(METHOD_TRACER_CLASS, TIMING_METHOD.name() + suffix, TIMING_METHOD.descriptor()); } - public static void invokeTrace(CodeBuilder builder, String suffix) { + private static void invokeTrace(CodeBuilder builder, String suffix) { builder.invokestatic(METHOD_TRACER_CLASS, TRACE_METHOD.name() + suffix, TRACE_METHOD.descriptor()); } - public static void invokeTraceTiming(CodeBuilder builder, String suffix) { + private static void invokeTraceTiming(CodeBuilder builder, String suffix) { builder.invokestatic(METHOD_TRACER_CLASS, TRACE_TIMING_METHOD.name() + suffix, TRACE_TIMING_METHOD.descriptor()); } - public static int invokeTimestamp(CodeBuilder builder) { + private static int invokeTimestamp(CodeBuilder builder) { Bytecode.invokestatic(builder, METHOD_TRACER_CLASS, TIMESTAMP_METHOD); return builder.allocateLocal(TypeKind.LONG); } diff --git a/src/jdk.jlink/share/man/jlink.md b/src/jdk.jlink/share/man/jlink.md index 0d16e69c9ef..5c77202434c 100644 --- a/src/jdk.jlink/share/man/jlink.md +++ b/src/jdk.jlink/share/man/jlink.md @@ -1,5 +1,5 @@ --- -# Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2017, 2026, 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 @@ -70,6 +70,7 @@ Developers are responsible for updating their custom runtime images. and zip-9 provides the best compression. Default is zip-6. : Deprecated values to be removed in a future release: + - `0`: No compression. Use zip-0 instead. - `1`: Constant string sharing - `2`: ZIP. Use zip-6 instead. @@ -182,6 +183,7 @@ Description and zip-9 provides the best compression. Default is zip-6. : Deprecated values to be removed in a future release: + - Level 0: No compression. Use zip-0 instead. - Level 1: Constant string sharing - Level 2: ZIP. Use zip-6 instead. diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/DesktopIntegration.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/DesktopIntegration.java index dbaa5e3eec6..523b6c4821c 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/DesktopIntegration.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/DesktopIntegration.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ -50,6 +50,7 @@ import jdk.jpackage.internal.model.LinuxLauncher; import jdk.jpackage.internal.model.LinuxPackage; import jdk.jpackage.internal.model.Package; import jdk.jpackage.internal.util.CompositeProxy; +import jdk.jpackage.internal.util.Enquoter; import jdk.jpackage.internal.util.PathUtils; import jdk.jpackage.internal.util.XmlUtils; diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LibProvidersLookup.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LibProvidersLookup.java index 55200b908cd..6faacbca528 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LibProvidersLookup.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LibProvidersLookup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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,13 +27,12 @@ package jdk.jpackage.internal; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.List; import java.util.Collection; -import java.util.Objects; import java.util.Collections; -import java.util.Set; -import java.util.ArrayList; import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.Set; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -48,9 +47,6 @@ public final class LibProvidersLookup { return (new ToolValidator(TOOL_LDD).validate() == null); } - public LibProvidersLookup() { - } - LibProvidersLookup setPackageLookup(PackageLookup v) { packageLookup = v; return this; @@ -87,23 +83,20 @@ public final class LibProvidersLookup { } private static List getNeededLibsForFile(Path path) throws IOException { - List result = new ArrayList<>(); - int ret = Executor.of(TOOL_LDD, path.toString()).setOutputConsumer(lines -> { - lines.map(line -> { - Matcher matcher = LIB_IN_LDD_OUTPUT_REGEX.matcher(line); - if (matcher.find()) { - return matcher.group(1); - } - return null; - }).filter(Objects::nonNull).map(Path::of).forEach(result::add); - }).execute(); + final var result = Executor.of(TOOL_LDD, path.toString()).saveOutput().execute(); - if (ret != 0) { + if (result.getExitCode() != 0) { // objdump failed. This is OK if the tool was applied to not a binary file return Collections.emptyList(); } - return result; + return result.stdout().stream().map(line -> { + Matcher matcher = LIB_IN_LDD_OUTPUT_REGEX.matcher(line); + if (matcher.find()) { + return matcher.group(1); + } + return null; + }).filter(Objects::nonNull).map(Path::of).toList(); } private static Collection getNeededLibsForFiles(List paths) { diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxBundlingEnvironment.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxBundlingEnvironment.java index 6e438e66a26..d2169ede461 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxBundlingEnvironment.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxBundlingEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -33,6 +33,7 @@ import static jdk.jpackage.internal.cli.StandardBundlingOperation.CREATE_LINUX_R import java.util.Map; import java.util.Optional; +import java.util.function.Supplier; import java.util.stream.Stream; import jdk.jpackage.internal.cli.Options; import jdk.jpackage.internal.cli.StandardBundlingOperation; @@ -44,19 +45,34 @@ import jdk.jpackage.internal.util.Result; public class LinuxBundlingEnvironment extends DefaultBundlingEnvironment { public LinuxBundlingEnvironment() { - super(build() - .defaultOperation(() -> { - return LazyLoad.SYS_ENV.value().map(LinuxSystemEnvironment::nativePackageType).map(DESCRIPTORS::get); - }) - .bundler(CREATE_LINUX_APP_IMAGE, LinuxBundlingEnvironment::createAppImage) - .bundler(CREATE_LINUX_DEB, LazyLoad::debSysEnv, LinuxBundlingEnvironment::createDebPackage) - .bundler(CREATE_LINUX_RPM, LazyLoad::rpmSysEnv, LinuxBundlingEnvironment::createRpmPackage)); + super(build().mutate(builder -> { + + // Wrap the generic Linux system environment supplier in the run-once wrapper + // as this supplier is called from both RPM and DEB Linux system environment suppliers. + var sysEnv = runOnce(() -> { + return LinuxSystemEnvironment.create(); + }); + + Supplier> debSysEnv = () -> { + return LinuxDebSystemEnvironment.create(sysEnv.get()); + }; + + Supplier> rpmSysEnv = () -> { + return LinuxRpmSystemEnvironment.create(sysEnv.get()); + }; + + builder.defaultOperation(() -> { + return sysEnv.get().value().map(LinuxSystemEnvironment::nativePackageType).map(DESCRIPTORS::get); + }) + .bundler(CREATE_LINUX_DEB, debSysEnv, LinuxBundlingEnvironment::createDebPackage) + .bundler(CREATE_LINUX_RPM, rpmSysEnv, LinuxBundlingEnvironment::createRpmPackage); + }).bundler(CREATE_LINUX_APP_IMAGE, LinuxBundlingEnvironment::createAppImage)); } private static void createDebPackage(Options options, LinuxDebSystemEnvironment sysEnv) { createNativePackage(options, - LinuxFromOptions.createLinuxDebPackage(options), + LinuxFromOptions.createLinuxDebPackage(options, sysEnv), buildEnv()::create, LinuxBundlingEnvironment::buildPipeline, (env, pkg, outputDir) -> { @@ -67,7 +83,7 @@ public class LinuxBundlingEnvironment extends DefaultBundlingEnvironment { private static void createRpmPackage(Options options, LinuxRpmSystemEnvironment sysEnv) { createNativePackage(options, - LinuxFromOptions.createLinuxRpmPackage(options), + LinuxFromOptions.createLinuxRpmPackage(options, sysEnv), buildEnv()::create, LinuxBundlingEnvironment::buildPipeline, (env, pkg, outputDir) -> { @@ -90,23 +106,6 @@ public class LinuxBundlingEnvironment extends DefaultBundlingEnvironment { return new BuildEnvFromOptions().predefinedAppImageLayout(APPLICATION_LAYOUT); } - private static final class LazyLoad { - - static Result debSysEnv() { - return DEB_SYS_ENV; - } - - static Result rpmSysEnv() { - return RPM_SYS_ENV; - } - - private static final Result SYS_ENV = LinuxSystemEnvironment.create(); - - private static final Result DEB_SYS_ENV = LinuxDebSystemEnvironment.create(SYS_ENV); - - private static final Result RPM_SYS_ENV = LinuxRpmSystemEnvironment.create(SYS_ENV); - } - private static final Map DESCRIPTORS = Stream.of( CREATE_LINUX_DEB, CREATE_LINUX_RPM diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebPackager.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebPackager.java index 64a0368e9a0..0ec6a77e683 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebPackager.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebPackager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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,6 @@ package jdk.jpackage.internal; -import static jdk.jpackage.internal.model.StandardPackageType.LINUX_DEB; import static jdk.jpackage.internal.util.function.ThrowingFunction.toFunction; import java.io.IOException; @@ -76,11 +75,11 @@ final class LinuxDebPackager extends LinuxPackager { try { // Try the real path first as it works better on newer Ubuntu versions - return findProvidingPackages(realPath, sysEnv.dpkg()); + return findProvidingPackages(realPath, sysEnv); } catch (IOException ex) { // Try the default path if differ if (!realPath.equals(file)) { - return findProvidingPackages(file, sysEnv.dpkg()); + return findProvidingPackages(file, sysEnv); } else { throw ex; } @@ -107,7 +106,7 @@ final class LinuxDebPackager extends LinuxPackager { properties.forEach(property -> cmdline.add(property.name)); - Map actualValues = Executor.of(cmdline.toArray(String[]::new)) + Map actualValues = Executor.of(cmdline) .saveOutput(true) .executeExpectSuccess() .getOutput().stream() @@ -158,9 +157,8 @@ final class LinuxDebPackager extends LinuxPackager { cmdline.addAll(List.of("-b", env.appImageDir().toString(), debFile.toAbsolutePath().toString())); // run dpkg - RetryExecutor.retryOnKnownErrorMessage( - "semop(1): encountered an error: Invalid argument").execute( - cmdline.toArray(String[]::new)); + Executor.of(cmdline).retryOnKnownErrorMessage( + "semop(1): encountered an error: Invalid argument").execute(); Log.verbose(I18N.format("message.output-to-location", debFile.toAbsolutePath())); } @@ -233,7 +231,7 @@ final class LinuxDebPackager extends LinuxPackager { } } - private static Stream findProvidingPackages(Path file, Path dpkg) throws IOException { + private static Stream findProvidingPackages(Path file, LinuxDebSystemEnvironment sysEnv) throws IOException { // // `dpkg -S` command does glob pattern lookup. If not the absolute path // to the file is specified it might return mltiple package names. @@ -279,9 +277,9 @@ final class LinuxDebPackager extends LinuxPackager { Set archPackages = new HashSet<>(); Set otherPackages = new HashSet<>(); - var debArch = LinuxPackageArch.getValue(LINUX_DEB); + var debArch = sysEnv.packageArch().value(); - Executor.of(dpkg.toString(), "-S", file.toString()) + Executor.of(sysEnv.dpkg().toString(), "-S", file.toString()) .saveOutput(true).executeExpectSuccess() .getOutput().forEach(line -> { Matcher matcher = PACKAGE_NAME_REGEX.matcher(line); diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebSystemEnvironment.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebSystemEnvironment.java index 5b5decb7a67..d5480361452 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebSystemEnvironment.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebSystemEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -28,7 +28,7 @@ import static jdk.jpackage.internal.LinuxSystemEnvironment.mixin; import jdk.jpackage.internal.util.Result; -public interface LinuxDebSystemEnvironment extends LinuxSystemEnvironment, LinuxDebSystemEnvironmentMixin { +interface LinuxDebSystemEnvironment extends LinuxSystemEnvironment, LinuxDebSystemEnvironmentMixin { static Result create(Result base) { return mixin(LinuxDebSystemEnvironment.class, base, LinuxDebSystemEnvironmentMixin::create); diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebSystemEnvironmentMixin.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebSystemEnvironmentMixin.java index 8688327b353..2cf3e9e36e8 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebSystemEnvironmentMixin.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxDebSystemEnvironmentMixin.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -29,7 +29,7 @@ import java.util.Objects; import java.util.stream.Stream; import jdk.jpackage.internal.util.Result; -public interface LinuxDebSystemEnvironmentMixin { +interface LinuxDebSystemEnvironmentMixin { Path dpkg(); Path dpkgdeb(); Path fakeroot(); diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxFromOptions.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxFromOptions.java index 799c92ce2e1..0791c79c662 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxFromOptions.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxFromOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -70,9 +70,9 @@ final class LinuxFromOptions { return LinuxApplication.create(appBuilder.create()); } - static LinuxRpmPackage createLinuxRpmPackage(Options options) { + static LinuxRpmPackage createLinuxRpmPackage(Options options, LinuxRpmSystemEnvironment sysEnv) { - final var superPkgBuilder = createLinuxPackageBuilder(options, LINUX_RPM); + final var superPkgBuilder = createLinuxPackageBuilder(options, sysEnv, LINUX_RPM); final var pkgBuilder = new LinuxRpmPackageBuilder(superPkgBuilder); @@ -81,9 +81,9 @@ final class LinuxFromOptions { return pkgBuilder.create(); } - static LinuxDebPackage createLinuxDebPackage(Options options) { + static LinuxDebPackage createLinuxDebPackage(Options options, LinuxDebSystemEnvironment sysEnv) { - final var superPkgBuilder = createLinuxPackageBuilder(options, LINUX_DEB); + final var superPkgBuilder = createLinuxPackageBuilder(options, sysEnv, LINUX_DEB); final var pkgBuilder = new LinuxDebPackageBuilder(superPkgBuilder); @@ -99,7 +99,7 @@ final class LinuxFromOptions { return pkg; } - private static LinuxPackageBuilder createLinuxPackageBuilder(Options options, StandardPackageType type) { + private static LinuxPackageBuilder createLinuxPackageBuilder(Options options, LinuxSystemEnvironment sysEnv, StandardPackageType type) { final var app = createLinuxApplication(options); @@ -107,6 +107,8 @@ final class LinuxFromOptions { final var pkgBuilder = new LinuxPackageBuilder(superPkgBuilder); + pkgBuilder.arch(sysEnv.packageArch()); + LINUX_PACKAGE_DEPENDENCIES.ifPresentIn(options, pkgBuilder::additionalDependencies); LINUX_APP_CATEGORY.ifPresentIn(options, pkgBuilder::category); LINUX_MENU_GROUP.ifPresentIn(options, pkgBuilder::menuGroupName); diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxLaunchersAsServices.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxLaunchersAsServices.java index b14404d67b1..40ff26bcfac 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxLaunchersAsServices.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxLaunchersAsServices.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, 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,6 +32,7 @@ import java.util.List; import java.util.Map; import jdk.jpackage.internal.model.Launcher; import jdk.jpackage.internal.model.Package; +import jdk.jpackage.internal.util.Enquoter; /** * Helper to install launchers as services using "systemd". diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageArch.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageArch.java index 836d1fb2c37..b1df92ae312 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageArch.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageArch.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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,18 +25,20 @@ package jdk.jpackage.internal; import java.io.IOException; -import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; +import java.util.ArrayList; import jdk.jpackage.internal.model.StandardPackageType; +import jdk.jpackage.internal.util.CommandOutputControl; +import jdk.jpackage.internal.util.Result; -final class LinuxPackageArch { +record LinuxPackageArch(String value) { - static String getValue(StandardPackageType pkgType) { + static Result create(StandardPackageType pkgType) { switch (pkgType) { case LINUX_RPM -> { - return RpmPackageArch.VALUE; + return rpm().map(LinuxPackageArch::new); } case LINUX_DEB -> { - return DebPackageArch.VALUE; + return deb().map(LinuxPackageArch::new); } default -> { throw new IllegalArgumentException(); @@ -44,62 +46,51 @@ final class LinuxPackageArch { } } - private static class DebPackageArch { - - static final String VALUE = toSupplier(DebPackageArch::getValue).get(); - - private static String getValue() throws IOException { - return Executor.of("dpkg", "--print-architecture").saveOutput(true) - .executeExpectSuccess().getOutput().get(0); - } + private static Result deb() { + var exec = Executor.of("dpkg", "--print-architecture").saveOutput(true); + return Result.of(exec::executeExpectSuccess, IOException.class) + .flatMap(LinuxPackageArch::getStdoutFirstLine); } - private static class RpmPackageArch { - - /* - * Various ways to get rpm arch. Needed to address JDK-8233143. rpmbuild is mandatory for - * rpm packaging, try it first. rpm is optional and may not be available, use as the last - * resort. - */ - private static enum RpmArchReader { - Rpmbuild("rpmbuild", "--eval=%{_target_cpu}"), - Rpm("rpm", "--eval=%{_target_cpu}"); - - RpmArchReader(String... cmdline) { - this.cmdline = cmdline; + private static Result rpm() { + var errors = new ArrayList(); + for (var tool : RpmArchReader.values()) { + var result = tool.getRpmArch(); + if (result.hasValue()) { + return result; + } else { + errors.addAll(result.errors()); } - - String getRpmArch() throws IOException { - Executor exec = Executor.of(cmdline).saveOutput(true); - switch (this) { - case Rpm -> { - exec.executeExpectSuccess(); - } - case Rpmbuild -> { - if (exec.execute() != 0) { - return null; - } - } - default -> { - throw new UnsupportedOperationException(); - } - } - return exec.getOutput().get(0); - } - - private final String[] cmdline; } - static final String VALUE = toSupplier(RpmPackageArch::getValue).get(); + return Result.ofErrors(errors); + } - private static String getValue() throws IOException { - for (var rpmArchReader : RpmArchReader.values()) { - var rpmArchStr = rpmArchReader.getRpmArch(); - if (rpmArchStr != null) { - return rpmArchStr; - } - } - throw new RuntimeException("error.rpm-arch-not-detected"); + /* + * Various ways to get rpm arch. Needed to address JDK-8233143. rpmbuild is mandatory for + * rpm packaging, try it first. rpm is optional and may not be available, use as the last + * resort. + */ + private enum RpmArchReader { + RPMBUILD("rpmbuild", "--eval=%{_target_cpu}"), + RPM("rpm", "--eval=%{_target_cpu}"); + + RpmArchReader(String... cmdline) { + this.cmdline = cmdline; } + + Result getRpmArch() { + var exec = Executor.of(cmdline).saveOutput(true); + return Result.of(exec::executeExpectSuccess, IOException.class) + .flatMap(LinuxPackageArch::getStdoutFirstLine); + } + + private final String[] cmdline; + } + + private static Result getStdoutFirstLine(CommandOutputControl.Result result) { + return Result.of(() -> { + return result.stdout().stream().findFirst().orElseThrow(result::unexpected); + }, IOException.class); } } diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageBuilder.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageBuilder.java index bc7c301ace2..cd4d674432e 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageBuilder.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -83,7 +83,7 @@ final class LinuxPackageBuilder { category(), Optional.ofNullable(additionalDependencies), release(), - pkg.asStandardPackageType().map(LinuxPackageArch::getValue).orElseThrow())); + arch.value())); } LinuxPackageBuilder literalName(String v) { @@ -119,6 +119,11 @@ final class LinuxPackageBuilder { return Optional.ofNullable(release); } + LinuxPackageBuilder arch(LinuxPackageArch v) { + arch = v; + return this; + } + private static LinuxApplicationLayout usrTreePackageLayout(Path prefix, String packageName) { final var lib = prefix.resolve(Path.of("lib", packageName)); return LinuxApplicationLayout.create( @@ -184,6 +189,7 @@ final class LinuxPackageBuilder { private String category; private String additionalDependencies; private String release; + private LinuxPackageArch arch; private final PackageBuilder pkgBuilder; diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxRpmSystemEnvironment.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxRpmSystemEnvironment.java index 58c10668227..e56551be325 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxRpmSystemEnvironment.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxRpmSystemEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -28,7 +28,7 @@ import static jdk.jpackage.internal.LinuxSystemEnvironment.mixin; import jdk.jpackage.internal.util.Result; -public interface LinuxRpmSystemEnvironment extends LinuxSystemEnvironment, LinuxRpmSystemEnvironmentMixin { +interface LinuxRpmSystemEnvironment extends LinuxSystemEnvironment, LinuxRpmSystemEnvironmentMixin { static Result create(Result base) { return mixin(LinuxRpmSystemEnvironment.class, base, LinuxRpmSystemEnvironmentMixin::create); diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxRpmSystemEnvironmentMixin.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxRpmSystemEnvironmentMixin.java index b741495f5ed..4cbd3ce4a9c 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxRpmSystemEnvironmentMixin.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxRpmSystemEnvironmentMixin.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ import java.util.stream.Stream; import jdk.jpackage.internal.model.DottedVersion; import jdk.jpackage.internal.util.Result; -public interface LinuxRpmSystemEnvironmentMixin { +interface LinuxRpmSystemEnvironmentMixin { Path rpm(); Path rpmbuild(); diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxSystemEnvironment.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxSystemEnvironment.java index 1a70cc938b8..e347c58ae21 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxSystemEnvironment.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxSystemEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ package jdk.jpackage.internal; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.Optional; import java.util.function.Supplier; import jdk.jpackage.internal.model.PackageType; @@ -35,9 +34,10 @@ import jdk.jpackage.internal.model.StandardPackageType; import jdk.jpackage.internal.util.CompositeProxy; import jdk.jpackage.internal.util.Result; -public interface LinuxSystemEnvironment extends SystemEnvironment { +interface LinuxSystemEnvironment extends SystemEnvironment { boolean soLookupAvailable(); PackageType nativePackageType(); + LinuxPackageArch packageArch(); static Result create() { return detectNativePackageType().map(LinuxSystemEnvironment::create).orElseGet(() -> { @@ -45,7 +45,7 @@ public interface LinuxSystemEnvironment extends SystemEnvironment { }); } - static Optional detectNativePackageType() { + static Optional detectNativePackageType() { if (Internal.isDebian()) { return Optional.of(StandardPackageType.LINUX_DEB); } else if (Internal.isRpm()) { @@ -55,13 +55,14 @@ public interface LinuxSystemEnvironment extends SystemEnvironment { } } - static Result create(PackageType nativePackageType) { - return Result.ofValue(new Stub(LibProvidersLookup.supported(), - Objects.requireNonNull(nativePackageType))); + static Result create(StandardPackageType nativePackageType) { + return LinuxPackageArch.create(nativePackageType).map(arch -> { + return new Stub(LibProvidersLookup.supported(), nativePackageType, arch); + }); } static U createWithMixin(Class type, LinuxSystemEnvironment base, T mixin) { - return CompositeProxy.create(type, base, mixin); + return CompositeProxy.build().invokeTunnel(CompositeProxyTunnel.INSTANCE).create(type, base, mixin); } static Result mixin(Class type, @@ -79,7 +80,7 @@ public interface LinuxSystemEnvironment extends SystemEnvironment { } } - record Stub(boolean soLookupAvailable, PackageType nativePackageType) implements LinuxSystemEnvironment { + record Stub(boolean soLookupAvailable, PackageType nativePackageType, LinuxPackageArch packageArch) implements LinuxSystemEnvironment { } static final class Internal { diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/AppImageInfoPListFile.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/AppImageInfoPListFile.java index 4787d1297bb..602e147a970 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/AppImageInfoPListFile.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/AppImageInfoPListFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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,6 @@ */ package jdk.jpackage.internal; -import static jdk.jpackage.internal.util.XmlUtils.initDocumentBuilder; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -50,7 +48,7 @@ record AppImageInfoPListFile(String bundleIdentifier, String bundleName, String static AppImageInfoPListFile loadFromInfoPList(Path infoPListFile) throws IOException, InvalidPlistFileException, SAXException { - final var plistReader = new PListReader(initDocumentBuilder().parse(Files.newInputStream(infoPListFile))); + final var plistReader = new PListReader(Files.readAllBytes(infoPListFile)); try { return new AppImageInfoPListFile( diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/AppImageSigner.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/AppImageSigner.java index 71f87dd8705..81e04ad7ed1 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/AppImageSigner.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/AppImageSigner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -48,6 +48,7 @@ import jdk.jpackage.internal.model.Launcher; import jdk.jpackage.internal.model.MacApplication; import jdk.jpackage.internal.model.RuntimeLayout; import jdk.jpackage.internal.util.PathUtils; +import jdk.jpackage.internal.util.Result; import jdk.jpackage.internal.util.function.ExceptionBox; @@ -188,11 +189,9 @@ final class AppImageSigner { } private static boolean isXcodeDevToolsInstalled() { - try { - return Executor.of("/usr/bin/xcrun", "--help").setQuiet(true).execute() == 0; - } catch (IOException ex) { - return false; - } + return Result.of( + Executor.of("/usr/bin/xcrun", "--help").setQuiet(true)::executeExpectSuccess, + IOException.class).hasValue(); } private static void unsign(Path path) throws IOException { diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/Codesign.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/Codesign.java index 920b75df398..a7cd17b06b9 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/Codesign.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/Codesign.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -34,7 +34,6 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; -import java.util.stream.Stream; public final class Codesign { @@ -94,14 +93,12 @@ public final class Codesign { public void applyTo(Path path) throws IOException, CodesignException { - var exec = Executor.of(Stream.concat( - cmdline.stream(), - Stream.of(path.toString())).toArray(String[]::new) - ).saveOutput(true); + var exec = Executor.of(cmdline).args(path.toString()).saveOutput(true); configureExecutor.ifPresent(configure -> configure.accept(exec)); - if (exec.execute() != 0) { - throw new CodesignException(exec.getOutput().toArray(String[]::new)); + var result = exec.execute(); + if (result.getExitCode() != 0) { + throw new CodesignException(result.getOutput().toArray(String[]::new)); } } diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacBundlingEnvironment.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacBundlingEnvironment.java index 3cecb2cd243..0531559e052 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacBundlingEnvironment.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacBundlingEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -36,7 +36,6 @@ import java.util.Optional; import jdk.jpackage.internal.cli.Options; import jdk.jpackage.internal.model.MacPackage; import jdk.jpackage.internal.model.Package; -import jdk.jpackage.internal.util.Result; public class MacBundlingEnvironment extends DefaultBundlingEnvironment { @@ -45,7 +44,7 @@ public class MacBundlingEnvironment extends DefaultBundlingEnvironment { .defaultOperation(CREATE_MAC_DMG) .bundler(SIGN_MAC_APP_IMAGE, MacBundlingEnvironment::signAppImage) .bundler(CREATE_MAC_APP_IMAGE, MacBundlingEnvironment::createAppImage) - .bundler(CREATE_MAC_DMG, LazyLoad::dmgSysEnv, MacBundlingEnvironment::createDmdPackage) + .bundler(CREATE_MAC_DMG, MacDmgSystemEnvironment::create, MacBundlingEnvironment::createDmdPackage) .bundler(CREATE_MAC_PKG, MacBundlingEnvironment::createPkgPackage)); } @@ -98,13 +97,4 @@ public class MacBundlingEnvironment extends DefaultBundlingEnvironment { .predefinedAppImageLayout(APPLICATION_LAYOUT) .predefinedRuntimeImageLayout(MacPackage::guessRuntimeLayout); } - - private static final class LazyLoad { - - static Result dmgSysEnv() { - return DMG_SYS_ENV; - } - - private static final Result DMG_SYS_ENV = MacDmgSystemEnvironment.create(); - } } diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacCertificateUtils.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacCertificateUtils.java index fe593e347fc..24a236ae15d 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacCertificateUtils.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacCertificateUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -53,7 +53,7 @@ public final class MacCertificateUtils { keychain.map(Keychain::asCliArg).ifPresent(args::add); return toSupplier(() -> { - final var output = Executor.of(args.toArray(String[]::new)) + final var output = Executor.of(args) .setQuiet(true).saveOutput(true).executeExpectSuccess() .getOutput(); diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgPackager.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgPackager.java index 4ccc459109f..20a687487ef 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgPackager.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgPackager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -33,11 +33,15 @@ import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.text.MessageFormat; +import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +import java.util.function.Function; import jdk.jpackage.internal.PackagingPipeline.PackageTaskID; import jdk.jpackage.internal.PackagingPipeline.TaskID; import jdk.jpackage.internal.model.MacDmgPackage; @@ -105,6 +109,10 @@ record MacDmgPackager(BuildEnv env, MacDmgPackage pkg, Path outputDir, return env.configDir().resolve(pkg.app().name() + "-license.plist"); } + private Path finalDmg() { + return outputDir.resolve(pkg.packageFileNameWithSuffix()); + } + Path protoDmg() { return dmgWorkdir().resolve("proto.dmg"); } @@ -128,6 +136,10 @@ record MacDmgPackager(BuildEnv env, MacDmgPackage pkg, Path outputDir, } } + private Executor hdiutil(String... args) { + return Executor.of(sysEnv.hdiutil().toString()).args(args).storeOutputInFiles(); + } + private void prepareDMGSetupScript() throws IOException { Path dmgSetup = volumeScript(); Log.verbose(MessageFormat.format( @@ -211,13 +223,17 @@ record MacDmgPackager(BuildEnv env, MacDmgPackage pkg, Path outputDir, } } + private String hdiUtilVerbosityFlag() { + return env.verbose() ? "-verbose" : "-quiet"; + } + private void buildDMG() throws IOException { boolean copyAppImage = false; - Path protoDMG = protoDmg(); - Path finalDMG = outputDir.resolve(pkg.packageFileNameWithSuffix()); + final Path protoDMG = protoDmg(); + final Path finalDMG = finalDmg(); - Path srcFolder = env.appImageDir(); + final Path srcFolder = env.appImageDir(); Log.verbose(MessageFormat.format(I18N.getString( "message.creating-dmg-file"), finalDMG.toAbsolutePath())); @@ -233,21 +249,17 @@ record MacDmgPackager(BuildEnv env, MacDmgPackage pkg, Path outputDir, Files.createDirectories(protoDMG.getParent()); Files.createDirectories(finalDMG.getParent()); - String hdiUtilVerbosityFlag = env.verbose() ? - "-verbose" : "-quiet"; + final String hdiUtilVerbosityFlag = hdiUtilVerbosityFlag(); // create temp image - ProcessBuilder pb = new ProcessBuilder( - sysEnv.hdiutil().toString(), - "create", - hdiUtilVerbosityFlag, - "-srcfolder", normalizedAbsolutePathString(srcFolder), - "-volname", volumeName(), - "-ov", normalizedAbsolutePathString(protoDMG), - "-fs", "HFS+", - "-format", "UDRW"); try { - IOUtils.exec(pb, false, null, true, Executor.INFINITE_TIMEOUT); + hdiutil("create", + hdiUtilVerbosityFlag, + "-srcfolder", normalizedAbsolutePathString(srcFolder), + "-volname", volumeName(), + "-ov", normalizedAbsolutePathString(protoDMG), + "-fs", "HFS+", + "-format", "UDRW").executeExpectSuccess(); } catch (IOException ex) { Log.verbose(ex); // Log exception @@ -260,31 +272,26 @@ record MacDmgPackager(BuildEnv env, MacDmgPackage pkg, Path outputDir, // not be bigger, but it will able to hold additional 50 megabytes of data. // We need extra room for icons and background image. When we providing // actual files to hdiutil, it will create DMG with ~50 megabytes extra room. - pb = new ProcessBuilder( - sysEnv.hdiutil().toString(), - "create", - hdiUtilVerbosityFlag, - "-size", String.valueOf(size), - "-volname", volumeName(), - "-ov", normalizedAbsolutePathString(protoDMG), - "-fs", "HFS+"); - new RetryExecutor() - .setMaxAttemptsCount(10) - .setAttemptTimeoutMillis(3000) - .setWriteOutputToFile(true) - .execute(pb); + hdiutil( + "create", + hdiUtilVerbosityFlag, + "-size", String.valueOf(size), + "-volname", volumeName(), + "-ov", normalizedAbsolutePathString(protoDMG), + "-fs", "HFS+" + ).retry() + .setMaxAttemptsCount(10) + .setAttemptTimeout(3, TimeUnit.SECONDS) + .execute(); } + final Path mountedVolume = volumePath(); + // mount temp image - pb = new ProcessBuilder( - sysEnv.hdiutil().toString(), - "attach", + hdiutil("attach", normalizedAbsolutePathString(protoDMG), hdiUtilVerbosityFlag, - "-mountroot", protoDMG.getParent().toString()); - IOUtils.exec(pb, false, null, true, Executor.INFINITE_TIMEOUT); - - final Path mountedVolume = volumePath(); + "-mountroot", mountedVolume.getParent().toString()).executeExpectSuccess(); // Copy app image, since we did not create DMG with it, but instead we created // empty one. @@ -302,9 +309,13 @@ record MacDmgPackager(BuildEnv env, MacDmgPackage pkg, Path outputDir, // to install-dir in DMG as critical error, since it can fail in // headless environment. try { - pb = new ProcessBuilder(sysEnv.osascript().toString(), - normalizedAbsolutePathString(volumeScript())); - IOUtils.exec(pb, 180); // Wait 3 minutes. See JDK-8248248. + Executor.of( + sysEnv.osascript().toString(), + normalizedAbsolutePathString(volumeScript()) + ) + // Wait 3 minutes. See JDK-8248248. + .timeout(3, TimeUnit.MINUTES) + .executeExpectSuccess(); } catch (IOException ex) { Log.verbose(ex); } @@ -325,18 +336,18 @@ record MacDmgPackager(BuildEnv env, MacDmgPackage pkg, Path outputDir, // but it seems Finder excepts these bytes to be // "icnC" for the volume icon // (might not work on Mac 10.13 with old XCode) - pb = new ProcessBuilder( + Executor.of( sysEnv.setFileUtility().orElseThrow().toString(), "-c", "icnC", - normalizedAbsolutePathString(volumeIconFile)); - IOUtils.exec(pb); + normalizedAbsolutePathString(volumeIconFile) + ).executeExpectSuccess(); volumeIconFile.toFile().setReadOnly(); - pb = new ProcessBuilder( + Executor.of( sysEnv.setFileUtility().orElseThrow().toString(), "-a", "C", - normalizedAbsolutePathString(mountedVolume)); - IOUtils.exec(pb); + normalizedAbsolutePathString(mountedVolume) + ).executeExpectSuccess(); } catch (IOException ex) { Log.error(ex.getMessage()); Log.verbose("Cannot enable custom icon using SetFile utility"); @@ -347,85 +358,23 @@ record MacDmgPackager(BuildEnv env, MacDmgPackage pkg, Path outputDir, } finally { // Detach the temporary image - pb = new ProcessBuilder( - sysEnv.hdiutil().toString(), - "detach", - hdiUtilVerbosityFlag, - normalizedAbsolutePathString(mountedVolume)); - // "hdiutil detach" might not work right away due to resource busy error, so - // repeat detach several times. - RetryExecutor retryExecutor = new RetryExecutor(); - // Image can get detach even if we got resource busy error, so stop - // trying to detach it if it is no longer attached. - retryExecutor.setExecutorInitializer(exec -> { - if (!Files.exists(mountedVolume)) { - retryExecutor.abort(); - } - }); - try { - // 10 times with 6 second delays. - retryExecutor.setMaxAttemptsCount(10).setAttemptTimeoutMillis(6000) - .execute(pb); - } catch (IOException ex) { - if (!retryExecutor.isAborted()) { - // Now force to detach if it still attached - if (Files.exists(mountedVolume)) { - pb = new ProcessBuilder( - sysEnv.hdiutil().toString(), - "detach", - "-force", - hdiUtilVerbosityFlag, - normalizedAbsolutePathString(mountedVolume)); - IOUtils.exec(pb, false, null, true, Executor.INFINITE_TIMEOUT); - } - } - } + detachVolume(); } // Compress it to a new image - pb = new ProcessBuilder( - sysEnv.hdiutil().toString(), - "convert", - normalizedAbsolutePathString(protoDMG), - hdiUtilVerbosityFlag, - "-format", "UDZO", - "-o", normalizedAbsolutePathString(finalDMG)); - try { - new RetryExecutor() - .setMaxAttemptsCount(10) - .setAttemptTimeoutMillis(3000) - .execute(pb); - } catch (Exception ex) { - // Convert might failed if something holds file. Try to convert copy. - Path protoCopyDMG = protoCopyDmg(); - Files.copy(protoDMG, protoCopyDMG); - try { - pb = new ProcessBuilder( - sysEnv.hdiutil().toString(), - "convert", - normalizedAbsolutePathString(protoCopyDMG), - hdiUtilVerbosityFlag, - "-format", "UDZO", - "-o", normalizedAbsolutePathString(finalDMG)); - IOUtils.exec(pb, false, null, true, Executor.INFINITE_TIMEOUT); - } finally { - Files.deleteIfExists(protoCopyDMG); - } - } + convertProtoDmg(); //add license if needed if (pkg.licenseFile().isPresent()) { - pb = new ProcessBuilder( - sysEnv.hdiutil().toString(), + hdiutil( "udifrez", normalizedAbsolutePathString(finalDMG), "-xml", normalizedAbsolutePathString(licenseFile()) - ); - new RetryExecutor() - .setMaxAttemptsCount(10) - .setAttemptTimeoutMillis(3000) - .execute(pb); + ).retry() + .setMaxAttemptsCount(10) + .setAttemptTimeout(3, TimeUnit.SECONDS) + .execute(); } try { @@ -441,6 +390,69 @@ record MacDmgPackager(BuildEnv env, MacDmgPackage pkg, Path outputDir, } + private void detachVolume() throws IOException { + var mountedVolume = volumePath(); + + // "hdiutil detach" might not work right away due to resource busy error, so + // repeat detach several times. + Globals.instance().objectFactory().retryExecutor(IOException.class).setExecutable(context -> { + + List cmdline = new ArrayList<>(); + cmdline.add("detach"); + + if (context.isLastAttempt()) { + // The last attempt, force detach. + cmdline.add("-force"); + } + + cmdline.addAll(List.of( + hdiUtilVerbosityFlag(), + normalizedAbsolutePathString(mountedVolume) + )); + + // The image can get detached even if we get a resource busy error, + // so execute the detach command without checking the exit code. + var result = hdiutil(cmdline.toArray(String[]::new)).execute(); + + if (result.getExitCode() == 0 || !Files.exists(mountedVolume)) { + // Detached successfully! + return null; + } else { + throw result.unexpected(); + } + }).setMaxAttemptsCount(10).setAttemptTimeout(6, TimeUnit.SECONDS).execute(); + } + + private void convertProtoDmg() throws IOException { + + Function convert = srcDmg -> { + return hdiutil( + "convert", + normalizedAbsolutePathString(srcDmg), + hdiUtilVerbosityFlag(), + "-format", "UDZO", + "-o", normalizedAbsolutePathString(finalDmg())); + }; + + // Convert it to a new image. + try { + convert.apply(protoDmg()).retry() + .setMaxAttemptsCount(10) + .setAttemptTimeout(3, TimeUnit.SECONDS) + .execute(); + } catch (IOException ex) { + Log.verbose(ex); + // Something holds the file, try to convert a copy. + Path copyDmg = protoCopyDmg(); + Files.copy(protoDmg(), copyDmg); + try { + convert.apply(copyDmg).executeExpectSuccess(); + } finally { + Files.deleteIfExists(copyDmg); + } + } + } + // Background image name in resources private static final String DEFAULT_BACKGROUND_IMAGE = "background_dmg.tiff"; private static final String DEFAULT_DMG_SETUP_SCRIPT = "DMGsetup.scpt"; diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgSystemEnvironment.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgSystemEnvironment.java index 54eb0c6f4fe..12d105b99b5 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgSystemEnvironment.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgSystemEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ package jdk.jpackage.internal; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; import java.util.stream.Stream; import jdk.jpackage.internal.util.Result; @@ -54,41 +55,31 @@ record MacDmgSystemEnvironment(Path hdiutil, Path osascript, Optional setF // Location of SetFile utility may be different depending on MacOS version // We look for several known places and if none of them work will // try to find it - private static Optional findSetFileUtility() { - String typicalPaths[] = {"/Developer/Tools/SetFile", - "/usr/bin/SetFile", "/Developer/usr/bin/SetFile"}; + static Optional findSetFileUtility() { + return SETFILE_KNOWN_PATHS.stream().filter(setFilePath -> { + // Validate SetFile, if Xcode is not installed it will run, but exit with error code + return Result.of( + Executor.of(setFilePath.toString(), "-h").setQuiet(true)::executeExpectSuccess, + IOException.class).hasValue(); + }).findFirst().or(() -> { + // generic find attempt + final var executor = Executor.of("/usr/bin/xcrun", "-find", "SetFile").setQuiet(true).saveFirstLineOfOutput(); - final var setFilePath = Stream.of(typicalPaths).map(Path::of).filter(Files::isExecutable).findFirst(); - if (setFilePath.isPresent()) { - // Validate SetFile, if Xcode is not installed it will run, but exit with error - // code - try { - if (Executor.of(setFilePath.orElseThrow().toString(), "-h").setQuiet(true).execute() == 0) { - return setFilePath; - } - } catch (Exception ignored) { - // No need for generic find attempt. We found it, but it does not work. - // Probably due to missing xcode. - return Optional.empty(); - } - } - - // generic find attempt - try { - final var executor = Executor.of("/usr/bin/xcrun", "-find", "SetFile"); - final var code = executor.setQuiet(true).saveOutput(true).execute(); - if (code == 0 && !executor.getOutput().isEmpty()) { - final var firstLine = executor.getOutput().getFirst(); - Path f = Path.of(firstLine); - if (new ToolValidator(f).checkExistsOnly().validate() == null) { - return Optional.of(f.toAbsolutePath()); - } - } - } catch (IOException ignored) {} - - return Optional.empty(); + return Result.of(executor::executeExpectSuccess, IOException.class).flatMap(execResult -> { + return Result.of(() -> { + return execResult.stdout().stream().findFirst().map(Path::of).orElseThrow(execResult::unexpected); + }, Exception.class); + }).value().filter(v -> { + return new ToolValidator(v).checkExistsOnly().validate() == null; + }).map(Path::toAbsolutePath); + }); } + static final List SETFILE_KNOWN_PATHS = Stream.of( + "/Developer/Tools/SetFile", + "/usr/bin/SetFile", + "/Developer/usr/bin/SetFile").map(Path::of).collect(Collectors.toUnmodifiableList()); + private static final Path HDIUTIL = Path.of("/usr/bin/hdiutil"); private static final Path OSASCRIPT = Path.of("/usr/bin/osascript"); } diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacPkgPackager.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacPkgPackager.java index 127b3232661..126248e2330 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacPkgPackager.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacPkgPackager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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,6 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.net.URISyntaxException; -import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.text.MessageFormat; @@ -57,6 +56,7 @@ import jdk.jpackage.internal.PackagingPipeline.PackageTaskID; import jdk.jpackage.internal.PackagingPipeline.TaskID; import jdk.jpackage.internal.model.MacPkgPackage; import jdk.jpackage.internal.resources.ResourceLocator; +import jdk.jpackage.internal.util.Enquoter; import jdk.jpackage.internal.util.XmlUtils; import org.xml.sax.SAXException; @@ -108,7 +108,7 @@ record MacPkgPackager(BuildEnv env, MacPkgPackage pkg, Optional servic cmdline.addAll(allPkgbuildArgs()); try { Files.createDirectories(path.getParent()); - IOUtils.exec(new ProcessBuilder(cmdline), false, null, true, Executor.INFINITE_TIMEOUT); + Executor.of(cmdline).executeExpectSuccess(); } catch (IOException ex) { throw new UncheckedIOException(ex); } @@ -487,15 +487,13 @@ record MacPkgPackager(BuildEnv env, MacPkgPackage pkg, Optional servic Files.createDirectories(cpl.getParent()); - final var pb = new ProcessBuilder("/usr/bin/pkgbuild", + Executor.of("/usr/bin/pkgbuild", "--root", normalizedAbsolutePathString(env.appImageDir()), "--install-location", normalizedAbsolutePathString(installLocation()), "--analyze", - normalizedAbsolutePathString(cpl)); - - IOUtils.exec(pb, false, null, true, Executor.INFINITE_TIMEOUT); + normalizedAbsolutePathString(cpl)).executeExpectSuccess(); patchCPLFile(cpl); } @@ -544,8 +542,7 @@ record MacPkgPackager(BuildEnv env, MacPkgPackage pkg, Optional servic } commandLine.add(normalizedAbsolutePathString(finalPkg)); - final var pb = new ProcessBuilder(commandLine); - IOUtils.exec(pb, false, null, true, Executor.INFINITE_TIMEOUT); + Executor.of(commandLine).executeExpectSuccess(); } private static Optional createServices(BuildEnv env, MacPkgPackage pkg) { diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/SigningIdentityBuilder.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/SigningIdentityBuilder.java index 87193783041..0f753c07569 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/SigningIdentityBuilder.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/SigningIdentityBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -40,6 +40,7 @@ import javax.naming.ldap.Rdn; import javax.security.auth.x500.X500Principal; import jdk.jpackage.internal.MacCertificateUtils.CertificateHash; import jdk.jpackage.internal.model.ConfigException; +import jdk.jpackage.internal.model.JPackageException; import jdk.jpackage.internal.model.SigningIdentity; final class SigningIdentityBuilder { @@ -147,11 +148,9 @@ final class SigningIdentityBuilder { Objects.requireNonNull(keychain); switch (certs.size()) { case 0 -> { - var errMsg = I18N.format("error.cert.not.found", certificateSelector.signingIdentities().getFirst(), - keychain.map(Keychain::name).orElse("")); - Log.error(I18N.format("message.error-header", errMsg)); - throw I18N.buildConfigException("error.explicit-sign-no-cert") - .advice("error.explicit-sign-no-cert.advice").create(); + throw new JPackageException(I18N.format("error.cert.not.found", + certificateSelector.signingIdentities().getFirst(), + keychain.map(Keychain::name).orElse(""))); } case 1 -> { return certs.getFirst(); diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/TempKeychain.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/TempKeychain.java index b38faecd96f..2f616aafba1 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/TempKeychain.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/TempKeychain.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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,15 +27,17 @@ package jdk.jpackage.internal; import java.io.Closeable; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.function.Consumer; import jdk.internal.util.OSVersion; -import jdk.jpackage.internal.util.function.ThrowingConsumer; final class TempKeychain implements Closeable { - static void withKeychains(ThrowingConsumer, ? extends Exception> keychainConsumer, List keychains) throws Exception { + static void withKeychains(Consumer> keychainConsumer, List keychains) { + keychains.forEach(Objects::requireNonNull); if (keychains.isEmpty() || OSVersion.current().compareTo(new OSVersion(10, 12)) < 0) { keychainConsumer.accept(keychains); @@ -43,11 +45,14 @@ final class TempKeychain implements Closeable { // we need this for OS X 10.12+ try (var tempKeychain = new TempKeychain(keychains)) { keychainConsumer.accept(tempKeychain.keychains); + } catch (IOException ex) { + throw new UncheckedIOException(ex); } } } - static void withKeychain(ThrowingConsumer keychainConsumer, Keychain keychain) throws Exception { + static void withKeychain(Consumer keychainConsumer, Keychain keychain) { + Objects.requireNonNull(keychainConsumer); withKeychains(keychains -> { keychainConsumer.accept(keychains.getFirst()); @@ -78,7 +83,7 @@ final class TempKeychain implements Closeable { args.addAll(missingKeychains.stream().map(Keychain::asCliArg).toList()); - Executor.of(args.toArray(String[]::new)).executeExpectSuccess(); + Executor.of(args).executeExpectSuccess(); } } @@ -89,7 +94,7 @@ final class TempKeychain implements Closeable { @Override public void close() throws IOException { if (!restoreKeychainsCmd.isEmpty()) { - Executor.of(restoreKeychainsCmd.toArray(String[]::new)).executeExpectSuccess(); + Executor.of(restoreKeychainsCmd).executeExpectSuccess(); } } diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/resources/MacResources.properties b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/resources/MacResources.properties index d01297aa814..240e82dcc9b 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/resources/MacResources.properties +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/resources/MacResources.properties @@ -1,5 +1,5 @@ # -# Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2017, 2026, 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,6 @@ # # error.invalid-cfbundle-version.advice=Set a compatible 'app-version' value. Valid versions are one to three integers separated by dots. -error.explicit-sign-no-cert=Signature explicitly requested but no signing certificate found -error.explicit-sign-no-cert.advice=Specify a valid mac-signing-key-user-name and mac-signing-keychain error.certificate.expired=Certificate expired {0} error.cert.not.found=No certificate found matching [{0}] using keychain [{1}] error.multiple.certs.found=Multiple certificates matching name [{0}] found in keychain [{1}] diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AppImageFile.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AppImageFile.java index 5f473b554be..75ead9d08ad 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AppImageFile.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AppImageFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ -28,11 +28,12 @@ import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toUnmodifiableMap; import static java.util.stream.Collectors.toUnmodifiableSet; import static jdk.jpackage.internal.cli.StandardAppImageFileOption.APP_VERSION; -import static jdk.jpackage.internal.cli.StandardAppImageFileOption.LAUNCHER_AS_SERVICE; import static jdk.jpackage.internal.cli.StandardAppImageFileOption.DESCRIPTION; +import static jdk.jpackage.internal.cli.StandardAppImageFileOption.LAUNCHER_AS_SERVICE; import static jdk.jpackage.internal.cli.StandardAppImageFileOption.LAUNCHER_NAME; import static jdk.jpackage.internal.util.function.ThrowingFunction.toFunction; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.NoSuchFileException; @@ -162,7 +163,23 @@ final class AppImageFile { final var relativeAppImageFilePath = appImageDir.relativize(appImageFilePath); try { - final Document doc = XmlUtils.initDocumentBuilder().parse(Files.newInputStream(appImageFilePath)); + // + // Use javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream). + // Don't use javax.xml.parsers.DocumentBuilder#parse(java.io.File) as this will introduce + // dependency on how the XML parser reports filesystem I/O errors. + // E.g.: the default JDK XML parser throws java.io.FileNotFoundException if the supplied + // directory is not found and throws org.xml.sax.SAXParseException if the supplied file is a directory. + // Another DOM XML parser (a different version of Xerces?) may behave differently. + // + // The use of javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream) eliminates + // differences in how XML parsers handle file system I/O errors. + // Filesystem I/O is delegated to java.nio.file.Files#readAllBytes(java.nio.file.Path), + // XML parser deals with the byte stream in memory and the error handling code + // doesn't depend on how XML parser reports filesystem I/O errors because + // it reads data from memory, not from the filesystem. + // + final Document doc = XmlUtils.initDocumentBuilder().parse( + new ByteArrayInputStream(Files.readAllBytes(appImageFilePath))); final XPath xPath = XPathFactory.newInstance().newXPath(); diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/DefaultBundlingEnvironment.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/DefaultBundlingEnvironment.java index 05e080f240a..e4473b1e5ce 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/DefaultBundlingEnvironment.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/DefaultBundlingEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -65,10 +65,10 @@ class DefaultBundlingEnvironment implements CliBundlingEnvironment { Map>>> bundlers) { this.bundlers = bundlers.entrySet().stream().collect(toMap(Map.Entry::getKey, e -> { - return new CachingSupplier<>(e.getValue()); + return runOnce(e.getValue()); })); - this.defaultOperationSupplier = Objects.requireNonNull(defaultOperationSupplier).map(CachingSupplier::new); + this.defaultOperationSupplier = Objects.requireNonNull(defaultOperationSupplier).map(DefaultBundlingEnvironment::runOnce); } @@ -98,6 +98,11 @@ class DefaultBundlingEnvironment implements CliBundlingEnvironment { return bundler(op, () -> Result.ofValue(bundler)); } + Builder mutate(Consumer mutator) { + mutator.accept(this); + return this; + } + private Supplier> defaultOperationSupplier; private final Map>>> bundlers = new HashMap<>(); } @@ -107,6 +112,10 @@ class DefaultBundlingEnvironment implements CliBundlingEnvironment { return new Builder(); } + static Supplier runOnce(Supplier supplier) { + return new CachingSupplier<>(supplier); + } + static Supplier>> createBundlerSupplier( Supplier> sysEnvResultSupplier, BiConsumer bundler) { Objects.requireNonNull(sysEnvResultSupplier); @@ -279,5 +288,5 @@ class DefaultBundlingEnvironment implements CliBundlingEnvironment { private final Map>>> bundlers; - private final Optional>> defaultOperationSupplier; + private final Optional>> defaultOperationSupplier; } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Executor.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Executor.java index dd1cc4a24b4..ca7a630b6d1 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Executor.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Executor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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,53 +25,153 @@ package jdk.jpackage.internal; import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.file.Files; -import java.nio.file.Path; +import java.io.PrintStream; +import java.io.StringReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.Objects; +import java.util.Optional; import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; -import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import java.util.spi.ToolProvider; import java.util.stream.Stream; +import jdk.jpackage.internal.util.CommandLineFormat; +import jdk.jpackage.internal.util.CommandOutputControl; +import jdk.jpackage.internal.util.CommandOutputControl.ProcessAttributes; +import jdk.jpackage.internal.util.CommandOutputControl.Result; +import jdk.jpackage.internal.util.RetryExecutor; +import jdk.jpackage.internal.util.function.ExceptionBox; -public final class Executor { +final class Executor { - Executor() { + static Executor of(String... cmdline) { + return of(List.of(cmdline)); } - Executor setOutputConsumer(Consumer> v) { - outputConsumer = v; - return this; + static Executor of(List cmdline) { + return of(new ProcessBuilder(cmdline)); + } + + static Executor of(ProcessBuilder pb) { + return Globals.instance().objectFactory().executor().processBuilder(pb); + } + + public Executor() { + commandOutputControl = new CommandOutputControl(); + args = new ArrayList<>(); + } + + private Executor(Executor other) { + commandOutputControl = other.commandOutputControl.copy(); + quietCommand = other.quietCommand; + args = new ArrayList<>(other.args); + processBuilder = other.processBuilder; + toolProvider = other.toolProvider; + timeout = other.timeout; + mapper = other.mapper; } Executor saveOutput(boolean v) { - saveOutput = v; + commandOutputControl.saveOutput(v); return this; } - Executor setWriteOutputToFile(boolean v) { - writeOutputToFile = v; + Executor saveOutput() { + return saveOutput(true); + } + + Executor saveFirstLineOfOutput() { + commandOutputControl.saveFirstLineOfOutput(); return this; } - Executor setTimeout(long v) { + Executor charset(Charset v) { + commandOutputControl.charset(v); + return this; + } + + Executor storeOutputInFiles(boolean v) { + commandOutputControl.storeOutputInFiles(v); + return this; + } + + Executor storeOutputInFiles() { + return storeOutputInFiles(true); + } + + Executor binaryOutput(boolean v) { + commandOutputControl.binaryOutput(v); + return this; + } + + Executor binaryOutput() { + return binaryOutput(true); + } + + Executor discardStdout(boolean v) { + commandOutputControl.discardStdout(v); + return this; + } + + Executor discardStdout() { + return discardStdout(true); + } + + Executor discardStderr(boolean v) { + commandOutputControl.discardStderr(v); + return this; + } + + Executor discardStderr() { + return discardStderr(true); + } + + Executor timeout(long v, TimeUnit unit) { + return timeout(Duration.of(v, unit.toChronoUnit())); + } + + Executor timeout(Duration v) { timeout = v; - if (timeout != INFINITE_TIMEOUT) { - // Redirect output to file if timeout is requested, otherwise we will - // reading until process ends and timeout will never be reached. - setWriteOutputToFile(true); - } return this; } - Executor setProcessBuilder(ProcessBuilder v) { - pb = v; + Executor toolProvider(ToolProvider v) { + toolProvider = Objects.requireNonNull(v); + processBuilder = null; return this; } - Executor setCommandLine(String... cmdline) { - return setProcessBuilder(new ProcessBuilder(cmdline)); + Optional toolProvider() { + return Optional.ofNullable(toolProvider); + } + + Executor processBuilder(ProcessBuilder v) { + processBuilder = Objects.requireNonNull(v); + toolProvider = null; + return this; + } + + Optional processBuilder() { + return Optional.ofNullable(processBuilder); + } + + Executor args(List v) { + args.addAll(v); + return this; + } + + Executor args(String... args) { + return args(List.of(args)); + } + + List args() { + return args; } Executor setQuiet(boolean v) { @@ -79,159 +179,207 @@ public final class Executor { return this; } - List getOutput() { - return output; - } - - Executor executeExpectSuccess() throws IOException { - int ret = execute(); - if (0 != ret) { - throw new IOException( - String.format("Command %s exited with %d code", - createLogMessage(pb, false), ret)); - } + Executor mapper(UnaryOperator v) { + mapper = v; return this; } - int execute() throws IOException { - output = null; + Optional> mapper() { + return Optional.ofNullable(mapper); + } - boolean needProcessOutput = outputConsumer != null || Log.isVerbose() || saveOutput; - Path outputFile = null; - if (needProcessOutput) { - pb.redirectErrorStream(true); - if (writeOutputToFile) { - outputFile = Files.createTempFile("jpackageOutputTempFile", ".tmp"); - pb.redirectOutput(outputFile.toFile()); + Executor copy() { + return new Executor(this); + } + + Result execute() throws IOException { + if (mapper != null) { + var mappedExecutor = Objects.requireNonNull(mapper.apply(this)); + if (mappedExecutor != this) { + return mappedExecutor.execute(); } + } + + var coc = commandOutputControl.copy(); + + final CommandOutputControl.Executable exec; + if (processBuilder != null) { + exec = coc.createExecutable(copyProcessBuilder()); + } else if (toolProvider != null) { + exec = coc.createExecutable(toolProvider, args.toArray(String[]::new)); } else { - // We are not going to read process output, so need to notify - // ProcessBuilder about this. Otherwise some processes might just - // hang up (`ldconfig -p`). - pb.redirectError(ProcessBuilder.Redirect.DISCARD); - pb.redirectOutput(ProcessBuilder.Redirect.DISCARD); + throw new IllegalStateException("No target to execute"); } - if (!quietCommand) { - Log.verbose(String.format("Running %s", createLogMessage(pb, true))); + PrintableOutputBuilder printableOutputBuilder; + if (dumpOutput()) { + printableOutputBuilder = new PrintableOutputBuilder(coc); + } else { + printableOutputBuilder = null; } - Process p = pb.start(); - - int code = 0; - if (writeOutputToFile) { - try { - code = waitForProcess(p); - } catch (InterruptedException ex) { - Log.verbose(ex); - throw new RuntimeException(ex); - } - } - - if (needProcessOutput) { - final List savedOutput; - Supplier> outputStream; - - if (writeOutputToFile) { - output = savedOutput = Files.readAllLines(outputFile); - Files.delete(outputFile); - outputStream = () -> { - if (savedOutput != null) { - return savedOutput.stream(); - } - return null; - }; - if (outputConsumer != null) { - outputConsumer.accept(outputStream.get()); - } - } else { - try (var br = new BufferedReader(new InputStreamReader( - p.getInputStream()))) { - - if ((outputConsumer != null || Log.isVerbose()) - || saveOutput) { - savedOutput = br.lines().toList(); - } else { - savedOutput = null; - } - output = savedOutput; - - outputStream = () -> { - if (savedOutput != null) { - return savedOutput.stream(); - } - return br.lines(); - }; - if (outputConsumer != null) { - outputConsumer.accept(outputStream.get()); - } - - if (savedOutput == null) { - // For some processes on Linux if the output stream - // of the process is opened but not consumed, the process - // would exit with code 141. - // It turned out that reading just a single line of process - // output fixes the problem, but let's process - // all of the output, just in case. - br.lines().forEach(x -> {}); - } - } - } + if (dumpOutput()) { + Log.verbose(String.format("Running %s", CommandLineFormat.DEFAULT.apply(List.of(commandLine().getFirst())))); } + Result result; try { - if (!writeOutputToFile) { - code = p.waitFor(); - } - if (!quietCommand) { - Log.verbose(pb.command(), getOutput(), code, IOUtils.getPID(p)); - } - return code; - } catch (InterruptedException ex) { - Log.verbose(ex); - throw new RuntimeException(ex); - } - } - - private int waitForProcess(Process p) throws InterruptedException { - if (timeout == INFINITE_TIMEOUT) { - return p.waitFor(); - } else { - if (p.waitFor(timeout, TimeUnit.SECONDS)) { - return p.exitValue(); + if (timeout == null) { + result = exec.execute(); } else { - Log.verbose(String.format("Command %s timeout after %d seconds", - createLogMessage(pb, false), timeout)); - p.destroy(); - return -1; + result = exec.execute(timeout.toMillis(), TimeUnit.MILLISECONDS); + } + } catch (InterruptedException ex) { + throw ExceptionBox.toUnchecked(ex); + } + + if (dumpOutput()) { + log(result, printableOutputBuilder.create()); + } + + return result; + } + + Result executeExpectSuccess() throws IOException { + return execute().expectExitCode(0); + } + + Result executeExpect(int mainExitCode, int... otherExitCodes) throws IOException { + return execute().expectExitCode(mainExitCode, otherExitCodes); + } + + RetryExecutor retry() { + return Globals.instance().objectFactory().retryExecutor(IOException.class) + .setExecutable(this::executeExpectSuccess); + } + + RetryExecutor retryOnKnownErrorMessage(String msg) { + Objects.requireNonNull(msg); + return saveOutput().retry().setExecutable(() -> { + // Execute it without exit code check. + var result = execute(); + if (result.stderr().stream().anyMatch(msg::equals)) { + throw result.unexpected(); + } + return result; + }); + } + + List commandLine() { + if (processBuilder != null) { + return Stream.of(processBuilder.command(), args).flatMap(Collection::stream).toList(); + } else if (toolProvider != null) { + return Stream.concat(Stream.of(toolProvider.name()), args.stream()).toList(); + } else { + throw new IllegalStateException("No target to execute"); + } + } + + private ProcessBuilder copyProcessBuilder() { + if (processBuilder == null) { + throw new IllegalStateException(); + } + + var copy = new ProcessBuilder(commandLine()); + copy.directory(processBuilder.directory()); + var env = copy.environment(); + env.clear(); + env.putAll(processBuilder.environment()); + + return copy; + } + + private boolean dumpOutput() { + return Log.isVerbose() && !quietCommand; + } + + private static void log(Result result, String printableOutput) throws IOException { + Objects.requireNonNull(result); + Objects.requireNonNull(printableOutput); + + Optional pid; + if (result.execAttrs() instanceof ProcessAttributes attrs) { + pid = attrs.pid(); + } else { + pid = Optional.empty(); + } + + var sb = new StringBuilder(); + sb.append("Command"); + pid.ifPresent(p -> { + sb.append(" [PID: ").append(p).append("]"); + }); + sb.append(":\n ").append(result.execAttrs()); + Log.verbose(sb.toString()); + + if (!printableOutput.isEmpty()) { + sb.delete(0, sb.length()); + sb.append("Output:"); + try (var lines = new BufferedReader(new StringReader(printableOutput)).lines()) { + lines.forEach(line -> { + sb.append("\n ").append(line); + }); + } + Log.verbose(sb.toString()); + } + + result.exitCode().ifPresentOrElse(exitCode -> { + Log.verbose("Returned: " + exitCode + "\n"); + }, () -> { + Log.verbose("Aborted: timed-out" + "\n"); + }); + } + + private static final class PrintableOutputBuilder { + + PrintableOutputBuilder(CommandOutputControl coc) { + coc.dumpOutput(true); + charset = coc.charset(); + if (coc.isBinaryOutput()) { + // Assume binary output goes into stdout and text error messages go into stderr, so keep them separated. + sinks = new ByteArrayOutputStream[2]; + sinks[0] = new ByteArrayOutputStream(); + sinks[1] = new ByteArrayOutputStream(); + coc.dumpStdout(new PrintStream(sinks[0], false, charset)) + .dumpStderr(new PrintStream(sinks[1], false, charset)); + } else { + sinks = new ByteArrayOutputStream[1]; + sinks[0] = new ByteArrayOutputStream(); + var ps = new PrintStream(sinks[0], false, charset); + // Redirect stderr in stdout. + coc.dumpStdout(ps).dumpStderr(ps); } } - } - static Executor of(String... cmdline) { - return new Executor().setCommandLine(cmdline); - } - - static Executor of(ProcessBuilder pb) { - return new Executor().setProcessBuilder(pb); - } - - private static String createLogMessage(ProcessBuilder pb, boolean quiet) { - StringBuilder sb = new StringBuilder(); - sb.append((quiet) ? pb.command().get(0) : pb.command()); - if (pb.directory() != null) { - sb.append(String.format(" in %s", pb.directory().getAbsolutePath())); + String create() { + if (isBinaryOutput()) { + // In case of binary output: + // - Convert binary stdout to text using ISO-8859-1 encoding and + // replace non-printable characters with the question mark symbol (?). + // - Convert binary stderr to text using designated encoding (assume stderr is always a character stream). + // - Merge text stdout and stderr into a single string; + // stderr first, stdout follows, with the aim to present user error messages first. + var sb = new StringBuilder(); + var stdout = sinks[0].toString(StandardCharsets.ISO_8859_1).replaceAll("[^\\p{Print}\\p{Space}]", "?"); + return sb.append(sinks[1].toString(charset)).append(stdout).toString(); + } else { + return sinks[0].toString(charset); + } } - return sb.toString(); + + private boolean isBinaryOutput() { + return sinks.length == 2; + } + + private final ByteArrayOutputStream sinks[]; + private final Charset charset; } - public static final int INFINITE_TIMEOUT = -1; - - private ProcessBuilder pb; - private boolean saveOutput; - private boolean writeOutputToFile; + private final CommandOutputControl commandOutputControl; private boolean quietCommand; - private long timeout = INFINITE_TIMEOUT; - private List output; - private Consumer> outputConsumer; + private final List args; + private ProcessBuilder processBuilder; + private ToolProvider toolProvider; + private Duration timeout; + private UnaryOperator mapper; } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/ExecutorFactory.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/ExecutorFactory.java new file mode 100644 index 00000000000..ce703358b82 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/ExecutorFactory.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2026, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ +package jdk.jpackage.internal; + +@FunctionalInterface +interface ExecutorFactory { + + Executor executor(); + + static final ExecutorFactory DEFAULT = Executor::new; +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Globals.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Globals.java new file mode 100644 index 00000000000..c1b56b24e0a --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Globals.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2026, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ +package jdk.jpackage.internal; + +import java.util.Optional; +import java.util.function.Supplier; + +public final class Globals { + + private Globals() { + } + + Globals objectFactory(ObjectFactory v) { + checkMutable(); + objectFactory = Optional.ofNullable(v).orElse(ObjectFactory.DEFAULT); + return this; + } + + ObjectFactory objectFactory() { + return objectFactory; + } + + Globals executorFactory(ExecutorFactory v) { + return objectFactory(ObjectFactory.build(objectFactory).executorFactory(v).create()); + } + + public static int main(Supplier mainBody) { + if (INSTANCE.isBound()) { + return mainBody.get(); + } else { + return ScopedValue.where(INSTANCE, new Globals()).call(mainBody::get); + } + } + + public static Globals instance() { + return INSTANCE.orElse(DEFAULT); + } + + private void checkMutable() { + if (this == DEFAULT) { + throw new UnsupportedOperationException("Can't modify immutable instance"); + } + } + + private ObjectFactory objectFactory = ObjectFactory.DEFAULT; + + private static final ScopedValue INSTANCE = ScopedValue.newInstance(); + private static final Globals DEFAULT = new Globals(); +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/IOUtils.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/IOUtils.java index aac113d7777..08cf0c10982 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/IOUtils.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/IOUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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,9 @@ package jdk.jpackage.internal; import java.io.IOException; -import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.List; import jdk.jpackage.internal.model.JPackageException; /** @@ -50,46 +47,6 @@ final class IOUtils { StandardCopyOption.COPY_ATTRIBUTES); } - public static void exec(ProcessBuilder pb) - throws IOException { - exec(pb, false, null, false, Executor.INFINITE_TIMEOUT); - } - - // timeout in seconds. -1 will be return if process timeouts. - public static void exec(ProcessBuilder pb, long timeout) - throws IOException { - exec(pb, false, null, false, timeout); - } - - static void exec(ProcessBuilder pb, boolean testForPresenceOnly, - PrintStream consumer, boolean writeOutputToFile, long timeout) - throws IOException { - exec(pb, testForPresenceOnly, consumer, writeOutputToFile, - timeout, false); - } - - static void exec(ProcessBuilder pb, boolean testForPresenceOnly, - PrintStream consumer, boolean writeOutputToFile, - long timeout, boolean quiet) throws IOException { - List output = new ArrayList<>(); - Executor exec = Executor.of(pb) - .setWriteOutputToFile(writeOutputToFile) - .setTimeout(timeout) - .setQuiet(quiet) - .setOutputConsumer(lines -> { - lines.forEach(output::add); - if (consumer != null) { - output.forEach(consumer::println); - } - }); - - if (testForPresenceOnly) { - exec.execute(); - } else { - exec.executeExpectSuccess(); - } - } - static void writableOutputDir(Path outdir) { if (!Files.isDirectory(outdir)) { try { @@ -103,15 +60,4 @@ final class IOUtils { throw new JPackageException(I18N.format("error.cannot-write-to-output-dir", outdir.toAbsolutePath())); } } - - public static long getPID(Process p) { - try { - return p.pid(); - } catch (UnsupportedOperationException ex) { - Log.verbose(ex); // Just log exception and ignore it. This method - // is used for verbose output, so not a problem - // if unsupported. - return -1; - } - } } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/JLinkRuntimeBuilder.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/JLinkRuntimeBuilder.java index 37f166a4e7c..f960f8dc2bf 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/JLinkRuntimeBuilder.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/JLinkRuntimeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, 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 @@ -22,13 +22,14 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + package jdk.jpackage.internal; + import static jdk.jpackage.internal.model.RuntimeBuilder.getDefaultModulePath; +import static jdk.jpackage.internal.util.function.ThrowingRunnable.toRunnable; import java.io.File; import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; import java.lang.module.Configuration; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleFinder; @@ -50,7 +51,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import jdk.internal.module.ModulePath; import jdk.jpackage.internal.model.AppImageLayout; -import jdk.jpackage.internal.model.JPackageException; import jdk.jpackage.internal.model.LauncherModularStartupInfo; import jdk.jpackage.internal.model.LauncherStartupInfo; import jdk.jpackage.internal.model.RuntimeBuilder; @@ -58,27 +58,15 @@ import jdk.jpackage.internal.model.RuntimeBuilder; final class JLinkRuntimeBuilder implements RuntimeBuilder { private JLinkRuntimeBuilder(List jlinkCmdLine) { - this.jlinkCmdLine = jlinkCmdLine; + this.jlinkCmdLine = Objects.requireNonNull(jlinkCmdLine); } @Override public void create(AppImageLayout appImageLayout) { - var args = new ArrayList(); - args.add("--output"); - args.add(appImageLayout.runtimeDirectory().toString()); - args.addAll(jlinkCmdLine); - - StringWriter writer = new StringWriter(); - PrintWriter pw = new PrintWriter(writer); - - int retVal = LazyLoad.JLINK_TOOL.run(pw, pw, args.toArray(String[]::new)); - String jlinkOut = writer.toString(); - - args.add(0, "jlink"); - Log.verbose(args, List.of(jlinkOut), retVal, -1); - if (retVal != 0) { - throw new JPackageException(I18N.format("error.jlink.failed", jlinkOut)); - } + toRunnable(Executor.of() + .toolProvider(LazyLoad.JLINK_TOOL) + .args("--output", appImageLayout.runtimeDirectory().toString()) + .args(jlinkCmdLine)::executeExpectSuccess).run(); } @Override diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Log.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Log.java index b14b4ab22ca..0f51fa166f9 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Log.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Log.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, 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 @@ -28,7 +28,6 @@ package jdk.jpackage.internal; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; -import java.util.List; /** * Log @@ -105,29 +104,6 @@ public class Log { } } - public void verbose(List strings, - List output, int returnCode, long pid) { - if (verbose) { - StringBuilder sb = new StringBuilder(); - sb.append("Command [PID: "); - sb.append(pid); - sb.append("]:\n "); - - for (String s : strings) { - sb.append(" " + s); - } - verbose(sb.toString()); - if (output != null && !output.isEmpty()) { - sb = new StringBuilder("Output:"); - for (String s : output) { - sb.append("\n " + s); - } - verbose(sb.toString()); - } - verbose("Returned: " + returnCode + "\n"); - } - } - private String addTimestamp(String msg) { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); Date time = new Date(System.currentTimeMillis()); @@ -177,9 +153,4 @@ public class Log { public static void verbose(Throwable t) { instance.get().verbose(t); } - - public static void verbose(List strings, List out, - int ret, long pid) { - instance.get().verbose(strings, out, ret, pid); - } } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/ObjectFactory.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/ObjectFactory.java new file mode 100644 index 00000000000..f1a83eb9eab --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/ObjectFactory.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2026, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ +package jdk.jpackage.internal; + +import java.util.Objects; +import java.util.Optional; +import jdk.jpackage.internal.util.CompositeProxy; + +interface ObjectFactory extends ExecutorFactory, RetryExecutorFactory { + + static ObjectFactory.Builder build() { + return new Builder(); + } + + static ObjectFactory.Builder build(ObjectFactory from) { + return build().initFrom(from); + } + + static final class Builder { + private Builder() { + } + + ObjectFactory create() { + return CompositeProxy.build().invokeTunnel(CompositeProxyTunnel.INSTANCE).create( + ObjectFactory.class, + Optional.ofNullable(executorFactory).orElse(ExecutorFactory.DEFAULT), + Optional.ofNullable(retryExecutorFactory).orElse(RetryExecutorFactory.DEFAULT)); + } + + Builder initFrom(ObjectFactory of) { + Objects.requireNonNull(of); + return executorFactory(of).retryExecutorFactory(of); + } + + Builder executorFactory(ExecutorFactory v) { + executorFactory = v; + return this; + } + + Builder retryExecutorFactory(RetryExecutorFactory v) { + retryExecutorFactory = v; + return this; + } + + private ExecutorFactory executorFactory; + private RetryExecutorFactory retryExecutorFactory; + } + + static final ObjectFactory DEFAULT = build().create(); +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/RetryExecutor.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/RetryExecutor.java deleted file mode 100644 index f806217e8f9..00000000000 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/RetryExecutor.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2020, 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * 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. - */ -package jdk.jpackage.internal; - -import java.io.IOException; -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public final class RetryExecutor { - public RetryExecutor() { - setMaxAttemptsCount(5); - setAttemptTimeoutMillis(2 * 1000); - setWriteOutputToFile(false); - } - - public RetryExecutor setMaxAttemptsCount(int v) { - attempts = v; - return this; - } - - public RetryExecutor setAttemptTimeoutMillis(int v) { - timeoutMillis = v; - return this; - } - - public RetryExecutor saveOutput(boolean v) { - saveOutput = v; - return this; - } - - public List getOutput() { - return output; - } - - public RetryExecutor setWriteOutputToFile(boolean v) { - writeOutputToFile = v; - return this; - } - - public RetryExecutor setExecutorInitializer(Consumer v) { - executorInitializer = v; - return this; - } - - public void abort() { - aborted = true; - } - - public boolean isAborted() { - return aborted; - } - - static RetryExecutor retryOnKnownErrorMessage(String v) { - RetryExecutor result = new RetryExecutor(); - return result.setExecutorInitializer(exec -> { - exec.setOutputConsumer(output -> { - if (!output.anyMatch(v::equals)) { - result.abort(); - } - }); - }); - } - - public void execute(String cmdline[]) throws IOException { - executeLoop(() -> - Executor.of(cmdline).setWriteOutputToFile(writeOutputToFile)); - } - - public void execute(ProcessBuilder pb) throws IOException { - executeLoop(() -> - Executor.of(pb).setWriteOutputToFile(writeOutputToFile)); - } - - private void executeLoop(Supplier execSupplier) throws IOException { - aborted = false; - for (;;) { - if (aborted) { - break; - } - - try { - Executor exec = execSupplier.get().saveOutput(saveOutput); - if (executorInitializer != null) { - executorInitializer.accept(exec); - } - exec.executeExpectSuccess(); - if (saveOutput) { - output = exec.getOutput(); - } - break; - } catch (IOException ex) { - if (aborted || (--attempts) <= 0) { - throw ex; - } - } - - try { - Thread.sleep(timeoutMillis); - } catch (InterruptedException ex) { - Log.verbose(ex); - throw new RuntimeException(ex); - } - } - } - - private Consumer executorInitializer; - private boolean aborted; - private int attempts; - private int timeoutMillis; - private boolean saveOutput; - private List output; - private boolean writeOutputToFile; -} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/RetryExecutorFactory.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/RetryExecutorFactory.java new file mode 100644 index 00000000000..3efb522abd4 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/RetryExecutorFactory.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2026, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ +package jdk.jpackage.internal; + +import jdk.jpackage.internal.util.RetryExecutor; + +@FunctionalInterface +interface RetryExecutorFactory { + + RetryExecutor retryExecutor(Class exceptionType); + + static final RetryExecutorFactory DEFAULT = RetryExecutor::new; +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/SystemEnvironment.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/SystemEnvironment.java index de98e97c922..5d9a1d6d147 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/SystemEnvironment.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/SystemEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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,5 +24,5 @@ */ package jdk.jpackage.internal; -public interface SystemEnvironment { +interface SystemEnvironment { } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/ToolValidator.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/ToolValidator.java index 13e87d5cfa6..9440aff3a53 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/ToolValidator.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/ToolValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ -121,32 +121,32 @@ final class ToolValidator { cmdline.addAll(args); } - boolean canUseTool[] = new boolean[1]; + boolean canUseTool = false; if (minimalVersion == null) { // No version check. - canUseTool[0] = true; + canUseTool = true; } - String[] version = new String[1]; + String version = null; try { - Executor.of(cmdline.toArray(String[]::new)).setQuiet(true).setOutputConsumer(lines -> { - if (versionParser != null && minimalVersion != null) { - version[0] = versionParser.apply(lines); - if (version[0] != null && minimalVersion.compareTo(version[0]) <= 0) { - canUseTool[0] = true; - } + var result = Executor.of(cmdline).setQuiet(true).saveOutput().execute(); + var lines = result.content(); + if (versionParser != null && minimalVersion != null) { + version = versionParser.apply(lines.stream()); + if (version != null && minimalVersion.compareTo(version) <= 0) { + canUseTool = true; } - }).execute(); + } } catch (IOException e) { return new ConfigException(I18N.format("error.tool-error", toolPath, e.getMessage()), null, e); } - if (canUseTool[0]) { + if (canUseTool) { // All good. Tool can be used. return null; } else if (toolOldVersionErrorHandler != null) { - return toolOldVersionErrorHandler.apply(toolPath, version[0]); + return toolOldVersionErrorHandler.apply(toolPath, version); } else { return new ConfigException( I18N.format("error.tool-old-version", toolPath, minimalVersion), diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/Main.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/Main.java index 9feb5b40944..31be2bb33c5 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/Main.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/Main.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -45,6 +45,7 @@ import java.util.function.Supplier; import java.util.spi.ToolProvider; import jdk.internal.opt.CommandLine; import jdk.internal.util.OperatingSystem; +import jdk.jpackage.internal.Globals; import jdk.jpackage.internal.Log; import jdk.jpackage.internal.model.ConfigException; import jdk.jpackage.internal.model.JPackageException; @@ -56,7 +57,15 @@ import jdk.jpackage.internal.util.function.ExceptionBox; */ public final class Main { - public static final class Provider implements ToolProvider { + public record Provider(Supplier bundlingEnvSupplier) implements ToolProvider { + + public Provider { + Objects.requireNonNull(bundlingEnvSupplier); + } + + public Provider() { + this(DefaultBundlingEnvironmentLoader.INSTANCE); + } @Override public String name() { @@ -65,7 +74,7 @@ public final class Main { @Override public int run(PrintWriter out, PrintWriter err, String... args) { - return Main.run(out, err, args); + return Main.run(bundlingEnvSupplier, out, err, args); } @Override @@ -94,7 +103,23 @@ public final class Main { System.exit(run(out, err, args)); } - public static int run(PrintWriter out, PrintWriter err, String... args) { + static int run(PrintWriter out, PrintWriter err, String... args) { + return run(DefaultBundlingEnvironmentLoader.INSTANCE, out, err, args); + } + + static int run(Supplier bundlingEnvSupplier, PrintWriter out, PrintWriter err, String... args) { + return Globals.main(() -> { + return runWithGlobals(bundlingEnvSupplier, out, err, args); + }); + } + + private static int runWithGlobals( + Supplier bundlingEnvSupplier, + PrintWriter out, + PrintWriter err, + String... args) { + + Objects.requireNonNull(bundlingEnvSupplier); Objects.requireNonNull(args); for (String arg : args) { Objects.requireNonNull(arg); @@ -128,8 +153,7 @@ public final class Main { return preprocessStatus; } - final var bundlingEnv = ServiceLoader.load(CliBundlingEnvironment.class, - CliBundlingEnvironment.class.getClassLoader()).findFirst().orElseThrow(); + final var bundlingEnv = bundlingEnvSupplier.get(); final var parseResult = Utils.buildParser(OperatingSystem.current(), bundlingEnv).create().apply(mappedArgs.get()); @@ -285,4 +309,15 @@ public final class Main { private static String getVersion() { return System.getProperty("java.version"); } + + private enum DefaultBundlingEnvironmentLoader implements Supplier { + INSTANCE; + + @Override + public CliBundlingEnvironment get() { + return ServiceLoader.load( + CliBundlingEnvironment.class, + CliBundlingEnvironment.class.getClassLoader()).findFirst().orElseThrow(); + } + } } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/StandardOption.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/StandardOption.java index ec63c1fb498..0fa0af296dc 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/StandardOption.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/StandardOption.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -727,8 +727,15 @@ public final class StandardOption { // // regexp for parsing args (for example, for additional launchers) - private static Pattern pattern = Pattern.compile( - "(?:(?:([\"'])(?:\\\\\\1|.)*?(?:\\1|$))|(?:\\\\[\"'\\s]|[^\\s]))++"); + private static Pattern PATTERN = Pattern.compile(String.format( + "(?:(?:%s|%s)|(?:\\\\[\"'\\s]|\\S))++", + createPatternComponent('\''), + createPatternComponent('\"'))); + + private static String createPatternComponent(char quoteChar) { + var str = Character.toString(quoteChar); + return String.format("(?:%s(?:\\\\%s|[^%s])*+(?:%s|$))", str, str, str, str); + } static List getArgumentList(String inputString) { Objects.requireNonNull(inputString); @@ -741,7 +748,7 @@ public final class StandardOption { // The "pattern" regexp attempts to abide to the rule that // strings are delimited by whitespace unless surrounded by // quotes, then it is anything (including spaces) in the quotes. - Matcher m = pattern.matcher(inputString); + Matcher m = PATTERN.matcher(inputString); while (m.find()) { String s = inputString.substring(m.start(), m.end()).trim(); // Ensure we do not have an empty string. trim() will take care of diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/resources/MainResources.properties b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/resources/MainResources.properties index c5ea583514f..e97bee79e6e 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/resources/MainResources.properties +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/resources/MainResources.properties @@ -1,5 +1,5 @@ # -# Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2017, 2026, 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 @@ -96,7 +96,6 @@ error.tool-not-found.advice=Please install "{0}" error.tool-old-version=Can not find "{0}" {1} or newer error.tool-old-version.advice=Please install "{0}" {1} or newer -error.jlink.failed=jlink failed with: {0} error.blocked.option=jlink option [{0}] is not permitted in --jlink-options error.no.name=Name not specified with --name and cannot infer one from app-image error.no.name.advice=Specify name with --name diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/CommandLineFormat.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/CommandLineFormat.java new file mode 100644 index 00000000000..4d64030876f --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/CommandLineFormat.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2026, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ +package jdk.jpackage.internal.util; + +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Formats command line arguments. + */ +public final class CommandLineFormat { + + public String format(List cmdline) { + return cmdline.stream().map(enquoter::applyTo).collect(Collectors.joining(" ")); + } + + public static CommandLineFormat platform() { + var format = new CommandLineFormat(); + format.enquoter = Enquoter.identity().setEnquotePredicate(Enquoter.QUOTE_IF_WHITESPACES).setQuoteChar('\''); + return format; + } + + private CommandLineFormat() { + } + + private Enquoter enquoter; + + public static final Function, String> DEFAULT = platform()::format; +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/CommandOutputControl.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/CommandOutputControl.java new file mode 100644 index 00000000000..e35439815b1 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/CommandOutputControl.java @@ -0,0 +1,1904 @@ +/* + * Copyright (c) 2026, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ +package jdk.jpackage.internal.util; + +import static java.util.stream.Collectors.joining; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.StringReader; +import java.io.UncheckedIOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.IntPredicate; +import java.util.function.Predicate; +import java.util.spi.ToolProvider; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import jdk.jpackage.internal.util.function.ExceptionBox; +import jdk.jpackage.internal.util.function.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingRunnable; + +/** + * Runs commands and processes their stdout and stderr streams. + *

+ * A command is either a subprocess represented by {@link ProcessBuilder} or a + * tool provided by {@link ToolProvider}. + *

+ * A command is executed synchronously, and the result of its execution is + * stored in a {@link Result} instance which captures the exit code and any + * saved output streams. + *

+ * Depending on the configuration, it can save the entire output stream, only + * the first line, or not save the output at all. Stdout and stderr streams can + * be configured independently. + *

+ * Output streams can be treated as either byte streams or character streams. + * + *

+ * The table below shows how different parameter combinations affect the content + * written to streams returned by {@link #dumpStdout()} and + * {@link #dumpStderr()} for subsequently executed tools, regardless of whether + * their output streams are saved, or for subprocesses when the output streams + * are saved: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
discardStdout(false) and discardStderr(false)discardStdout(false) and discardStderr(true)discardStdout(true) and discardStderr(false)
redirectStderr(true) and dumpOutput(true) + *

+ * dumpStdout(): STDOUT and STDERR interleaved + *

+ * dumpStderr(): unchanged

+ *

+ * dumpStdout(): STDOUT + *

+ * dumpStderr(): unchanged

+ *

+ * dumpStdout(): STDERR; + *

+ * dumpStderr(): unchanged

redirectStderr(false) and dumpOutput(true) + *

+ * dumpStdout(): STDOUT + *

+ * dumpStderr(): STDERR

+ *

+ * dumpStdout(): STDOUT + *

+ * dumpStderr(): unchanged

+ *

+ * dumpStdout(): unchanged + *

+ * dumpStderr(): STDERR

+ * + *

+ * The table below shows how different parameter combinations affect the content + * written to the native file descriptors associated with {@link System#out} and + * {@link System#err} for subsequently executed subprocesses when the output + * streams are not saved: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
discardStdout(false) and discardStderr(false)discardStdout(false) and discardStderr(true)discardStdout(true) and discardStderr(false)
redirectStderr(true) and dumpOutput(true) + *

+ * System.out: STDOUT and STDERR interleaved + *

+ * System.err: unchanged

+ *

+ * System.out: STDOUT + *

+ * System.err: unchanged

+ *

+ * System.out: STDERR; + *

+ * The command's STDERR will be written to the stream referenced by + * {@link #dumpStdout()} rather than to the underlying file descriptor + * associated with the Java process's STDOUT + *

+ * System.err: unchanged

redirectStderr(false) and dumpOutput(true) + *

+ * System.out: STDOUT + *

+ * System.err: STDERR

+ *

+ * System.out: STDOUT + *

+ * System.err: unchanged

+ *

+ * System.out: unchanged + *

+ * System.err: STDERR

+ * + *

+ * The table below shows how different parameter combinations affect the + * properties of {@link Result} objects returned by + * {@link #execute(ProcessBuilder, long)} or + * {@link #execute(ToolProvider, long, String...)} when processing character + * streams: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
saveOutput(true)saveFirstLineOfOutput()
redirectStderr(true) and discardStdout(false) and + * discardStderr(false) + *

+ * content(): STDOUT and STDERR interleaved + *

+ * findStdout(): {@code Optional.empty()} + *

+ * findStderr(): {@code Optional.empty()}

+ *

+ * content(): a single-item list containing the first line of interleaved STDOUT + * and STDERR if the command produced any output; otherwise, an empty list + *

+ * findStdout(): {@code Optional.empty()} + *

+ * findStderr(): {@code Optional.empty()}

redirectStderr(false) and discardStdout(false) and + * discardStderr(false) + *

+ * content(): STDOUT followed by STDERR + *

+ * stdout(): STDOUT + *

+ * stderr(): STDERR

+ *

+ * content(): a list containing at most two items: the first line of STDOUT (if + * the command produced any), followed by the first line of STDERR (if the + * command produced any) + *

+ * stdout(): The first line of STDOUT (if the command produced any); otherwise + * an empty list + *

+ * findStderr(): The first line of STDERR (if the command produced any); + * otherwise an empty list + *

redirectStderr(true) and discardStdout(false) and + * discardStderr(true) + *

+ * content(): STDOUT + *

+ * stdout(): The same as content() + *

+ * findStderr(): {@code Optional.empty()}

+ *

+ * content(): The first line of STDOUT (if the command produced any); otherwise + * an empty list + *

+ * stdout(): The same as content() + *

+ * findStderr(): {@code Optional.empty()}

redirectStderr(false) and discardStdout(false) and + * discardStderr(true) + *

+ * content(): STDOUT + *

+ * stdout(): The same as content() + *

+ * stderr(): an empty list

+ *

+ * content(): The first line of STDOUT (if the command produced any); otherwise + * an empty list + *

+ * stdout(): The same as content() + *

+ * stderr(): an empty list

redirectStderr(true) and discardStdout(true) and + * discardStderr(false) + *

+ * content(): STDERR + *

+ * stdout(): The same as content() + *

+ * findStderr(): {@code Optional.empty()}

+ *

+ * content(): The first line of STDERR (if the command produced any); otherwise + * an empty list + *

+ * stdout(): The same as content() + *

+ * findStderr(): {@code Optional.empty()}

redirectStderr(false) and discardStdout(true) and + * discardStderr(false) + *

+ * content(): STDERR + *

+ * findStdout(): an empty list + *

+ * stderr(): The same as content()

+ *

+ * content(): The first line of STDERR (if the command produced any); otherwise + * an empty list + *

+ * findStdout(): an empty list + *

+ * stderr(): The same as content()

+ *

+ * The table below shows how different parameter combinations affect the + * properties of {@link Result} objects returned by + * {@link #execute(ProcessBuilder, long)} or + * {@link #execute(ToolProvider, long, String...)} when processing byte streams: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
saveOutput(true) or saveFirstLineOfOutput()
redirectStderr(true) and discardStdout(false) and + * discardStderr(false) + *

+ * byteContent(): STDOUT and STDERR interleaved + *

+ * findByteStdout(): {@code Optional.empty()} + *

+ * findByteStderr(): {@code Optional.empty()}

redirectStderr(false) and discardStdout(false) and + * discardStderr(false) + *

+ * byteContent(): STDOUT followed by STDERR + *

+ * byteStdout(): STDOUT + *

+ * byteStderr(): STDERR

redirectStderr(true) and discardStdout(false) and + * discardStderr(true) + *

+ * byteContent(): STDOUT + *

+ * byteStdout(): The same as byteContent() + *

+ * findByteStderr(): {@code Optional.empty()}

redirectStderr(false) and discardStdout(false) and + * discardStderr(true) + *

+ * byteContent(): STDOUT + *

+ * byteStdout(): The same as byteContent() + *

+ * byteStderr(): an empty array

redirectStderr(true) and discardStdout(true) and + * discardStderr(false) + *

+ * byteContent(): STDERR + *

+ * byteStdout(): The same as byteContent() + *

+ * findByteStderr(): {@code Optional.empty()}

redirectStderr(false) and discardStdout(true) and + * discardStderr(false) + *

+ * byteContent(): STDERR + *

+ * findByteStdout(): an empty array + *

+ * byteStderr(): The same as byteContent()

+ */ +public final class CommandOutputControl { + + public CommandOutputControl() { + outputStreamsControl = new OutputStreamsControl(); + } + + private CommandOutputControl(CommandOutputControl other) { + flags = other.flags; + outputStreamsControl = other.outputStreamsControl.copy(); + dumpStdout = other.dumpStdout; + dumpStderr = other.dumpStderr; + charset = other.charset; + processListener = other.processListener; + } + + /** + * Specifies whether the full output produced by commands subsequently executed + * by this object will be saved. + *

+ * If {@code v} is {@code true}, both stdout and stderr streams will be saved; + * otherwise, they will not be saved. + *

+ * This setting is mutually exclusive with {@link #saveFirstLineOfOutput()}. + * + * @param v {@code true} to save the full stdout and stderr streams; + * {@code false} otherwise + * @return this + */ + public CommandOutputControl saveOutput(boolean v) { + return setOutputControl(v, OutputControlOption.SAVE_ALL); + } + + /** + * Returns whether this object will save the complete output of commands + * subsequently executed. + * + * @return {@code true} if this object will save the full output of commands it + * executes subsequently; {@code false} otherwise + */ + public boolean isSaveOutput() { + return outputStreamsControl.stdout().saveAll(); + } + + /** + * Specifies whether the first line of the output, combined from the stdout and + * stderr streams of commands subsequently executed by this object, will be + * saved. + *

+ * This setting is mutually exclusive with {@link #saveOutput(boolean)}. + * + * @return this + */ + public CommandOutputControl saveFirstLineOfOutput() { + return setOutputControl(true, OutputControlOption.SAVE_FIRST_LINE); + } + + /** + * Returns whether this object will save the first line of the output of + * commands subsequently executed. + * + * @return {@code true} if this object will save the first line of the output of + * commands it executes subsequently; {@code false} otherwise + */ + public boolean isSaveFirstLineOfOutput() { + return outputStreamsControl.stdout().saveFirstLine(); + } + + /** + * Specifies whether this object will dump the output streams from + * subsequently executed commands into the streams returned by + * {@link #dumpStdout()} and {@link #dumpStdout()} methods respectively. + *

+ * If this object is configured to redirect stderr of subsequently executed + * commands into their stdout ({@code redirectStderr(true)}), their output + * streams will be dumped into the stream returned by {@code dumpStdout()} + * method. Otherwise, their stdout and stderr streams will be dumped into the + * stream returned by {@code dumpStdout()} and {@code dumpStderr()} methods + * respectively. + * + * @param v if output streams from subsequently executed commands will be + * dumped into streams returned by {@code dumpStdout()} and + * {@code dumpStderr()} methods respectively + * + * @return this + * + * @see #redirectStderr(boolean) + * @see #dumpStdout() + * @see #dumpStderr() + */ + public CommandOutputControl dumpOutput(boolean v) { + setFlag(Flag.DUMP, v); + return setOutputControl(v, OutputControlOption.DUMP); + } + + /** + * Returns the value passed in the last call of {@link #dumpOutput(boolean)} + * method on this object, or {@code false} if the method has not been called. + * + * @return the value passed in the last call of {@link #dumpOutput(boolean)} + */ + public boolean isDumpOutput() { + return Flag.DUMP.isSet(flags); + } + + /** + * Specifies whether this object will treat output streams of subsequently + * executed commands as byte streams rather than character streams. + * + * @param v {@code true} if this object will treat the output streams of + * subsequently executed commands as byte streams, and {@code false} + * otherwise + * + * @return this + */ + public CommandOutputControl binaryOutput(boolean v) { + return setFlag(Flag.BINARY_OUTPUT, v); + } + + /** + * Returns the value passed in the last call of {@link #binaryOutput(boolean)} + * method on this object, or {@code false} if the method has not been called. + * + * @return the value passed in the last call of {@link #binaryOutput(boolean)} + */ + public boolean isBinaryOutput() { + return Flag.BINARY_OUTPUT.isSet(flags); + } + + /** + * Sets character encoding that will be applied to the stdout and the stderr + * streams of commands (subprocesses and {@code ToolProvider}-s) subsequently + * executed by this object. The default encoding is {@code UTF-8}. + *

+ * The value will be ignored if this object is configured for byte output + * streams. + * + * @param v character encoding for output streams of subsequently executed + * commands + * + * @see #binaryOutput(boolean) + * + * @return this + */ + public CommandOutputControl charset(Charset v) { + charset = v; + return this; + } + + /** + * Returns the value passed in the last call of + * {@link #charset(Charset)} method on this object, or + * {@link StandardCharsets#UTF_8} if the method has not been called. + * + * @return the character encoding that will be applied to the stdout and stderr + * streams of commands subsequently executed by this object + */ + public Charset charset() { + return Optional.ofNullable(charset).orElse(StandardCharsets.UTF_8); + } + + /** + * Specifies whether the stderr stream will be redirected into the stdout stream + * for commands subsequently executed by this object. + * + * @see ProcessBuilder#redirectErrorStream(boolean) + * + * @param v {@code true} if the stderr stream of commands subsequently executed + * by this object will be redirected into the stdout stream; + * {@code false} otherwise + * + * @return this + */ + public CommandOutputControl redirectStderr(boolean v) { + return setFlag(Flag.REDIRECT_STDERR, v); + } + + /** + * Returns the value passed in the last call of {@link #redirectStderr(boolean)} + * method on this object, or {@code false} if the method has not been called. + * + * @return the value passed in the last call of {@link #redirectStderr(boolean)} + */ + public boolean isRedirectStderr() { + return Flag.REDIRECT_STDERR.isSet(flags); + } + + /** + * Specifies whether stderr and stdout streams for subprocesses subsequently + * executed by this object will be stored in files. + *

+ * By default, if an output stream of a subprocess is configured for saving, + * this object will retrieve the content using {@link Process#getInputStream()} + * function for stdout and {@link Process#getErrorStream()} function for stderr. + * However, these functions don't always work correctly due to a + * JDK-8236825 bug + * still reproducible on macOS JDK26. The alternative way to get the content of + * output streams of a subprocess is to redirect them into files and read these + * files when the subprocess terminates. + *

+ * It will use {@code Files.createTempFile("jpackageOutputTempFile", ".tmp")} to + * create a file for each subprocess's output stream configured for saving. All + * created files will be automatically deleted at the exit of + * {@link #execute(ProcessBuilder, long)} method. + *

+ * Doesn't apply to executing {@code ToolProvider}-s. + *

+ * Storing output streams in files takes longer than managing them in memory and + * should be avoided if possible. + * + * @param v {@code true} if this object will use files to store saved output + * streams of subsequently executed subprocesses; {@code false} + * otherwise + * @return this + */ + public CommandOutputControl storeOutputInFiles(boolean v) { + return setFlag(Flag.STORE_OUTPUT_IN_FILES, v); + } + + /** + * Returns the value passed in the last call of {@link #storeOutputInFiles(boolean)} + * method on this object, or {@code false} if the method has not been called. + * + * @return the value passed in the last call of {@link #storeOutputInFiles(boolean)} + */ + public boolean isStoreOutputInFiles() { + return Flag.STORE_OUTPUT_IN_FILES.isSet(flags); + } + + /** + * Specifies whether stdout streams from commands subsequently executed by this + * object will be discarded. + * + * @param v {@code true} if this object will discard stdout streams from + * commands subsequently executed by this object; {@code false} + * otherwise + * @return this + */ + public CommandOutputControl discardStdout(boolean v) { + setFlag(Flag.DISCARD_STDOUT, v); + outputStreamsControl.stdout().discard(v); + return this; + } + + /** + * Returns the value passed in the last call of {@link #discardStdout(boolean)} + * method on this object, or {@code false} if the method has not been called. + * + * @return the value passed in the last call of {@link #discardStdout(boolean)} + */ + public boolean isDiscardStdout() { + return Flag.DISCARD_STDOUT.isSet(flags); + } + + /** + * Specifies whether stderr streams from commands subsequently executed by this + * object will be discarded. + * + * @param v {@code true} if this object will discard stderr streams from + * commands subsequently executed by this object; {@code false} + * otherwise + * @return this + */ + public CommandOutputControl discardStderr(boolean v) { + setFlag(Flag.DISCARD_STDERR, v); + outputStreamsControl.stderr().discard(v); + return this; + } + + /** + * Returns the value passed in the last call of {@link #discardStderr(boolean)} + * method on this object, or {@code false} if the method has not been called. + * + * @return the value passed in the last call of {@link #discardStderr(boolean)} + */ + public boolean isDiscardStderr() { + return Flag.DISCARD_STDERR.isSet(flags); + } + + /** + * Specifies the stream where stdout streams from commands subsequently executed + * by this object will be dumped. + *

+ * If the {@code null} is specified and this object configuration is equivalent + * to {@code dumpOutput(true).saveOutput(false).discardStdout(false)} the stdout + * streams from commands subsequently executed by this object will be written + * into the file descriptor associated with the {@code Systsem.out} stream. If + * you want them to be written into the {@code Systsem.out} object, pass the + * {@code Systsem.out} reference into this function. + * + * @param v the stream where stdout streams from commands subsequently executed + * by this object will be dumped; {@code null} permitted + * @return this + */ + public CommandOutputControl dumpStdout(PrintStream v) { + dumpStdout = v; + return this; + } + + /** + * Returns the value passed in the last call of {@link #dumpStdout(PrintStream)} + * method on this object, or {@link System#out} if the method has not been + * called. + * + * @return the stream where stdout streams from commands subsequently executed + * by this object will be dumped + */ + public PrintStream dumpStdout() { + return Optional.ofNullable(dumpStdout).orElse(System.out); + } + + /** + * Specifies the stream where stderr streams from commands subsequently executed + * by this object will be dumped. + *

+ * If the {@code null} is specified and this object configuration is equivalent + * to + * {@code dumpOutput(true).saveOutput(false).redirectStderr(false).discardStderr(false)} + * the stderr streams from commands subsequently executed by this object will be + * written into the file descriptor associated with the {@code Systsem.err} + * stream. If you want them to be written into the {@code Systsem.err} object, + * pass the {@code Systsem.err} reference into this function. + * + * @param v the stream where stderr streams from commands subsequently executed + * by this object will be dumped; {@code null} permitted + * @return this + */ + public CommandOutputControl dumpStderr(PrintStream v) { + dumpStderr = v; + return this; + } + + /** + * Returns the value passed in the last call of {@link #dumpStderr(PrintStream)} + * method on this object, or {@link System#err} if the method has not been + * called. + * + * @return the stream where stderr streams from commands subsequently executed + * by this object will be dumped + */ + public PrintStream dumpStderr() { + return Optional.ofNullable(dumpStderr).orElse(System.err); + } + + /** + * Sets the callback to be invoked when this object starts a subprocess from + * subsequent {@link #execute(ProcessBuilder, long)} calls. + * + *

+ * This object maintains a single callback. Calling this method replaces any + * previously set callback. + * + *

+ * The callback is invoked on the thread that calls + * {@link #execute(ProcessBuilder, long)} after the subprocess's output streams + * begin being pumped. + * + * @param v the callback for notifying a subprocess being started or + * {@code null} + * @return this + */ + public CommandOutputControl processListener(Consumer v) { + processListener = v; + return this; + } + + /** + * Returns an {@code Optional} wrapping the value passed in the last call of + * {@link #processListener(Consumer)} method on this object, or an empty + * {@code Optional} if the method has not been called or {@code null} was passed in the last call. + * + * @return an {@code Optional} wrapping the value passed in the last call of + * {@link #processListener(Consumer)} + */ + public Optional> processListener() { + return Optional.ofNullable(processListener); + } + + /** + * Returns a deep copy of this object. Changes to the copy will not affect the + * original. + * + * @return a deep copy of this object + */ + public CommandOutputControl copy() { + return new CommandOutputControl(this); + } + + public interface ExecutableAttributes { + List commandLine(); + } + + public sealed interface Executable { + + ExecutableAttributes attributes(); + + Result execute() throws IOException, InterruptedException; + + Result execute(long timeout, TimeUnit unit) throws IOException, InterruptedException; + } + + public record ProcessAttributes(Optional pid, List commandLine) implements ExecutableAttributes { + public ProcessAttributes { + Objects.requireNonNull(pid); + commandLine.forEach(Objects::requireNonNull); + } + + @Override + public String toString() { + return CommandLineFormat.DEFAULT.apply(commandLine()); + } + } + + public record ToolProviderAttributes(String name, List args) implements ExecutableAttributes { + public ToolProviderAttributes { + Objects.requireNonNull(name); + args.forEach(Objects::requireNonNull); + } + + @Override + public String toString() { + return CommandLineFormat.DEFAULT.apply(commandLine()); + } + + @Override + public List commandLine() { + return Stream.concat(Stream.of(name), args.stream()).toList(); + } + } + + public static ExecutableAttributes EMPTY_EXECUTABLE_ATTRIBUTES = new ExecutableAttributes() { + @Override + public String toString() { + return ""; + } + + @Override + public List commandLine() { + return List.of(); + } + }; + + public Executable createExecutable(ToolProvider tp, String... args) { + return new ToolProviderExecutable(tp, List.of(args), this); + } + + public Executable createExecutable(ProcessBuilder pb) { + return new ProcessExecutable(pb, this); + } + + public record Result( + Optional exitCode, + Optional>> output, + Optional> byteOutput, + ExecutableAttributes execAttrs) { + + public Result { + Objects.requireNonNull(exitCode); + Objects.requireNonNull(output); + Objects.requireNonNull(byteOutput); + Objects.requireNonNull(execAttrs); + } + + public Result(int exitCode) { + this(Optional.of(exitCode), Optional.empty(), Optional.empty(), EMPTY_EXECUTABLE_ATTRIBUTES); + } + + public int getExitCode() { + return exitCode.orElseThrow(() -> { + return new IllegalStateException("Exit code is unavailable for timed-out command"); + }); + } + + public Result expectExitCode(int main, int... other) throws UnexpectedExitCodeException { + return expectExitCode(v -> { + return IntStream.concat(IntStream.of(main), IntStream.of(other)).boxed().anyMatch(Predicate.isEqual(v)); + }); + } + + public Result expectExitCode(Collection expected) throws UnexpectedExitCodeException { + return expectExitCode(expected::contains); + } + + public Result expectExitCode(IntPredicate expected) throws UnexpectedExitCodeException { + if (!expected.test(getExitCode())) { + throw new UnexpectedExitCodeException(this); + } + return this; + } + + public UnexpectedResultException unexpected() { + return new UnexpectedResultException(this); + } + + public UnexpectedResultException unexpected(String message) { + return new UnexpectedResultException(this, message); + } + + public Optional> findContent() { + return output.flatMap(CommandOutput::combined); + } + + public Optional> findStdout() { + return output.flatMap(CommandOutput::stdout); + } + + public Optional> findStderr() { + return output.flatMap(CommandOutput::stderr); + } + + // For backward compatibility + public List getOutput() { + return content(); + } + + public List content() { + return findContent().orElseThrow(); + } + + public List stdout() { + return findStdout().orElseThrow(); + } + + public List stderr() { + return findStderr().orElseThrow(); + } + + public Optional findByteContent() { + return byteOutput.flatMap(CommandOutput::combined); + } + + public Optional findByteStdout() { + return byteOutput.flatMap(CommandOutput::stdout); + } + + public Optional findByteStderr() { + return byteOutput.flatMap(CommandOutput::stderr); + } + + public byte[] byteContent() { + return findByteContent().orElseThrow(); + } + + public byte[] byteStdout() { + return findByteStdout().orElseThrow(); + } + + public byte[] byteStderr() { + return findByteStderr().orElseThrow(); + } + + public Result toCharacterResult(Charset charset, boolean keepByteContent) throws IOException { + Objects.requireNonNull(charset); + + if (byteOutput.isEmpty()) { + return this; + } + + var theByteOutput = byteOutput.get(); + + try { + Optional>> out; + if (theByteOutput.content().isEmpty()) { + // The content is unavailable. + out = Optional.empty(); + } else if (theByteOutput.stdoutContentSize() == 0) { + // The content is available, but empty. + out = Optional.of(new StringListContent(List.of())); + } else if (theByteOutput.interleaved()) { + // STDOUT and STDERR streams are interleaved. + out = theByteOutput.combined().map(data -> { + return toStringList(data, charset); + }); + } else { + // Non-empty STDOUT not interleaved with STDERR. + out = findByteStdout().map(data -> { + return toStringList(data, charset); + }); + } + + var err = findByteStderr().map(data -> { + return toStringList(data, charset); + }); + + var newOutput = combine(out, err, theByteOutput.interleaved); + + return new Result(exitCode, Optional.of(newOutput), byteOutput.filter(_ -> keepByteContent), execAttrs); + } catch (UncheckedIOException ex) { + throw ex.getCause(); + } + } + + public Result copyWithExecutableAttributes(ExecutableAttributes execAttrs) { + return new Result(exitCode, output, byteOutput, Objects.requireNonNull(execAttrs)); + } + + private static StringListContent toStringList(byte[] data, Charset charset) { + try (var bufReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data), charset))) { + return new StringListContent(bufReader.lines().toList()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + } + + public static sealed class UnexpectedResultException extends IOException { + + private UnexpectedResultException(Result value, String message) { + super(Objects.requireNonNull(message)); + this.value = Objects.requireNonNull(value); + } + + private UnexpectedResultException(Result value) { + this(value, String.format("Unexpected result from executing the command %s", value.execAttrs())); + } + + public Result getResult() { + return value; + } + + private final transient Result value; + + private static final long serialVersionUID = 1L; + } + + public static final class UnexpectedExitCodeException extends UnexpectedResultException { + + public UnexpectedExitCodeException(Result value, String message) { + super(value, message); + } + + public UnexpectedExitCodeException(Result value) { + this(value, String.format("Unexpected exit code %d from executing the command %s", value.getExitCode(), value.execAttrs())); + } + + private static final long serialVersionUID = 1L; + } + + public String description() { + var tokens = outputStreamsControl.descriptionTokens(); + if (isBinaryOutput()) { + tokens.add("byte"); + } + if (redirectRetainedStderr()) { + tokens.add("interleave"); + } + return String.join("; ", tokens); + } + + private Result execute(ProcessBuilder pb, long timeoutMillis) + throws IOException, InterruptedException { + + Objects.requireNonNull(pb); + + var theCharset = charset(); + + configureProcessBuilder(pb); + + var csc = new CachingStreamsConfig(); + + var process = pb.start(); + + BiConsumer gobbler = (in, ps) -> { + try { + if (isBinaryOutput()) { + try (in) { + in.transferTo(ps); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } else { + try (var bufReader = new BufferedReader(new InputStreamReader(in, theCharset))) { + bufReader.lines().forEach(ps::println); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + } finally { + suppressIOException(ps::flush); + } + }; + + // Start fetching process output streams. + // Do it before waiting for the process termination to avoid deadlocks. + + final Optional> stdoutGobbler; + if (mustReadOutputStream(pb.redirectOutput())) { + stdoutGobbler = Optional.of(CompletableFuture.runAsync(() -> { + gobbler.accept(process.getInputStream(), csc.out()); + }, gobblerExecutor)); + } else { + stdoutGobbler = Optional.empty(); + } + + final Optional> stderrGobbler; + if (!pb.redirectErrorStream() && mustReadOutputStream(pb.redirectError())) { + stderrGobbler = Optional.of(CompletableFuture.runAsync(() -> { + gobbler.accept(process.getErrorStream(), csc.err()); + }, gobblerExecutor)); + } else { + stderrGobbler = Optional.empty(); + } + + processListener().ifPresent(c -> { + c.accept(process); + }); + + final Optional exitCode; + if (timeoutMillis < 0) { + exitCode = Optional.of(process.waitFor()); + } else if (!process.waitFor(timeoutMillis, TimeUnit.MILLISECONDS)) { + // Destroy the process and cancel the process output stream gobblers. + process.destroy(); + for (var g : List.of(stdoutGobbler, stderrGobbler)) { + g.ifPresent(future -> { + future.cancel(true); + }); + } + exitCode = Optional.empty(); + } else { + exitCode = Optional.of(process.exitValue()); + } + + try { + if (isStoreOutputInFiles()) { + var stdoutStorage = streamFileSink(pb.redirectOutput()); + var stderrStorage = streamFileSink(pb.redirectError()); + + Function toInputStream = path -> { + try { + return Files.newInputStream(path); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }; + + try { + stdoutStorage.map(toInputStream).ifPresent(in -> { + gobbler.accept(in, csc.out()); + }); + + stderrStorage.map(toInputStream).ifPresent(in -> { + gobbler.accept(in, csc.err()); + }); + } finally { + Consumer silentDeleter = path -> { + suppressIOException(Files::delete, path); + }; + + stdoutStorage.ifPresent(silentDeleter); + stderrStorage.ifPresent(silentDeleter); + } + } else { + stdoutGobbler.ifPresent(CommandOutputControl::join); + stderrGobbler.ifPresent(CommandOutputControl::join); + } + } catch (UncheckedIOException ex) { + throw ex.getCause(); + } + + return csc.createResult(exitCode, new ProcessAttributes(getPID(process), pb.command())); + } + + private Result execute(ToolProvider tp, long timeoutMillis, String... args) + throws IOException, InterruptedException { + + var csc = new CachingStreamsConfig(); + + Optional exitCode; + var out = csc.out(); + var err = csc.err(); + try { + if (timeoutMillis < 0) { + exitCode = Optional.of(tp.run(out, err, args)); + } else { + var future = new CompletableFuture>(); + + var workerThread = Thread.ofVirtual().start(() -> { + Optional result = Optional.empty(); + try { + result = Optional.of(tp.run(out, err, args)); + } catch (Exception ex) { + future.completeExceptionally(ex); + return; + } + future.complete(result); + }); + + try { + exitCode = future.get(timeoutMillis, TimeUnit.MILLISECONDS); + } catch (ExecutionException ex) { + // Rethrow the cause (ex.getCause()) as a RuntimeException. + // If `ex.getCause()` returns an Error, ExceptionBox.unbox() will throw it. + throw ExceptionBox.toUnchecked(ExceptionBox.unbox(ex.getCause())); + } catch (TimeoutException ex) { + workerThread.interrupt(); + exitCode = Optional.empty(); + } + } + } finally { + suppressIOException(out::flush); + suppressIOException(err::flush); + } + + return csc.createResult(exitCode, new ToolProviderAttributes(tp.name(), List.of(args))); + } + + private CommandOutputControl setOutputControl(boolean set, OutputControlOption v) { + outputStreamsControl.stdout().set(set, v); + outputStreamsControl.stderr().set(set, v); + return this; + } + + private CommandOutputControl setFlag(Flag flag, boolean v) { + flags = flag.set(flags, v); + return this; + } + + private Optional streamFileSink(ProcessBuilder.Redirect redirect) { + return Optional.of(redirect) + .filter(Predicate.isEqual(ProcessBuilder.Redirect.DISCARD).negate()) + .map(ProcessBuilder.Redirect::file) + .map(File::toPath); + } + + private void configureProcessBuilder(ProcessBuilder pb) throws IOException { + + var stdoutRedirect = outputStreamsControl.stdout().asProcessBuilderRedirect(); + var stderrRedirect = outputStreamsControl.stderr().asProcessBuilderRedirect(); + + if (!stdoutRedirect.equals(stderrRedirect) && Stream.of( + stdoutRedirect, + stderrRedirect + ).noneMatch(Predicate.isEqual(ProcessBuilder.Redirect.DISCARD)) && redirectRetainedStderr()) { + throw new IllegalStateException(String.format( + "Can't redirect stderr into stdout because they have different redirects: stdout=%s; stderr=%s", + stdoutRedirect, stderrRedirect)); + } + + pb.redirectErrorStream(redirectRetainedStderr()); + if (replaceStdoutWithStderr()) { + if (stderrRedirect.equals(ProcessBuilder.Redirect.INHERIT)) { + stderrRedirect = ProcessBuilder.Redirect.PIPE; + } + pb.redirectErrorStream(false); + } + + stdoutRedirect = mapRedirect(stdoutRedirect); + stderrRedirect = mapRedirect(stderrRedirect); + + if (dumpStdout != null && stdoutRedirect.equals(ProcessBuilder.Redirect.INHERIT)) { + stdoutRedirect = ProcessBuilder.Redirect.PIPE; + } + + if (dumpStderr != null && stderrRedirect.equals(ProcessBuilder.Redirect.INHERIT)) { + stderrRedirect = ProcessBuilder.Redirect.PIPE; + } + + pb.redirectOutput(stdoutRedirect); + pb.redirectError(stderrRedirect); + } + + private ProcessBuilder.Redirect mapRedirect(ProcessBuilder.Redirect redirect) throws IOException { + if (isStoreOutputInFiles() && redirect.equals(ProcessBuilder.Redirect.PIPE)) { + var sink = Files.createTempFile("jpackageOutputTempFile", ".tmp"); + return ProcessBuilder.Redirect.to(sink.toFile()); + } else { + return redirect; + } + } + + /** + * Returns {@code true} if STDERR is not discarded and will be redirected to STDOUT, and {@code false} otherwise. + */ + private boolean redirectRetainedStderr() { + return isRedirectStderr() && !outputStreamsControl.stderr().discard(); + } + + /** + * Returns {@code true} if STDERR will replace STDOUT, and {@code false} otherwise. + *

+ * STDERR will replace STDOUT if it is redirected and not discarded, and if STDOUT is discarded. + */ + private boolean replaceStdoutWithStderr() { + return redirectRetainedStderr() && outputStreamsControl.stdout().discard(); + } + + private static T join(CompletableFuture future, T cancelledValue) { + Objects.requireNonNull(future); + try { + return future.join(); + } catch (CancellationException ex) { + return cancelledValue; + } catch (CompletionException ex) { + switch (ExceptionBox.unbox(ex.getCause())) { + case IOException cause -> { + throw new UncheckedIOException(cause); + } + case UncheckedIOException cause -> { + throw cause; + } + case Exception cause -> { + throw ExceptionBox.toUnchecked(cause); + } + } + } + } + + private static void join(CompletableFuture future) { + join(future, null); + } + + private static boolean mustReadOutputStream(ProcessBuilder.Redirect redirect) { + return redirect.equals(ProcessBuilder.Redirect.PIPE); + } + + private static Optional> read(OutputControl outputControl, CachingPrintStream cps) throws IOException { + final var bufferAsString = cps.bufferContents(); + try (final var bufReader = new BufferedReader(new StringReader(bufferAsString.orElse("")))) { + if (outputControl.saveFirstLine()) { + return Optional.of(bufReader.lines().findFirst().map(List::of).orElseGet(List::of)); + } else if (outputControl.saveAll()) { + return Optional.of(bufReader.lines().toList()); + } else { + return Optional.empty(); + } + } catch (UncheckedIOException ex) { + throw ex.getCause(); + } + } + + private static Optional readBinary(OutputControl outputControl, CachingPrintStream cps) { + if (outputControl.save()) { + return cps.buf().map(ByteArrayOutputStream::toByteArray).or(() -> { + return Optional.of(new byte[0]); + }); + } else { + return Optional.empty(); + } + } + + private static CommandOutput combine( + Optional> out, + Optional> err, + boolean interleaved) { + + if (out.isEmpty() && err.isEmpty()) { + return CommandOutput.empty(); + } else if (out.isEmpty()) { + // This branch is unreachable because it is impossible to make it save stderr without saving stdout. + // If streams are configured for saving and stdout is discarded, + // its saved contents will be an Optional instance wrapping an empty content, not an empty Optional. + throw ExceptionBox.reachedUnreachable(); + } else if (err.isEmpty()) { + return new CommandOutput<>(out, Integer.MAX_VALUE, interleaved); + } else { + final var combined = out.get().append(err.get()); + return new CommandOutput<>(Optional.of(combined), out.orElseThrow().size(), interleaved); + } + } + + private static PrintStream nullPrintStream() { + return new PrintStream(OutputStream.nullOutputStream()); + } + + private sealed interface Content { + T data(); + int size(); + Content slice(int from, int to); + Content append(Content other); + } + + private record StringListContent(List data) implements Content> { + StringListContent { + Objects.requireNonNull(data); + } + + @Override + public int size() { + return data.size(); + } + + @Override + public StringListContent slice(int from, int to) { + return new StringListContent(data.subList(from, to)); + } + + @Override + public StringListContent append(Content> other) { + return new StringListContent(Stream.of(data, other.data()).flatMap(List::stream).toList()); + } + } + + private record ByteContent(byte[] data) implements Content { + ByteContent { + Objects.requireNonNull(data); + } + + @Override + public int size() { + return data.length; + } + + @Override + public ByteContent slice(int from, int to) { + return new ByteContent(Arrays.copyOfRange(data, from, to)); + } + + @Override + public ByteContent append(Content other) { + byte[] combined = new byte[size() + other.size()]; + System.arraycopy(data, 0, combined, 0, data.length); + System.arraycopy(other.data(), 0, combined, data.length, other.size()); + return new ByteContent(combined); + } + } + + private record OutputStreamsControl(OutputControl stdout, OutputControl stderr) { + OutputStreamsControl { + Objects.requireNonNull(stdout); + Objects.requireNonNull(stderr); + } + + OutputStreamsControl() { + this(new OutputControl(), new OutputControl()); + } + + OutputStreamsControl copy() { + return new OutputStreamsControl(stdout.copy(), stderr.copy()); + } + + List descriptionTokens() { + final List tokens = new ArrayList<>(); + if (stdout.save()) { // Save flags are the same for stdout and stderr, checking stdout is sufficient. + streamsLabel("save ", true).ifPresent(tokens::add); + } + if (stdout.dump() || stderr.dump()) { + streamsLabel("echo ", true).ifPresent(tokens::add); + } + streamsLabel("discard ", false).ifPresent(tokens::add); + if (tokens.isEmpty()) { + // Unreachable because there is always at least one token in the description. + throw ExceptionBox.reachedUnreachable(); + } else { + return tokens; + } + } + + private Optional streamsLabel(String prefix, boolean negate) { + Objects.requireNonNull(prefix); + final var str = Stream.of(stdoutLabel(negate), stderrLabel(negate)) + .filter(Optional::isPresent) + .map(Optional::orElseThrow) + .collect(joining("+")); + if (str.isEmpty()) { + return Optional.empty(); + } else { + return Optional.of(prefix + str); + } + } + + private Optional stdoutLabel(boolean negate) { + if ((stdout.discard() && !negate) || (!stdout.discard() && negate)) { + return Optional.of("out"); + } else { + return Optional.empty(); + } + } + + private Optional stderrLabel(boolean negate) { + if ((stderr.discard() && !negate) || (!stderr.discard() && negate)) { + return Optional.of("err"); + } else { + return Optional.empty(); + } + } + } + + private record CachingPrintStream(PrintStream ps, Optional buf) { + CachingPrintStream { + Objects.requireNonNull(ps); + Objects.requireNonNull(buf); + } + + Optional bufferContents() { + return buf.map(ByteArrayOutputStream::toString); + } + + static Builder build(Charset charset) { + return new Builder(charset); + } + + static final class Builder { + + private Builder(Charset charset) { + this.charset = Objects.requireNonNull(charset); + } + + Builder save(boolean v) { + save = v; + return this; + } + + Builder discard(boolean v) { + discard = v; + return this; + } + + Builder dumpStream(PrintStream v) { + dumpStream = v; + return this; + } + + Builder buffer(ByteArrayOutputStream v) { + externalBuffer = v; + return this; + } + + CachingPrintStream create() { + final Optional buf; + if (save && !discard) { + buf = Optional.ofNullable(externalBuffer).or(() -> { + return Optional.of(new ByteArrayOutputStream()); + }); + } else { + buf = Optional.empty(); + } + + final PrintStream ps; + if (buf.isPresent() && dumpStream != null) { + ps = new PrintStream(new TeeOutputStream(List.of(buf.get(), dumpStream)), true, dumpStream.charset()); + } else if (!discard) { + ps = buf.map(in -> { + return new PrintStream(in, false, charset); + }).or(() -> { + return Optional.ofNullable(dumpStream); + }).orElseGet(CommandOutputControl::nullPrintStream); + } else { + ps = nullPrintStream(); + } + + return new CachingPrintStream(ps, buf); + } + + private boolean save; + private boolean discard; + private PrintStream dumpStream; + private ByteArrayOutputStream externalBuffer; + private final Charset charset; + } + } + + private final class CachingStreamsConfig { + + CachingStreamsConfig() { + out = outputStreamsControl.stdout().buildCachingPrintStream(dumpStdout(), charset()).create(); + if (isRedirectStderr()) { + var builder = outputStreamsControl.stderr().buildCachingPrintStream(dumpStdout(), charset()); + out.buf().ifPresent(builder::buffer); + err = builder.create(); + } else { + err = outputStreamsControl.stderr().buildCachingPrintStream(dumpStderr(), charset()).create(); + } + } + + Result createResult(Optional exitCode, ExecutableAttributes execAttrs) throws IOException { + + CommandOutput> output; + CommandOutput byteOutput; + + CachingPrintStream effectiveOut; + if (out.buf().isEmpty() && isRedirectStderr()) { + effectiveOut = new CachingPrintStream(nullPrintStream(), err.buf()); + } else { + effectiveOut = out; + } + + if (isBinaryOutput()) { + Optional outContent, errContent; + if (isRedirectStderr()) { + outContent = readBinary(outputStreamsControl.stdout(), effectiveOut).map(ByteContent::new); + errContent = Optional.empty(); + } else { + outContent = readBinary(outputStreamsControl.stdout(), out).map(ByteContent::new); + errContent = readBinary(outputStreamsControl.stderr(), err).map(ByteContent::new); + } + + byteOutput = combine(outContent, errContent, redirectRetainedStderr()); + output = null; + } else { + Optional outContent, errContent; + if (isRedirectStderr()) { + outContent = read(outputStreamsControl.stdout(), effectiveOut).map(StringListContent::new); + errContent = Optional.empty(); + } else { + outContent = read(outputStreamsControl.stdout(), out).map(StringListContent::new); + errContent = read(outputStreamsControl.stderr(), err).map(StringListContent::new); + } + + output = combine(outContent, errContent, redirectRetainedStderr()); + byteOutput = null; + } + + return new Result(exitCode, Optional.ofNullable(output), Optional.ofNullable(byteOutput), execAttrs); + } + + PrintStream out() { + return out.ps(); + } + + PrintStream err() { + return err.ps(); + } + + private final CachingPrintStream out; + private final CachingPrintStream err; + } + + private static final class OutputControl { + + OutputControl() { + } + + private OutputControl(OutputControl other) { + dump = other.dump; + discard = other.discard; + save = other.save; + } + + boolean save() { + return save.isPresent(); + } + + boolean saveAll() { + return save.orElse(null) == OutputControlOption.SAVE_ALL; + } + + boolean saveFirstLine() { + return save.orElse(null) == OutputControlOption.SAVE_FIRST_LINE; + } + + boolean discard() { + return discard || (!dump && save.isEmpty()); + } + + boolean dump() { + return !discard && dump; + } + + OutputControl dump(boolean v) { + this.dump = v; + return this; + } + + OutputControl discard(boolean v) { + this.discard = v; + return this; + } + + OutputControl saveAll(boolean v) { + if (v) { + save = Optional.of(OutputControlOption.SAVE_ALL); + } else { + save = Optional.empty(); + } + return this; + } + + OutputControl saveFirstLine(boolean v) { + if (v) { + save = Optional.of(OutputControlOption.SAVE_FIRST_LINE); + } else { + save = Optional.empty(); + } + return this; + } + + OutputControl set(boolean set, OutputControlOption v) { + switch (v) { + case DUMP -> dump(set); + case SAVE_ALL -> saveAll(set); + case SAVE_FIRST_LINE -> saveFirstLine(set); + } + return this; + } + + OutputControl copy() { + return new OutputControl(this); + } + + ProcessBuilder.Redirect asProcessBuilderRedirect() { + if (discard()) { + return ProcessBuilder.Redirect.DISCARD; + } else if (dump && !save()) { + return ProcessBuilder.Redirect.INHERIT; + } else { + return ProcessBuilder.Redirect.PIPE; + } + } + + CachingPrintStream.Builder buildCachingPrintStream(PrintStream dumpStream, Charset charset) { + Objects.requireNonNull(dumpStream); + final var builder = CachingPrintStream.build(charset).save(save()).discard(discard()); + if (dump()) { + builder.dumpStream(dumpStream); + } + return builder; + } + + private boolean dump; + private boolean discard; + private Optional save = Optional.empty(); + } + + private record CommandOutput(Optional> content, int stdoutContentSize, boolean interleaved) { + + CommandOutput { + Objects.requireNonNull(content); + if (interleaved) { + stdoutContentSize = content.map(Content::size).orElse(-1); + } + } + + CommandOutput() { + this(Optional.empty(), 0, false); + } + + Optional combined() { + return content.map(Content::data); + } + + /** + * Returns non-empty {@code Optional} if stdout is available and stdout and stderr are not interleaved. + * @return stdout if it can be extracted from the combined output + */ + Optional stdout() { + if (withoutExtractableStdout()) { + return Optional.empty(); + } + + final var theContent = content.orElseThrow(); + if (stdoutContentSize == theContent.size()) { + return combined(); + } else { + return Optional.of(theContent.slice(0, Integer.min(stdoutContentSize, theContent.size())).data()); + } + } + + /** + * Returns non-empty {@code Optional} if stderr is available and stdout and stderr are not interleaved. + * @return stderr if it can be extracted from the combined output + */ + Optional stderr() { + if (withoutExtractableStderr()) { + return Optional.empty(); + } else if (stdoutContentSize <= 0) { + return combined(); + } else { + final var theContent = content.orElseThrow(); + return Optional.of(theContent.slice(stdoutContentSize, theContent.size()).data()); + } + } + + @SuppressWarnings("unchecked") + static CommandOutput empty() { + return (CommandOutput)EMPTY; + } + + private boolean withoutExtractableStdout() { + return interleaved || content.isEmpty() || stdoutContentSize < 0; + } + + private boolean withoutExtractableStderr() { + return interleaved || content.isEmpty() || stdoutContentSize > content.get().size(); + } + + private static final CommandOutput EMPTY = new CommandOutput<>(); + } + + private record ToolProviderExecutable(ToolProvider tp, List args, CommandOutputControl coc) implements Executable { + + ToolProviderExecutable { + Objects.requireNonNull(tp); + Objects.requireNonNull(args); + Objects.requireNonNull(coc); + } + + @Override + public Result execute() throws IOException, InterruptedException { + return coc.execute(tp, -1, args.toArray(String[]::new)); + } + + @Override + public Result execute(long timeout, TimeUnit unit) throws IOException, InterruptedException { + return coc.execute(tp, unit.toMillis(timeout), args.toArray(String[]::new)); + } + + @Override + public ExecutableAttributes attributes() { + return new ToolProviderAttributes(tp.name(), args); + } + } + + private record ProcessExecutable(ProcessBuilder pb, CommandOutputControl coc) implements Executable { + + ProcessExecutable { + Objects.requireNonNull(pb); + Objects.requireNonNull(coc); + } + + @Override + public Result execute() throws IOException, InterruptedException { + return coc.execute(pb, -1L); + } + + @Override + public Result execute(long timeout, TimeUnit unit) throws IOException, InterruptedException { + return coc.execute(pb, unit.toMillis(timeout)); + } + + @Override + public ExecutableAttributes attributes() { + return new ProcessAttributes(Optional.empty(), pb.command()); + } + } + + private static Optional getPID(Process p) { + try { + return Optional.of(p.pid()); + } catch (UnsupportedOperationException ex) { + return Optional.empty(); + } + } + + private static void suppressIOException(ThrowingRunnable r) { + try { + r.run(); + } catch (IOException ex) {} + } + + private static void suppressIOException(ThrowingConsumer c, T value) { + suppressIOException(() -> { + c.accept(value); + }); + } + + private int flags; + private final OutputStreamsControl outputStreamsControl; + private PrintStream dumpStdout; + private PrintStream dumpStderr; + private Charset charset; + private Consumer processListener; + + // Executor to run subprocess output stream gobblers. + // Output stream gobblers should start fetching output streams ASAP after the process starts. + // No pooling, no waiting. + // CompletableFuture#runAsync() method starts an output stream gobbler. + // If used with the default executor, it is known to make WiX3 light.exe create + // a locked msi file when multiple jpackage tool providers are executed asynchronously. + // The AsyncTest fails with cryptic java.nio.file.FileSystemException error: + // jtreg_open_test_jdk_tools_jpackage_share_AsyncTest_java\\tmp\\jdk.jpackage8108811639097525318\\msi\\Foo-1.0.msi: The process cannot access the file because it is being used by another process. + // The remedy for the problem is to use non-pooling executor to run subprocess output stream gobblers. + private final java.util.concurrent.Executor gobblerExecutor = Executors.newVirtualThreadPerTaskExecutor(); + + private enum OutputControlOption { + SAVE_ALL, SAVE_FIRST_LINE, DUMP + } + + private enum Flag { + DUMP (0x01), + REDIRECT_STDERR (0x02), + BINARY_OUTPUT (0x04), + STORE_OUTPUT_IN_FILES (0x08), + DISCARD_STDOUT (0x10), + DISCARD_STDERR (0x20), + ; + + Flag(int value) { + this.value = value; + } + + int set(int flags, boolean set) { + if (set) { + return flags | value; + } else { + return flags & ~value; + } + } + + boolean isSet(int flags) { + return (flags & value) != 0; + } + + private final int value; + } +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Enquoter.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/Enquoter.java similarity index 77% rename from src/jdk.jpackage/share/classes/jdk/jpackage/internal/Enquoter.java rename to src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/Enquoter.java index 51f97ad2cd6..d9ededcbadb 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/Enquoter.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/Enquoter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, 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 @@ -22,7 +22,7 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -package jdk.jpackage.internal; +package jdk.jpackage.internal.util; import java.util.Optional; import java.util.function.BiConsumer; @@ -32,39 +32,43 @@ import java.util.regex.Pattern; /** * Add quotes to the given string in a configurable way. */ -final class Enquoter { +public final class Enquoter { private Enquoter() { setQuoteChar('"'); } - static Enquoter forPropertyValues() { + public static Enquoter identity() { + return new Enquoter(); + } + + public static Enquoter forPropertyValues() { return new Enquoter() .setEnquotePredicate(QUOTE_IF_WHITESPACES) .setEscaper(PREPEND_BACKSLASH); } - static Enquoter forShellLiterals() { + public static Enquoter forShellLiterals() { return forShellLiterals('\''); } - static Enquoter forShellLiterals(char quoteChar) { + public static Enquoter forShellLiterals(char quoteChar) { return new Enquoter() .setQuoteChar(quoteChar) .setEnquotePredicate(x -> true) .setEscaper(PREPEND_BACKSLASH); } - String applyTo(String v) { + public String applyTo(String v) { if (!needQuotes.test(v)) { return v; } else { var buf = new StringBuilder(); buf.appendCodePoint(beginQuoteChr); - Optional.of(escaper).ifPresentOrElse(op -> { + Optional.ofNullable(escaper).ifPresentOrElse(op -> { v.codePoints().forEachOrdered(chr -> { if (chr == beginQuoteChr || chr == endQuoteChr) { - escaper.accept(chr, buf); + op.accept(chr, buf); } else { buf.appendCodePoint(chr); } @@ -77,28 +81,23 @@ final class Enquoter { } } - Enquoter setQuoteChar(char chr) { + public Enquoter setQuoteChar(char chr) { beginQuoteChr = chr; endQuoteChr = chr; return this; } - Enquoter setEscaper(BiConsumer v) { + public Enquoter setEscaper(BiConsumer v) { escaper = v; return this; } - Enquoter setEnquotePredicate(Predicate v) { + public Enquoter setEnquotePredicate(Predicate v) { needQuotes = v; return this; } - private int beginQuoteChr; - private int endQuoteChr; - private BiConsumer escaper; - private Predicate needQuotes = str -> false; - - private static final Predicate QUOTE_IF_WHITESPACES = new Predicate() { + public static final Predicate QUOTE_IF_WHITESPACES = new Predicate() { @Override public boolean test(String t) { return pattern.matcher(t).find(); @@ -106,8 +105,13 @@ final class Enquoter { private final Pattern pattern = Pattern.compile("\\s"); }; - private static final BiConsumer PREPEND_BACKSLASH = (chr, buf) -> { + public static final BiConsumer PREPEND_BACKSLASH = (chr, buf) -> { buf.append('\\'); buf.appendCodePoint(chr); }; + + private int beginQuoteChr; + private int endQuoteChr; + private BiConsumer escaper; + private Predicate needQuotes = str -> false; } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PListReader.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PListReader.java index 2c693939dab..4c85358d424 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PListReader.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PListReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -35,7 +35,6 @@ import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; @@ -311,7 +310,7 @@ public final class PListReader { } } - public PListReader(byte[] xmlData) throws ParserConfigurationException, SAXException, IOException { + public PListReader(byte[] xmlData) throws SAXException, IOException { this(XmlUtils.initDocumentBuilder().parse(new ByteArrayInputStream(xmlData))); } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/RetryExecutor.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/RetryExecutor.java new file mode 100644 index 00000000000..c67373e8233 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/RetryExecutor.java @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2020, 2026, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ +package jdk.jpackage.internal.util; + +import static jdk.jpackage.internal.util.function.ThrowingConsumer.toConsumer; + +import java.time.Duration; +import java.util.Iterator; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Function; +import jdk.jpackage.internal.util.function.ExceptionBox; +import jdk.jpackage.internal.util.function.ThrowingFunction; +import jdk.jpackage.internal.util.function.ThrowingSupplier; + +public class RetryExecutor { + + public RetryExecutor(Class exceptionType) { + this.exceptionType = Objects.requireNonNull(exceptionType); + setMaxAttemptsCount(5); + setAttemptTimeout(2, TimeUnit.SECONDS); + } + + final public Class exceptionType() { + return exceptionType; + } + + public RetryExecutor setExecutable(ThrowingFunction>, T, E> v) { + executable = v; + return this; + } + + final public RetryExecutor setExecutable(ThrowingSupplier v) { + if (v != null) { + setExecutable(_ -> { + return v.get(); + }); + } else { + executable = null; + } + return this; + } + + public RetryExecutor setMaxAttemptsCount(int v) { + attempts = v; + return this; + } + + final public RetryExecutor setAttemptTimeout(long v, TimeUnit unit) { + return setAttemptTimeout(Duration.of(v, unit.toChronoUnit())); + } + + public RetryExecutor setAttemptTimeout(Duration v) { + timeout = v; + return this; + } + + public RetryExecutor setExceptionMapper(Function v) { + toUnchecked = v; + return this; + } + + public RetryExecutor setSleepFunction(Consumer v) { + sleepFunction = v; + return this; + } + + final public RetryExecutor mutate(Consumer> mutator) { + mutator.accept(this); + return this; + } + + public T execute() throws E { + var curExecutable = executable(); + T result = null; + var attemptIter = new DefaultContext(); + while (attemptIter.hasNext()) { + attemptIter.next(); + try { + result = curExecutable.apply(attemptIter); + break; + } catch (Exception ex) { + if (!exceptionType.isInstance(ex)) { + throw ExceptionBox.toUnchecked(ex); + } else if (attemptIter.isLastAttempt()) { + // No more attempts left. This is fatal. + throw exceptionType.cast(ex); + } else { + curExecutable = executable(); + } + } + + sleep(); + } + + return result; + } + + final public T executeUnchecked() { + try { + return execute(); + } catch (Error | RuntimeException t) { + throw t; + } catch (Exception ex) { + if (exceptionType.isInstance(ex)) { + throw Optional.ofNullable(toUnchecked).orElse(ExceptionBox::toUnchecked).apply(exceptionType.cast(ex)); + } else { + // Unreachable unless it is a direct subclass of Throwable, + // which is not Error or Exception which should not happen. + throw ExceptionBox.reachedUnreachable(); + } + } + } + + public interface Context { + boolean isLastAttempt(); + int attempt(); + T executor(); + } + + private final class DefaultContext implements Context>, Iterator { + + @Override + public boolean isLastAttempt() { + return !hasNext(); + } + + @Override + public int attempt() { + return attempt; + } + + @Override + public boolean hasNext() { + return (attempts - attempt) > 1; + } + + @Override + public Void next() { + attempt++; + return null; + } + + @Override + public RetryExecutor executor() { + return RetryExecutor.this; + } + + private int attempt = -1; + } + + private ThrowingFunction>, T, E> executable() { + return Optional.ofNullable(executable).orElseThrow(() -> { + return new IllegalStateException("No executable"); + }); + } + + private void sleep() { + Optional.ofNullable(timeout).ifPresent(Optional.ofNullable(sleepFunction).orElseGet(() -> { + return toConsumer(Thread::sleep); + })); + } + + private final Class exceptionType; + private ThrowingFunction>, T, E> executable; + private int attempts; + private Duration timeout; + private Function toUnchecked; + private Consumer sleepFunction; +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/TeeOutputStream.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/TeeOutputStream.java new file mode 100644 index 00000000000..db098eb2b48 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/TeeOutputStream.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2026, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ +package jdk.jpackage.internal.util; + +import java.io.Closeable; +import java.io.Flushable; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Objects; +import jdk.jpackage.internal.util.function.ThrowingConsumer; + +public final class TeeOutputStream extends OutputStream { + + public TeeOutputStream(Iterable items) { + items.forEach(Objects::requireNonNull); + this.items = items; + } + + @Override + public void write(int b) throws IOException { + for (final var item : items) { + item.write(b); + } + } + + @Override + public void write(byte[] b) throws IOException { + for (final var item : items) { + item.write(b); + } + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + for (final var item : items) { + item.write(b, off, len); + } + } + + @Override + public void flush() throws IOException { + forEach(Flushable::flush); + } + + @Override + public void close() throws IOException { + forEach(Closeable::close); + } + + private void forEach(ThrowingConsumer c) throws IOException { + IOException firstEx = null; + for (final var item : items) { + try { + c.accept(item); + } catch (IOException e) { + if (firstEx == null) { + firstEx = e; + } + } + } + if (firstEx != null) { + throw firstEx; + } + } + + private final Iterable items; +} diff --git a/src/jdk.jpackage/unix/classes/jdk/jpackage/internal/UnixLaunchersAsServices.java b/src/jdk.jpackage/unix/classes/jdk/jpackage/internal/UnixLaunchersAsServices.java index e1e02ba7850..b196a5805a0 100644 --- a/src/jdk.jpackage/unix/classes/jdk/jpackage/internal/UnixLaunchersAsServices.java +++ b/src/jdk.jpackage/unix/classes/jdk/jpackage/internal/UnixLaunchersAsServices.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, 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,6 @@ */ package jdk.jpackage.internal; -import jdk.jpackage.internal.model.Launcher; -import jdk.jpackage.internal.model.Application; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; @@ -36,6 +34,9 @@ import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; +import jdk.jpackage.internal.model.Application; +import jdk.jpackage.internal.model.Launcher; +import jdk.jpackage.internal.util.Enquoter; /** * Helper to install launchers as services for Unix installers. diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinBundlingEnvironment.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinBundlingEnvironment.java index dc9891f154a..de52a222d7d 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinBundlingEnvironment.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinBundlingEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -31,16 +31,17 @@ import static jdk.jpackage.internal.cli.StandardBundlingOperation.CREATE_WIN_EXE import static jdk.jpackage.internal.cli.StandardBundlingOperation.CREATE_WIN_MSI; import jdk.jpackage.internal.cli.Options; -import jdk.jpackage.internal.util.Result; public class WinBundlingEnvironment extends DefaultBundlingEnvironment { public WinBundlingEnvironment() { - super(build() - .defaultOperation(CREATE_WIN_EXE) - .bundler(CREATE_WIN_APP_IMAGE, WinBundlingEnvironment::createAppImage) - .bundler(CREATE_WIN_EXE, LazyLoad::sysEnv, WinBundlingEnvironment::createExePackage) - .bundler(CREATE_WIN_MSI, LazyLoad::sysEnv, WinBundlingEnvironment::createMsiPackage)); + super(build().mutate(builder -> { + var sysEnv = runOnce(WinSystemEnvironment::create); + + builder + .bundler(CREATE_WIN_EXE, sysEnv, WinBundlingEnvironment::createExePackage) + .bundler(CREATE_WIN_MSI, sysEnv, WinBundlingEnvironment::createMsiPackage); + }).defaultOperation(CREATE_WIN_EXE).bundler(CREATE_WIN_APP_IMAGE, WinBundlingEnvironment::createAppImage)); } private static void createMsiPackage(Options options, WinSystemEnvironment sysEnv) { @@ -98,12 +99,4 @@ public class WinBundlingEnvironment extends DefaultBundlingEnvironment { } } - private static final class LazyLoad { - - static Result sysEnv() { - return SYS_ENV; - } - - private static final Result SYS_ENV = WinSystemEnvironment.create(); - } } diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixTool.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixTool.java index e2ed175fbf3..c4f8610312a 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixTool.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixTool.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ -233,10 +233,10 @@ public enum WixTool { // Detect FIPS mode var fips = false; try { - final var exec = Executor.of(toolPath.toString(), "-?").setQuiet(true).saveOutput(true); - final var exitCode = exec.execute(); + final var result = Executor.of(toolPath.toString(), "-?").setQuiet(true).saveOutput(true).execute(); + final var exitCode = result.getExitCode(); if (exitCode != 0 /* 308 */) { - final var output = exec.getOutput(); + final var output = result.getOutput(); if (!output.isEmpty() && output.get(0).contains("error CNDL0308")) { fips = true; } diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlPage.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlPage.java index d8fd13fdd7c..af28135e673 100644 --- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlPage.java +++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlPage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, 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,19 +23,50 @@ package jdk.test.failurehandler; +import java.io.FileWriter; +import java.io.IOException; import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Objects; public class HtmlPage implements AutoCloseable { + static final String STYLE_SHEET_FILENAME = "failure-handler-style.css"; + static final String SCRIPT_FILENAME = "failure-handler-script.js"; + private final PrintWriter writer; private final HtmlSection rootSection; - public HtmlPage(PrintWriter writer) { - Objects.requireNonNull(writer, "writer cannot be null"); - this.writer = writer; + /** + * Constructs a {@code HtmlPage} + * + * @param dir The directory into which the HTML file and related resources will be created + * @param htmlFileName The HTML file name + * @param append if {@code true} then the content will be appended to the file represented + * by the {@code htmlFileName}, else the {@code htmlFileName} will be overwritten + * with the new content + * @throws IllegalArgumentException if {@code dir} is not a directory or if the + * {@code htmlFileName} is {@linkplain String#isBlank() blank} + * @throws IOException if there is an error constructing file resource(s) for this HTML page + */ + public HtmlPage(final Path dir, final String htmlFileName, final boolean append) + throws IOException { + Objects.requireNonNull(dir, "directory cannot be null"); + Objects.requireNonNull(htmlFileName, "HTML file name cannot be null"); + if (!Files.isDirectory(dir)) { + throw new IllegalArgumentException(dir + " is not a directory"); + } + if (htmlFileName.isBlank()) { + throw new IllegalArgumentException("HTML file name cannot be blank"); + } + final FileWriter fileWriter = new FileWriter(dir.resolve(htmlFileName).toFile(), append); + this.writer = new PrintWriter(fileWriter, true); + createScriptFile(dir); + createStyleSheetFile(dir); rootSection = new HtmlSection(writer); } + @Override public void close() { writer.close(); @@ -44,4 +75,71 @@ public class HtmlPage implements AutoCloseable { public HtmlSection getRootSection() { return rootSection; } + + private static void createStyleSheetFile(final Path destDir) throws IOException { + final Path styleSheet = destDir.resolve(STYLE_SHEET_FILENAME); + if (Files.exists(styleSheet)) { + return; + } + final String content = """ + div { display:none;} + """; + Files.writeString(styleSheet, content); + } + + private static void createScriptFile(final Path destDir) throws IOException { + final Path script = destDir.resolve(SCRIPT_FILENAME); + if (Files.exists(script)) { + return; + } + final String content = """ + function doShow(e) { + while (e != null) { + if (e.tagName == 'DIV') { + e.style.display = 'block'; + } + e = e.parentNode; + } + } + + function showHandler(event) { + elementId = this.dataset.show; + elementToShow = document.getElementById(elementId); + doShow(elementToShow); + } + + function toggleHandler(event) { + toggleElementId = this.dataset.toggle; + elementToToggle = document.getElementById(toggleElementId); + d = elementToToggle.style.display; + if (d == 'block') { + elementToToggle.style.display = 'none'; + } else { + doShow(elementToToggle); + } + } + + function bodyLoadHandler() { + const index = location.href.indexOf("#"); + if (index != -1) { + doShow(document.getElementById(location.href.substring(index + 1))); + } + // elements that require the "toggleHandler" function to be registered + // as an event handler for the onclick event + const requiringToggleHandler = document.querySelectorAll("[data-toggle]"); + for (const e of requiringToggleHandler) { + e.addEventListener("click", toggleHandler); + } + // elements that require the "showHandler" function to be registered + // as an event handler for the onclick event + const requiringShowHandler = document.querySelectorAll("[data-show]"); + for (const e of requiringShowHandler) { + e.addEventListener("click", showHandler); + } + } + // register a onload event handler + window.addEventListener("DOMContentLoaded", bodyLoadHandler); + """; + Files.writeString(script, content); + } } diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlSection.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlSection.java index 141caf450bd..53ffab95a1e 100644 --- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlSection.java +++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlSection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, 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 @@ -57,41 +57,15 @@ public class HtmlSection { if (rootSection == null) { this.rootSection = this; this.pw.println(""); - this.pw.println("\n" - + "\n" - + "\n" - + ""); - this.pw.println(""); + this.pw.println(""); + this.pw.println( + ""); + this.pw.println( + ""); + this.pw.println(""); + + this.pw.println(""); } else { this.rootSection = rootSection; this.pw.print("

    "); @@ -146,7 +120,7 @@ public class HtmlSection { } else if (child != null) { path = String.format("%s.%s", path, child); } - pw.printf("%2$s%n", + pw.printf("%2$s%n", path, name); } @@ -188,7 +162,7 @@ public class HtmlSection { : String.format("%s.%s", parent.id, name), name, rootSection); this.parent = parent; - pw.printf("
  • %2$s
    ",
    +            pw.printf("
  • %2$s
    ",
                         id, name);
             }
     
    diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java
    index 96c5f4f2858..e63e55888d7 100644
    --- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java
    +++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2015, 2026, 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
    @@ -105,9 +105,7 @@ public class GatherDiagnosticInfoObserver implements Harness.Observer {
     
         private void gatherCoreInfo(Path workDir, String name, Path core, PrintWriter log,
                                    CoreInfoGatherer gatherer) {
    -        File output = workDir.resolve(CORES_OUTPUT).toFile();
    -        try (HtmlPage html = new HtmlPage(new PrintWriter(
    -                new FileWriter(output, true), true))) {
    +        try (HtmlPage html = new HtmlPage(workDir, CORES_OUTPUT, true)) {
                 try (ElapsedTimePrinter timePrinter
                              = new ElapsedTimePrinter(new Stopwatch(), name, log)) {
                     gatherer.gatherCoreInfo(html.getRootSection(), core);
    @@ -121,9 +119,7 @@ public class GatherDiagnosticInfoObserver implements Harness.Observer {
     
         private void gatherEnvInfo(Path workDir, String name, PrintWriter log,
                                    EnvironmentInfoGatherer gatherer) {
    -        File output = workDir.resolve(ENVIRONMENT_OUTPUT).toFile();
    -        try (HtmlPage html = new HtmlPage(new PrintWriter(
    -                new FileWriter(output, true), true))) {
    +        try (HtmlPage html = new HtmlPage(workDir, ENVIRONMENT_OUTPUT, true)) {
                 try (ElapsedTimePrinter timePrinter
                              = new ElapsedTimePrinter(new Stopwatch(), name, log)) {
                     gatherer.gatherEnvironmentInfo(html.getRootSection());
    diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherProcessInfoTimeoutHandler.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherProcessInfoTimeoutHandler.java
    index 63ed7e5f2c7..c1f1ddfb69f 100644
    --- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherProcessInfoTimeoutHandler.java
    +++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherProcessInfoTimeoutHandler.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2015, 2026, 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
    @@ -69,16 +69,7 @@ public class GatherProcessInfoTimeoutHandler extends TimeoutHandler {
             }
             try {
                 actionsLog.printf("%s ---%n", name);
    -
    -            File output = workDir.resolve(OUTPUT_FILENAME).toFile();
    -            try {
    -                PrintWriter pw = new PrintWriter(new FileWriter(output, true), true);
    -                runGatherer(name, workDir, actionsLog, pw, pid);
    -            } catch (IOException e) {
    -                actionsLog.printf("IOException: cannot open output file[%s] : %s",
    -                        output, e.getMessage());
    -                e.printStackTrace(actionsLog);
    -            }
    +            runGatherer(name, actionsLog, pid);
             } finally {
                 actionsLog.printf("--- %s%n", name);
                 // don't close jtreg log
    @@ -90,9 +81,9 @@ public class GatherProcessInfoTimeoutHandler extends TimeoutHandler {
             }
         }
     
    -    private void runGatherer(String name, Path workDir, PrintWriter log,
    -                             PrintWriter out, long pid) {
    -        try (HtmlPage html = new HtmlPage(out)) {
    +    private void runGatherer(String name, PrintWriter log, long pid) {
    +        Path workDir = outputDir.toPath();
    +        try (HtmlPage html = new HtmlPage(workDir, OUTPUT_FILENAME, true)) {
                 ProcessInfoGatherer gatherer = new GathererFactory(
                         OS.current().family,
                         workDir, log, testJdk.toPath()).getProcessInfoGatherer();
    diff --git a/test/hotspot/gtest/cds/test_archiveWorkers.cpp b/test/hotspot/gtest/cds/test_archiveWorkers.cpp
    index 55c3528f0c2..87e55b80b94 100644
    --- a/test/hotspot/gtest/cds/test_archiveWorkers.cpp
    +++ b/test/hotspot/gtest/cds/test_archiveWorkers.cpp
    @@ -1,4 +1,5 @@
     /*
    + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved.
      * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
    @@ -23,20 +24,21 @@
      */
     
     #include "cds/archiveUtils.hpp"
    +#include "runtime/atomic.hpp"
     #include "unittest.hpp"
     
     class TestArchiveWorkerTask : public ArchiveWorkerTask {
     private:
    -  volatile int _sum;
    -  int _max;
    +  Atomic _sum;
    +  Atomic _max;
     public:
       TestArchiveWorkerTask() : ArchiveWorkerTask("Test"), _sum(0), _max(0) {}
       void work(int chunk, int max_chunks) override {
    -    AtomicAccess::add(&_sum, chunk);
    -    AtomicAccess::store(&_max, max_chunks);
    +    _sum.add_then_fetch(chunk);
    +    _max.store_relaxed(max_chunks);
       }
    -  int sum() { return AtomicAccess::load(&_sum); }
    -  int max() { return AtomicAccess::load(&_max); }
    +  int sum() { return _sum.load_relaxed(); }
    +  int max() { return _max.load_relaxed(); }
     };
     
     // Test a repeated cycle of workers init/shutdown without task works.
    diff --git a/test/hotspot/gtest/gc/g1/test_g1BatchedGangTask.cpp b/test/hotspot/gtest/gc/g1/test_g1BatchedGangTask.cpp
    index 902406eaf65..08df547585a 100644
    --- a/test/hotspot/gtest/gc/g1/test_g1BatchedGangTask.cpp
    +++ b/test/hotspot/gtest/gc/g1/test_g1BatchedGangTask.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2021, 2026, 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
    @@ -22,9 +22,10 @@
      *
      */
     
    +#include "cppstdlib/new.hpp"
     #include "gc/g1/g1BatchedTask.hpp"
     #include "gc/shared/workerThread.hpp"
    -#include "runtime/atomicAccess.hpp"
    +#include "runtime/atomic.hpp"
     #include "unittest.hpp"
     
     class G1BatchedTaskWorkers : AllStatic {
    @@ -49,26 +50,26 @@ WorkerThreads* G1BatchedTaskWorkers::_workers = nullptr;
     
     class G1TestSubTask : public G1AbstractSubTask {
       mutable uint _phase;
    -  volatile uint _num_do_work; // Amount of do_work() has been called.
    +  Atomic _num_do_work; // Amount of do_work() has been called.
     
       void check_and_inc_phase(uint expected) const {
         ASSERT_EQ(_phase, expected);
         _phase++;
       }
     
    -  bool volatile* _do_work_called_by;
    +  Atomic* _do_work_called_by;
     
     protected:
       uint _max_workers;
     
       void do_work_called(uint worker_id) {
    -    AtomicAccess::inc(&_num_do_work);
    -    bool orig_value = AtomicAccess::cmpxchg(&_do_work_called_by[worker_id], false, true);
    +    _num_do_work.add_then_fetch(1u);
    +    bool orig_value = _do_work_called_by[worker_id].compare_exchange(false, true);
         ASSERT_EQ(orig_value, false);
       }
     
       void verify_do_work_called_by(uint num_workers) {
    -    ASSERT_EQ(AtomicAccess::load(&_num_do_work), num_workers);
    +    ASSERT_EQ(_num_do_work.load_relaxed(), num_workers);
         // Do not need to check the _do_work_called_by array. The count is already verified
         // by above statement, and we already check that a given flag is only set once.
       }
    @@ -86,7 +87,7 @@ public:
     
       ~G1TestSubTask() {
         check_and_inc_phase(3);
    -    FREE_C_HEAP_ARRAY(bool, _do_work_called_by);
    +    FREE_C_HEAP_ARRAY(Atomic, _do_work_called_by);
       }
     
       double worker_cost() const override {
    @@ -100,9 +101,9 @@ public:
         assert(max_workers >= 1, "must be");
         check_and_inc_phase(2);
     
    -    _do_work_called_by = NEW_C_HEAP_ARRAY(bool, max_workers, mtInternal);
    +    _do_work_called_by = NEW_C_HEAP_ARRAY(Atomic, max_workers, mtInternal);
         for (uint i = 0; i < max_workers; i++) {
    -      _do_work_called_by[i] = false;
    +      ::new (&_do_work_called_by[i]) Atomic{false};
         }
         _max_workers = max_workers;
       }
    diff --git a/test/hotspot/gtest/gc/g1/test_g1CardSet.cpp b/test/hotspot/gtest/gc/g1/test_g1CardSet.cpp
    index 70a70dc069f..c2de96bea4f 100644
    --- a/test/hotspot/gtest/gc/g1/test_g1CardSet.cpp
    +++ b/test/hotspot/gtest/gc/g1/test_g1CardSet.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2021, 2026, 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 @@
     #include "gc/shared/workerThread.hpp"
     #include "logging/log.hpp"
     #include "memory/allocation.hpp"
    +#include "runtime/atomic.hpp"
     #include "unittest.hpp"
     #include "utilities/powerOfTwo.hpp"
     
    @@ -385,8 +386,8 @@ void G1CardSetTest::cardset_basic_test() {
     class G1CardSetMtTestTask : public WorkerTask {
       G1CardSet* _card_set;
     
    -  size_t _added;
    -  size_t _found;
    +  Atomic _added;
    +  Atomic _found;
     
     public:
       G1CardSetMtTestTask(G1CardSet* card_set) :
    @@ -413,12 +414,12 @@ public:
             found++;
           }
         }
    -    AtomicAccess::add(&_added, added);
    -    AtomicAccess::add(&_found, found);
    +    _added.add_then_fetch(added);
    +    _found.add_then_fetch(found);
       }
     
    -  size_t added() const { return _added; }
    -  size_t found() const { return _found; }
    +  size_t added() const { return _added.load_relaxed(); }
    +  size_t found() const { return _found.load_relaxed(); }
     };
     
     void G1CardSetTest::cardset_mt_test() {
    diff --git a/test/hotspot/gtest/gc/g1/test_stressCommitUncommit.cpp b/test/hotspot/gtest/gc/g1/test_stressCommitUncommit.cpp
    index 6b3e9fd50bc..ce6a4f8819e 100644
    --- a/test/hotspot/gtest/gc/g1/test_stressCommitUncommit.cpp
    +++ b/test/hotspot/gtest/gc/g1/test_stressCommitUncommit.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2020, 2026, 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,7 +26,7 @@
     #include "gc/g1/g1RegionToSpaceMapper.hpp"
     #include "gc/shared/workerThread.hpp"
     #include "memory/memoryReserver.hpp"
    -#include "runtime/atomicAccess.hpp"
    +#include "runtime/atomic.hpp"
     #include "runtime/os.hpp"
     #include "unittest.hpp"
     
    @@ -51,7 +51,7 @@ WorkerThreads* G1MapperWorkers::_workers = nullptr;
     
     class G1TestCommitUncommit : public WorkerTask {
       G1RegionToSpaceMapper* _mapper;
    -  uint _claim_id;
    +  Atomic _claim_id;
     public:
       G1TestCommitUncommit(G1RegionToSpaceMapper* mapper) :
           WorkerTask("Stress mapper"),
    @@ -59,7 +59,7 @@ public:
           _claim_id(0) { }
     
       void work(uint worker_id) {
    -    uint index = AtomicAccess::fetch_then_add(&_claim_id, 1u);
    +    uint index = _claim_id.fetch_then_add(1u);
     
         for (int i = 0; i < 100000; i++) {
           // Stress commit and uncommit of a single region. The same
    diff --git a/test/hotspot/gtest/gc/shared/test_bufferNodeAllocator.cpp b/test/hotspot/gtest/gc/shared/test_bufferNodeAllocator.cpp
    index ec72ce404e3..edcea03d696 100644
    --- a/test/hotspot/gtest/gc/shared/test_bufferNodeAllocator.cpp
    +++ b/test/hotspot/gtest/gc/shared/test_bufferNodeAllocator.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2018, 2026, 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,7 +24,7 @@
     
     #include "gc/shared/bufferNode.hpp"
     #include "memory/allocation.hpp"
    -#include "runtime/atomicAccess.hpp"
    +#include "runtime/atomic.hpp"
     #include "runtime/interfaceSupport.inline.hpp"
     #include "runtime/semaphore.inline.hpp"
     #include "runtime/thread.hpp"
    @@ -116,16 +116,16 @@ public:
     class BufferNode::TestSupport::AllocatorThread : public JavaTestThread {
       BufferNode::Allocator* _allocator;
       CompletedList* _cbl;
    -  volatile size_t* _total_allocations;
    -  volatile bool* _continue_running;
    +  Atomic* _total_allocations;
    +  Atomic* _continue_running;
       size_t _allocations;
     
     public:
       AllocatorThread(Semaphore* post,
                       BufferNode::Allocator* allocator,
                       CompletedList* cbl,
    -                  volatile size_t* total_allocations,
    -                  volatile bool* continue_running) :
    +                  Atomic* total_allocations,
    +                  Atomic* continue_running) :
         JavaTestThread(post),
         _allocator(allocator),
         _cbl(cbl),
    @@ -135,14 +135,14 @@ public:
       {}
     
       virtual void main_run() {
    -    while (AtomicAccess::load_acquire(_continue_running)) {
    +    while (_continue_running->load_acquire()) {
           BufferNode* node = _allocator->allocate();
           _cbl->push(node);
           ++_allocations;
           ThreadBlockInVM tbiv(this); // Safepoint check.
         }
         tty->print_cr("allocations: %zu", _allocations);
    -    AtomicAccess::add(_total_allocations, _allocations);
    +    _total_allocations->add_then_fetch(_allocations);
       }
     };
     
    @@ -151,13 +151,13 @@ public:
     class BufferNode::TestSupport::ProcessorThread : public JavaTestThread {
       BufferNode::Allocator* _allocator;
       CompletedList* _cbl;
    -  volatile bool* _continue_running;
    +  Atomic* _continue_running;
     
     public:
       ProcessorThread(Semaphore* post,
                       BufferNode::Allocator* allocator,
                       CompletedList* cbl,
    -                  volatile bool* continue_running) :
    +                  Atomic* continue_running) :
         JavaTestThread(post),
         _allocator(allocator),
         _cbl(cbl),
    @@ -172,7 +172,7 @@ public:
             _allocator->release(node);
           } else if (shutdown_requested) {
             return;
    -      } else if (!AtomicAccess::load_acquire(_continue_running)) {
    +      } else if (!_continue_running->load_acquire()) {
             // To avoid a race that could leave buffers in the list after this
             // thread has shut down, continue processing until the list is empty
             // *after* the shut down request has been received.
    @@ -193,9 +193,9 @@ static void run_test(BufferNode::Allocator* allocator, CompletedList* cbl) {
       constexpr uint milliseconds_to_run = 1000;
     
       Semaphore post;
    -  volatile size_t total_allocations = 0;
    -  volatile bool allocator_running = true;
    -  volatile bool processor_running = true;
    +  Atomic total_allocations{0};
    +  Atomic allocator_running{true};
    +  Atomic processor_running{true};
     
       ProcessorThread* proc_threads[num_processor_threads] = {};
       for (uint i = 0; i < num_processor_threads; ++i) {
    @@ -222,18 +222,18 @@ static void run_test(BufferNode::Allocator* allocator, CompletedList* cbl) {
         ThreadInVMfromNative invm(this_thread);
         this_thread->sleep(milliseconds_to_run);
       }
    -  AtomicAccess::release_store(&allocator_running, false);
    +  allocator_running.release_store(false);
       for (uint i = 0; i < num_allocator_threads; ++i) {
         ThreadInVMfromNative invm(this_thread);
         post.wait_with_safepoint_check(this_thread);
       }
    -  AtomicAccess::release_store(&processor_running, false);
    +  processor_running.release_store(false);
       for (uint i = 0; i < num_processor_threads; ++i) {
         ThreadInVMfromNative invm(this_thread);
         post.wait_with_safepoint_check(this_thread);
       }
       ASSERT_TRUE(BufferNode::TestSupport::try_transfer_pending(allocator));
    -  tty->print_cr("total allocations: %zu", total_allocations);
    +  tty->print_cr("total allocations: %zu", total_allocations.load_relaxed());
       tty->print_cr("allocator free count: %zu", allocator->free_count());
     }
     
    diff --git a/test/hotspot/gtest/gtestMain.cpp b/test/hotspot/gtest/gtestMain.cpp
    index 842b6547b48..a1869ab5499 100644
    --- a/test/hotspot/gtest/gtestMain.cpp
    +++ b/test/hotspot/gtest/gtestMain.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2016, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2016, 2026, 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
    @@ -22,6 +22,7 @@
      *
      */
     
    +#include "cppstdlib/cstdlib.hpp"
     #include "jni.h"
     #include "runtime/os.hpp"
     #include "runtime/thread.inline.hpp"
    @@ -31,7 +32,6 @@
     
     #include 
     #include 
    -#include 
     #ifdef __APPLE__
     #include 
     #endif
    diff --git a/test/hotspot/gtest/oops/test_compressedKlass.cpp b/test/hotspot/gtest/oops/test_compressedKlass.cpp
    index c2ae7719776..dcdb335adb5 100644
    --- a/test/hotspot/gtest/oops/test_compressedKlass.cpp
    +++ b/test/hotspot/gtest/oops/test_compressedKlass.cpp
    @@ -1,6 +1,6 @@
     /*
      * Copyright (c) 2024, 2025, Red Hat, Inc. All rights reserved.
    - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2024, 2026, 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,6 @@ TEST_VM(CompressedKlass, basics) {
       if (!UseCompressedClassPointers) {
         return;
       }
    -  ASSERT_LE((address)0, CompressedKlassPointers::base());
       ASSERT_LE(CompressedKlassPointers::base(), CompressedKlassPointers::klass_range_start());
       ASSERT_LT(CompressedKlassPointers::klass_range_start(), CompressedKlassPointers::klass_range_end());
       ASSERT_LE(CompressedKlassPointers::klass_range_end(), CompressedKlassPointers::encoding_range_end());
    @@ -50,7 +49,7 @@ TEST_VM(CompressedKlass, basics) {
         ASSERT_EQ(CompressedKlassPointers::encoding_range_end() - CompressedKlassPointers::base(), (ptrdiff_t)expected_size);
       }
     #else
    -  ASSERT_EQ(CompressedKlassPointers::base(), (address)0);
    +  ASSERT_EQ(CompressedKlassPointers::base(), nullptr);
       ASSERT_EQ(CompressedKlassPointers::encoding_range_end(), (address)(UINT_MAX));
     #endif // _LP64
     }
    diff --git a/test/hotspot/gtest/runtime/test_atomic.cpp b/test/hotspot/gtest/runtime/test_atomic.cpp
    index b37c14d41a7..753dde0ca57 100644
    --- a/test/hotspot/gtest/runtime/test_atomic.cpp
    +++ b/test/hotspot/gtest/runtime/test_atomic.cpp
    @@ -162,6 +162,35 @@ TEST_VM(AtomicIntegerTest, cmpxchg_int64) {
       Support().test();
     }
     
    +template
    +struct AtomicIntegerCmpsetTestSupport {
    +  Atomic _test_value;
    +
    +  AtomicIntegerCmpsetTestSupport() : _test_value{} {}
    +
    +  void test() {
    +    T zero = 0;
    +    T five = 5;
    +    T ten = 10;
    +    _test_value.store_relaxed(zero);
    +    EXPECT_FALSE(_test_value.compare_set(five, ten));
    +    EXPECT_EQ(zero, _test_value.load_relaxed());
    +    EXPECT_TRUE(_test_value.compare_set(zero, ten));
    +    EXPECT_EQ(ten, _test_value.load_relaxed());
    +  }
    +};
    +
    +TEST_VM(AtomicIntegerTest, cmpset_int32) {
    +  using Support = AtomicIntegerCmpsetTestSupport;
    +  Support().test();
    +}
    +
    +TEST_VM(AtomicIntegerTest, cmpset_int64) {
    +  // Check if 64-bit atomics are available on the machine.
    +  using Support = AtomicIntegerCmpsetTestSupport;
    +  Support().test();
    +}
    +
     struct AtomicXchgAndCmpxchg1ByteStressSupport {
       char _default_val;
       int  _base;
    diff --git a/test/hotspot/gtest/unittest.hpp b/test/hotspot/gtest/unittest.hpp
    index 336a2f0766e..6a2cd400cb6 100644
    --- a/test/hotspot/gtest/unittest.hpp
    +++ b/test/hotspot/gtest/unittest.hpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2016, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2016, 2026, 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,9 @@
     #ifndef UNITTEST_HPP
     #define UNITTEST_HPP
     
    +#include "cppstdlib/cstdlib.hpp"
     #include "utilities/globalDefinitions.hpp"
     
    -#include 
     #include 
     
     #define GTEST_DONT_DEFINE_TEST 1
    diff --git a/test/hotspot/gtest/utilities/test_bitMap_setops.cpp b/test/hotspot/gtest/utilities/test_bitMap_setops.cpp
    index 2b1e67533df..1def9c89cfc 100644
    --- a/test/hotspot/gtest/utilities/test_bitMap_setops.cpp
    +++ b/test/hotspot/gtest/utilities/test_bitMap_setops.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2016, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2016, 2026, 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,6 +21,7 @@
      * questions.
      */
     
    +#include "cppstdlib/cstdlib.hpp"
     #include "runtime/os.hpp"
     #include "utilities/align.hpp"
     #include "utilities/bitMap.inline.hpp"
    @@ -29,8 +30,6 @@
     #include "utilities/globalDefinitions.hpp"
     #include "unittest.hpp"
     
    -#include 
    -
     typedef BitMap::idx_t idx_t;
     typedef BitMap::bm_word_t bm_word_t;
     
    diff --git a/test/hotspot/gtest/utilities/test_concurrentHashtable.cpp b/test/hotspot/gtest/utilities/test_concurrentHashtable.cpp
    index 775f0e17409..77055e92256 100644
    --- a/test/hotspot/gtest/utilities/test_concurrentHashtable.cpp
    +++ b/test/hotspot/gtest/utilities/test_concurrentHashtable.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2018, 2026, 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
    @@ -22,6 +22,7 @@
      */
     
     #include "gc/shared/workerThread.hpp"
    +#include "runtime/atomic.hpp"
     #include "runtime/mutex.hpp"
     #include "runtime/os.hpp"
     #include "runtime/semaphore.hpp"
    @@ -1169,12 +1170,12 @@ TEST_VM(ConcurrentHashTable, concurrent_mt_bulk_delete) {
     class CHTParallelScanTask: public WorkerTask {
       TestTable* _cht;
       TestTable::ScanTask* _scan_task;
    -  size_t *_total_scanned;
    +  Atomic* _total_scanned;
     
     public:
       CHTParallelScanTask(TestTable* cht,
                           TestTable::ScanTask* bc,
    -                      size_t *total_scanned) :
    +                      Atomic* total_scanned) :
         WorkerTask("CHT Parallel Scan"),
         _cht(cht),
         _scan_task(bc),
    @@ -1184,7 +1185,7 @@ public:
       void work(uint worker_id) {
         ChtCountScan par_scan;
         _scan_task->do_safepoint_scan(par_scan);
    -    AtomicAccess::add(_total_scanned, par_scan._count);
    +    _total_scanned->add_then_fetch(par_scan._count);
       }
     };
     
    @@ -1217,13 +1218,14 @@ public:
       {}
     
       void doit() {
    -    size_t total_scanned = 0;
    +    Atomic total_scanned{0};
         TestTable::ScanTask scan_task(_cht, 64);
     
         CHTParallelScanTask task(_cht, &scan_task, &total_scanned);
         CHTWorkers::run_task(&task);
     
    -     EXPECT_TRUE(total_scanned == (size_t)_num_items) << " Should scan all inserted items: " << total_scanned;
    +    EXPECT_TRUE(total_scanned.load_relaxed() == (size_t)_num_items)
    +        << " Should scan all inserted items: " << total_scanned.load_relaxed();
       }
     };
     
    diff --git a/test/hotspot/gtest/utilities/test_globalCounter_nested.cpp b/test/hotspot/gtest/utilities/test_globalCounter_nested.cpp
    index f5cd67d39f0..d7a824deed3 100644
    --- a/test/hotspot/gtest/utilities/test_globalCounter_nested.cpp
    +++ b/test/hotspot/gtest/utilities/test_globalCounter_nested.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2018, 2026, 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,7 +21,7 @@
      * questions.
      */
     
    -#include "runtime/atomicAccess.hpp"
    +#include "runtime/atomic.hpp"
     #include "runtime/os.hpp"
     #include "utilities/globalCounter.inline.hpp"
     #include "utilities/spinYield.hpp"
    @@ -39,8 +39,8 @@ enum NestedTestState {
     };
     
     class RCUNestedThread : public JavaTestThread {
    -  volatile NestedTestState _state;
    -  volatile bool _proceed;
    +  Atomic _state;
    +  Atomic _proceed;
     
     protected:
       RCUNestedThread(Semaphore* post) :
    @@ -52,21 +52,21 @@ protected:
       ~RCUNestedThread() {}
     
       void set_state(NestedTestState new_state) {
    -    AtomicAccess::release_store(&_state, new_state);
    +    _state.release_store(new_state);
       }
     
       void wait_with_state(NestedTestState new_state) {
         SpinYield spinner;
    -    AtomicAccess::release_store(&_state, new_state);
    -    while (!AtomicAccess::load_acquire(&_proceed)) {
    +    _state.release_store(new_state);
    +    while (!_proceed.load_acquire()) {
           spinner.wait();
         }
    -    AtomicAccess::release_store(&_proceed, false);
    +    _proceed.release_store(false);
       }
     
     public:
       NestedTestState state() const {
    -    return AtomicAccess::load_acquire(&_state);
    +    return _state.load_acquire();
       }
     
       void wait_for_state(NestedTestState goal) {
    @@ -77,7 +77,7 @@ public:
       }
     
       void proceed() {
    -    AtomicAccess::release_store(&_proceed, true);
    +    _proceed.release_store(true);
       }
     };
     
    diff --git a/test/hotspot/gtest/utilities/test_singleWriterSynchronizer.cpp b/test/hotspot/gtest/utilities/test_singleWriterSynchronizer.cpp
    index 323908ebd12..744001f0867 100644
    --- a/test/hotspot/gtest/utilities/test_singleWriterSynchronizer.cpp
    +++ b/test/hotspot/gtest/utilities/test_singleWriterSynchronizer.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2018, 2026, 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
    @@ -22,7 +22,7 @@
      *
      */
     
    -#include "runtime/atomicAccess.hpp"
    +#include "runtime/atomic.hpp"
     #include "runtime/interfaceSupport.inline.hpp"
     #include "runtime/os.hpp"
     #include "runtime/thread.hpp"
    @@ -36,16 +36,16 @@
     
     class SingleWriterSynchronizerTestReader : public JavaTestThread {
       SingleWriterSynchronizer* _synchronizer;
    -  volatile uintx* _synchronized_value;
    -  volatile int* _continue_running;
    +  Atomic* _synchronized_value;
    +  Atomic* _continue_running;
     
       static const uint reader_iterations = 10;
     
     public:
       SingleWriterSynchronizerTestReader(Semaphore* post,
                                          SingleWriterSynchronizer* synchronizer,
    -                                     volatile uintx* synchronized_value,
    -                                     volatile int* continue_running) :
    +                                     Atomic* synchronized_value,
    +                                     Atomic* continue_running) :
         JavaTestThread(post),
         _synchronizer(synchronizer),
         _synchronized_value(synchronized_value),
    @@ -55,14 +55,14 @@ public:
       virtual void main_run() {
         size_t iterations = 0;
         size_t values_changed = 0;
    -    while (AtomicAccess::load_acquire(_continue_running) != 0) {
    +    while (_continue_running->load_acquire() != 0) {
           { ThreadBlockInVM tbiv(this); } // Safepoint check outside critical section.
           ++iterations;
           SingleWriterSynchronizer::CriticalSection cs(_synchronizer);
    -      uintx value = AtomicAccess::load_acquire(_synchronized_value);
    +      uintx value = _synchronized_value->load_acquire();
           uintx new_value = value;
           for (uint i = 0; i < reader_iterations; ++i) {
    -        new_value = AtomicAccess::load_acquire(_synchronized_value);
    +        new_value = _synchronized_value->load_acquire();
             // A reader can see either the value it first read after
             // entering the critical section, or that value + 1.  No other
             // values are possible.
    @@ -81,14 +81,14 @@ public:
     
     class SingleWriterSynchronizerTestWriter : public JavaTestThread {
       SingleWriterSynchronizer* _synchronizer;
    -  volatile uintx* _synchronized_value;
    -  volatile int* _continue_running;
    +  Atomic* _synchronized_value;
    +  Atomic* _continue_running;
     
     public:
       SingleWriterSynchronizerTestWriter(Semaphore* post,
                                          SingleWriterSynchronizer* synchronizer,
    -                                     volatile uintx* synchronized_value,
    -                                     volatile int* continue_running) :
    +                                     Atomic* synchronized_value,
    +                                     Atomic* continue_running) :
         JavaTestThread(post),
         _synchronizer(synchronizer),
         _synchronized_value(synchronized_value),
    @@ -96,12 +96,12 @@ public:
       {}
     
       virtual void main_run() {
    -    while (AtomicAccess::load_acquire(_continue_running) != 0) {
    -      ++*_synchronized_value;
    +    while (_continue_running->load_acquire() != 0) {
    +      _synchronized_value->add_then_fetch(1u, memory_order_relaxed);
           _synchronizer->synchronize();
           { ThreadBlockInVM tbiv(this); } // Safepoint check.
         }
    -    tty->print_cr("writer iterations: %zu", *_synchronized_value);
    +    tty->print_cr("writer iterations: %zu", _synchronized_value->load_relaxed());
       }
     };
     
    @@ -111,8 +111,8 @@ const uint milliseconds_to_run = 1000;
     TEST_VM(TestSingleWriterSynchronizer, stress) {
       Semaphore post;
       SingleWriterSynchronizer synchronizer;
    -  volatile uintx synchronized_value = 0;
    -  volatile int continue_running = 1;
    +  Atomic synchronized_value{0};
    +  Atomic continue_running{1};
     
       JavaTestThread* readers[nreaders] = {};
       for (uint i = 0; i < nreaders; ++i) {
    @@ -137,7 +137,7 @@ TEST_VM(TestSingleWriterSynchronizer, stress) {
         ThreadInVMfromNative invm(cur);
         cur->sleep(milliseconds_to_run);
       }
    -  continue_running = 0;
    +  continue_running.store_relaxed(0);
       for (uint i = 0; i < nreaders + 1; ++i) {
         post.wait();
       }
    diff --git a/test/hotspot/gtest/utilities/test_waitBarrier.cpp b/test/hotspot/gtest/utilities/test_waitBarrier.cpp
    index 0b4a9bd8d2e..b2e42348a74 100644
    --- a/test/hotspot/gtest/utilities/test_waitBarrier.cpp
    +++ b/test/hotspot/gtest/utilities/test_waitBarrier.cpp
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2019, 2026, 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,23 @@
      * questions.
      */
     
    -#include "runtime/atomicAccess.hpp"
    +#include "runtime/atomic.hpp"
     #include "runtime/orderAccess.hpp"
     #include "runtime/os.hpp"
     #include "utilities/spinYield.hpp"
     #include "utilities/waitBarrier.hpp"
     #include "threadHelper.inline.hpp"
     
    -static volatile int wait_tag = 0;
    -static volatile int valid_value = 0;
    +static Atomic wait_tag{0};
    +static Atomic valid_value{0};
     
     template 
     class WBThread : public JavaTestThread {
     public:
    -  static volatile bool _exit;
    +  static Atomic _exit;
       WaitBarrierType* _wait_barrier;
       Semaphore* _wrt_start;
    -  volatile int _on_barrier;
    +  Atomic _on_barrier;
     
       WBThread(Semaphore* post, WaitBarrierType* wb, Semaphore* wrt_start)
         : JavaTestThread(post), _wait_barrier(wb), _wrt_start(wrt_start) {};
    @@ -46,12 +46,12 @@ public:
         _wrt_start->signal();
         int vv, tag;
         // Similar to how a JavaThread would stop in a safepoint.
    -    while (!_exit) {
    +    while (!_exit.load_relaxed()) {
           // Load the published tag.
    -      tag = AtomicAccess::load_acquire(&wait_tag);
    +      tag = wait_tag.load_acquire();
           // Publish the tag this thread is going to wait for.
    -      AtomicAccess::release_store(&_on_barrier, tag);
    -      if (_on_barrier == 0) {
    +      _on_barrier.release_store(tag);
    +      if (_on_barrier.load_relaxed() == 0) {
             SpinPause();
             continue;
           }
    @@ -59,15 +59,15 @@ public:
           // Wait until we are woken.
           _wait_barrier->wait(tag);
           // Verify that we do not see an invalid value.
    -      vv = AtomicAccess::load_acquire(&valid_value);
    +      vv = valid_value.load_acquire();
           ASSERT_EQ((vv & 0x1), 0);
    -      AtomicAccess::release_store(&_on_barrier, 0);
    +      _on_barrier.release_store(0);
         }
       }
     };
     
     template 
    -volatile bool WBThread::_exit = false;
    +Atomic WBThread::_exit{false};
     
     template 
     class WBArmerThread : public JavaTestThread {
    @@ -103,35 +103,35 @@ public:
           // Arm next tag.
           wb.arm(next_tag);
           // Publish tag.
    -      AtomicAccess::release_store_fence(&wait_tag, next_tag);
    +      wait_tag.release_store_fence(next_tag);
     
           // Wait until threads picked up new tag.
    -      while (reader1->_on_barrier != wait_tag ||
    -             reader2->_on_barrier != wait_tag ||
    -             reader3->_on_barrier != wait_tag ||
    -             reader4->_on_barrier != wait_tag) {
    +      while (reader1->_on_barrier.load_relaxed() != wait_tag.load_relaxed() ||
    +             reader2->_on_barrier.load_relaxed() != wait_tag.load_relaxed() ||
    +             reader3->_on_barrier.load_relaxed() != wait_tag.load_relaxed() ||
    +             reader4->_on_barrier.load_relaxed() != wait_tag.load_relaxed()) {
             SpinPause();
           }
     
           // Set an invalid value.
    -      AtomicAccess::release_store(&valid_value, valid_value + 1); // odd
    +      valid_value.release_store(valid_value.load_relaxed() + 1); // odd
           os::naked_yield();
           // Set a valid value.
    -      AtomicAccess::release_store(&valid_value, valid_value + 1); // even
    +      valid_value.release_store(valid_value.load_relaxed() + 1); // even
           // Publish inactive tag.
    -      AtomicAccess::release_store_fence(&wait_tag, 0); // Stores in WB must not float up.
    +      wait_tag.release_store_fence(0); // Stores in WB must not float up.
           wb.disarm();
     
           // Wait until threads done valid_value verification.
    -      while (reader1->_on_barrier != 0 ||
    -             reader2->_on_barrier != 0 ||
    -             reader3->_on_barrier != 0 ||
    -             reader4->_on_barrier != 0) {
    +      while (reader1->_on_barrier.load_relaxed() != 0 ||
    +             reader2->_on_barrier.load_relaxed() != 0 ||
    +             reader3->_on_barrier.load_relaxed() != 0 ||
    +             reader4->_on_barrier.load_relaxed() != 0) {
             SpinPause();
           }
           ++next_tag;
         }
    -    WBThread::_exit = true;
    +    WBThread::_exit.store_relaxed(true);
         for (int i = 0; i < NUMBER_OF_READERS; i++) {
           post.wait();
         }
    @@ -139,13 +139,13 @@ public:
     };
     
     TEST_VM(WaitBarrier, default_wb) {
    -  WBThread::_exit = false;
    +  WBThread::_exit.store_relaxed(false);
       mt_test_doer >();
     }
     
     #if defined(LINUX)
     TEST_VM(WaitBarrier, generic_wb) {
    -  WBThread::_exit = false;
    +  WBThread::_exit.store_relaxed(false);
       mt_test_doer >();
     }
     #endif
    diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt
    index 4e16e328ab4..13e1ea30a34 100644
    --- a/test/hotspot/jtreg/ProblemList.txt
    +++ b/test/hotspot/jtreg/ProblemList.txt
    @@ -77,8 +77,6 @@ compiler/interpreter/Test6833129.java 8335266 generic-i586
     
     compiler/c2/aarch64/TestStaticCallStub.java 8359963 linux-aarch64,macosx-aarch64
     
    -serviceability/jvmti/NMethodRelocation/NMethodRelocationTest.java 8369150 generic-all
    -
     #############################################################################
     
     # :hotspot_gc
    diff --git a/test/hotspot/jtreg/TEST.groups b/test/hotspot/jtreg/TEST.groups
    index 2288e8f8876..32cff812975 100644
    --- a/test/hotspot/jtreg/TEST.groups
    +++ b/test/hotspot/jtreg/TEST.groups
    @@ -1,5 +1,5 @@
     #
    -# Copyright (c) 2013, 2025, Oracle and/or its affiliates. All rights reserved.
    +# Copyright (c) 2013, 2026, 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
    @@ -132,13 +132,6 @@ tier1_loom_serviceability = \
     hotspot_loom = \
       :tier1_loom
     
    -serviceability_ttf_virtual = \
    -  serviceability/ \
    -  -serviceability/jvmti/vthread \
    -  -serviceability/jvmti/thread  \
    -  -serviceability/jvmti/events  \
    -  -serviceability/jvmti/negative
    -
     tier1_common = \
       sources \
       sanity/BasicVMTest.java \
    diff --git a/test/jdk/java/security/Security/SecurityPropFile/SecurityPropFile.java b/test/hotspot/jtreg/compiler/c1/TestCITimeCountLinearScan.java
    similarity index 59%
    rename from test/jdk/java/security/Security/SecurityPropFile/SecurityPropFile.java
    rename to test/hotspot/jtreg/compiler/c1/TestCITimeCountLinearScan.java
    index b0ba6c60854..e67a3679758 100644
    --- a/test/jdk/java/security/Security/SecurityPropFile/SecurityPropFile.java
    +++ b/test/hotspot/jtreg/compiler/c1/TestCITimeCountLinearScan.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2026, 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,20 +23,15 @@
     
     /*
      * @test
    - * @bug 4303068
    - * @summary be allowed to specify the security properties file
    - *      as a -D system property
    - *
    - * @run main/othervm -Djava.security.properties=${test.src}/SecurityPropFile.file -Djava.security.debug=properties SecurityPropFile
    + * @bug 8374518
    + * @summary Sanity check the flag -XX:+CITime and -XX:+CountLinearScan
    + * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:+CITime -XX:+CountLinearScan ${test.main.class}
      */
     
    -public class SecurityPropFile {
    +package compiler.c1;
    +
    +public class TestCITimeCountLinearScan {
         public static void main(String[] args) {
    -        System.out.println(java.security.Security.getProperty
    -                                ("policy.provider"));
    -        System.out.println(java.security.Security.getProperty
    -                                ("policy.url.1"));
    -        System.out.println(java.security.Security.getProperty
    -                                ("policy.url.2"));
    +        System.out.println("Hello World!");
         }
     }
    diff --git a/test/hotspot/jtreg/compiler/igvn/IntegerDivValueTests.java b/test/hotspot/jtreg/compiler/igvn/IntegerDivValueTests.java
    index 3585d1347ac..2abeffb0c41 100644
    --- a/test/hotspot/jtreg/compiler/igvn/IntegerDivValueTests.java
    +++ b/test/hotspot/jtreg/compiler/igvn/IntegerDivValueTests.java
    @@ -204,7 +204,11 @@ public class IntegerDivValueTests {
     
         @Run(test = {"testIntConstantFolding", "testIntConstantFoldingSpecialCase"})
         public void checkIntConstants(RunInfo info) {
    -        Asserts.assertEquals(INT_CONST_1 / INT_CONST_2, testIntConstantFolding());
    +        if (INT_CONST_2 == 0) {
    +            Asserts.assertThrows(ArithmeticException.class, () -> testIntConstantFolding());
    +        } else {
    +            Asserts.assertEquals(INT_CONST_1 / INT_CONST_2, testIntConstantFolding());
    +        }
             Asserts.assertEquals(Integer.MIN_VALUE, testIntConstantFoldingSpecialCase());
         }
     
    @@ -441,7 +445,11 @@ public class IntegerDivValueTests {
     
         @Run(test = {"testLongConstantFolding", "testLongConstantFoldingSpecialCase"})
         public void checkLongConstants(RunInfo infoLong) {
    -        Asserts.assertEquals(LONG_CONST_1 / LONG_CONST_2, testLongConstantFolding());
    +        if (LONG_CONST_2 == 0L) {
    +            Asserts.assertThrows(ArithmeticException.class, () -> testLongConstantFolding());
    +        } else {
    +            Asserts.assertEquals(LONG_CONST_1 / LONG_CONST_2, testLongConstantFolding());
    +        }
             Asserts.assertEquals(Long.MIN_VALUE, testLongConstantFoldingSpecialCase());
         }
     
    diff --git a/test/hotspot/jtreg/compiler/intrinsics/TestVerifyIntrinsicChecks.java b/test/hotspot/jtreg/compiler/intrinsics/TestVerifyIntrinsicChecks.java
    deleted file mode 100644
    index c482a73affd..00000000000
    --- a/test/hotspot/jtreg/compiler/intrinsics/TestVerifyIntrinsicChecks.java
    +++ /dev/null
    @@ -1,105 +0,0 @@
    -/*
    - * Copyright (c) 2025, 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.
    - */
    -
    -/*
    - * @test
    - * @bug 8361842
    - * @summary Verify the effectiveness of the `VerifyIntrinsicChecks` VM flag
    - *          through (bypassing `StringCoding::encodeAsciiArray`, and) feeding
    - *          invalid input to an intrinsified `StringCoding::encodeAsciiArray0`
    - *          (note the `0` suffix!).
    - * @library /compiler/patches
    - * @library /test/lib
    - * @build java.base/java.lang.Helper
    - * @comment `vm.debug == true` is required since `VerifyIntrinsicChecks` is a
    - *          development flag
    - * @requires vm.debug == true & vm.flavor == "server" & !vm.graal.enabled
    - * @requires (os.arch != "riscv64" | (os.arch == "riscv64" & vm.cpu.features ~= ".*rvv.*"))
    - * @run main/othervm compiler.intrinsics.TestVerifyIntrinsicChecks verify
    - */
    -
    -package compiler.intrinsics;
    -
    -import java.lang.Helper;
    -import java.time.Instant;
    -import jdk.test.lib.process.ProcessTools;
    -import jdk.test.lib.process.OutputAnalyzer;
    -
    -public final class TestVerifyIntrinsicChecks {
    -
    -    public static void main(String[] args) throws Exception {
    -        switch (args[0]) {
    -            case "verify" -> {
    -                log("Starting JVM in a separate process to verify the crash");
    -                OutputAnalyzer outputAnalyzer = ProcessTools.executeTestJava(
    -                        "-Xcomp",
    -                        "-XX:-TieredCompilation",
    -                        "-XX:CompileCommand=inline,java.lang.StringCoding::encodeAsciiArray0",
    -                        "-XX:+VerifyIntrinsicChecks",
    -                        "--patch-module", "java.base=%s/java.base".formatted(System.getProperty("test.patch.path")),
    -                        "compiler.intrinsics.TestVerifyIntrinsicChecks",
    -                        "crash");
    -                outputAnalyzer.shouldContain("unexpected null in intrinsic");
    -                outputAnalyzer.shouldNotHaveExitValue(0);
    -            }
    -            case "crash" -> {
    -                log("Triggering the crash");
    -                warmUpIntrinsicMethod();
    -                violateIntrinsicMethodContract();
    -            }
    -            default -> throw new IllegalArgumentException();
    -        }
    -    }
    -
    -    private static void warmUpIntrinsicMethod() {
    -        log("Warming up the intrinsic method");
    -        char[] sa = createAsciiChars(8192);
    -        byte[] sp = new byte[4096];
    -        for (int i = 0; i < 1_000; i++) {
    -            Helper.StringCodingEncodeAsciiArray0(sa, i, sp, 0, sp.length - i);
    -        }
    -    }
    -
    -    private static char[] createAsciiChars(int length) {
    -        char[] buffer = new char[length];
    -        for (int i = 0; i < length; i++) {
    -            buffer[i] = (char) (i % '\u0080');
    -        }
    -        return buffer;
    -    }
    -
    -    private static void violateIntrinsicMethodContract() {
    -        log("Violating the intrinsic method contract (sa=null)");
    -        Helper.StringCodingEncodeAsciiArray0(null, 1, null, 1, 1);
    -    }
    -
    -    private synchronized static void log(String format, Object... args) {
    -        Object[] extendedArgs = new Object[2 + args.length];
    -        extendedArgs[0] = Instant.now();
    -        extendedArgs[1] = Thread.currentThread().getName();
    -        System.arraycopy(args, 0, extendedArgs, extendedArgs.length - args.length, args.length);
    -        String extendedFormat = "%%s [%%s] %s%%n".formatted(format);
    -        System.out.printf(extendedFormat, extendedArgs);
    -    }
    -
    -}
    diff --git a/test/hotspot/jtreg/compiler/intrinsics/string/TestCountPositives.java b/test/hotspot/jtreg/compiler/intrinsics/string/TestCountPositives.java
    index 1c20a49d281..76ef4766159 100644
    --- a/test/hotspot/jtreg/compiler/intrinsics/string/TestCountPositives.java
    +++ b/test/hotspot/jtreg/compiler/intrinsics/string/TestCountPositives.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2022, 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,6 @@
      * @build java.base/java.lang.Helper
      * @run main compiler.intrinsics.string.TestCountPositives
      */
    -
     /*
      * @test
      * @bug 8281146 8318509
    @@ -47,38 +46,17 @@
      * @run main/othervm/timeout=1200 -XX:UseAVX=3 compiler.intrinsics.string.TestCountPositives
      * @run main/othervm/timeout=1200 -XX:UseAVX=3 -XX:+UnlockDiagnosticVMOptions -XX:AVX3Threshold=0 compiler.intrinsics.string.TestCountPositives
      */
    -
    -/*
    - * @test
    - * @bug 8281146
    - * @summary Verify `StringCoding::countPositives` intrinsic Java wrapper checks
    - *          by enabling the ones in the VM intrinsic using
    - *          `-XX:+VerifyIntrinsicChecks`
    - * @comment This does not check out-of-range conditions. The
    - *          `-XX:+VerifyIntrinsicChecks` version of this test simply ensures
    - *          that the VM intrinsic will produce no spurious errors.
    - * @key randomness
    - * @library /compiler/patches
    - * @library /test/lib
    - * @comment `vm.debug == true` is required since `VerifyIntrinsicChecks` is a
    - *          development flag
    - * @requires vm.debug == true
    - * @build java.base/java.lang.Helper
    - * @run main/othervm
    - *      -XX:+VerifyIntrinsicChecks
    - *      compiler.intrinsics.string.TestCountPositives
    +/**
    + * This test was derived from compiler.intrinsics.string.TestHasNegatives
      */
    -
     package compiler.intrinsics.string;
     
     import java.lang.Helper;
     import java.util.Random;
    +import java.util.stream.IntStream;
     
     import jdk.test.lib.Utils;
     
    -/**
    - * This test was derived from {@link TestHasNegatives}.
    - */
     public class TestCountPositives {
     
         private static byte[] bytes = new byte[4096 + 32];
    diff --git a/test/hotspot/jtreg/compiler/intrinsics/string/TestEncodeIntrinsics.java b/test/hotspot/jtreg/compiler/intrinsics/string/TestEncodeIntrinsics.java
    index bb343b246ff..38a516e7521 100644
    --- a/test/hotspot/jtreg/compiler/intrinsics/string/TestEncodeIntrinsics.java
    +++ b/test/hotspot/jtreg/compiler/intrinsics/string/TestEncodeIntrinsics.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2013, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2013, 2021, 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
    @@ -31,26 +31,6 @@
      * @run main/othervm/timeout=1200 --add-opens=java.base/sun.nio.cs=ALL-UNNAMED -Xbatch -Xmx256m compiler.intrinsics.string.TestEncodeIntrinsics
      */
     
    -/*
    - * @test
    - * @bug 6896617 8274242
    - * @summary Verify `sun.nio.cs.ISO_8859_1.Encoder::encodeISOArray` intrinsic
    - *          Java wrapper checks by enabling the ones in the VM intrinsic using
    - *          `-XX:+VerifyIntrinsicChecks`
    - * @comment This does not check out-of-range conditions. The
    - *          `-XX:+VerifyIntrinsicChecks` version of this test simply ensures
    - *          that the VM intrinsic will produce no spurious errors.
    - * @key randomness
    - * @library /test/lib
    - * @comment `vm.debug == true` is required since `VerifyIntrinsicChecks` is a
    - *          development flag
    - * @requires vm.debug == true
    - * @run main/othervm/timeout=1200
    - *      -XX:+VerifyIntrinsicChecks
    - *      --add-opens=java.base/sun.nio.cs=ALL-UNNAMED -Xbatch -Xmx256m
    - *      compiler.intrinsics.string.TestEncodeIntrinsics
    - */
    -
     package compiler.intrinsics.string;
     
     import jdk.test.lib.Utils;
    diff --git a/test/hotspot/jtreg/compiler/intrinsics/string/TestHasNegatives.java b/test/hotspot/jtreg/compiler/intrinsics/string/TestHasNegatives.java
    index a15f6aade2e..6edf2dc2e56 100644
    --- a/test/hotspot/jtreg/compiler/intrinsics/string/TestHasNegatives.java
    +++ b/test/hotspot/jtreg/compiler/intrinsics/string/TestHasNegatives.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2016, 2025, 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
    @@ -31,7 +31,6 @@
      * @build java.base/java.lang.Helper
      * @run main compiler.intrinsics.string.TestHasNegatives
      */
    -
     /*
      * @test
      * @bug 8054307 8318509
    @@ -47,31 +46,11 @@
      * @run main/othervm/timeout=1200 -XX:UseAVX=3 -XX:+UnlockDiagnosticVMOptions -XX:AVX3Threshold=0 compiler.intrinsics.string.TestHasNegatives
      */
     
    -/*
    - * @test
    - * @bug 8054307
    - * @summary Verify `StringCoding::hasNegatives` intrinsic Java wrapper checks
    - *          by enabling the ones in the VM intrinsic using
    - *          `-XX:+VerifyIntrinsicChecks`
    - * @comment This does not check out-of-range conditions. The
    - *          `-XX:+VerifyIntrinsicChecks` version of this test simply ensures
    - *          that the VM intrinsic will produce no spurious errors.
    - * @key randomness
    - * @library /compiler/patches
    - * @library /test/lib
    - * @comment `vm.debug == true` is required since `VerifyIntrinsicChecks` is a
    - *          development flag
    - * @requires vm.debug == true
    - * @build java.base/java.lang.Helper
    - * @run main/othervm
    - *      -XX:+VerifyIntrinsicChecks
    - *      compiler.intrinsics.string.TestHasNegatives
    - */
    -
     package compiler.intrinsics.string;
     
     import java.lang.Helper;
     import java.util.Random;
    +import java.util.stream.IntStream;
     
     import jdk.test.lib.Utils;
     
    diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestAliasingFuzzer.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestAliasingFuzzer.java
    index 5d20ce659b9..825d5ca60bc 100644
    --- a/test/hotspot/jtreg/compiler/loopopts/superword/TestAliasingFuzzer.java
    +++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestAliasingFuzzer.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2024, 2026, 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
    @@ -1052,35 +1052,20 @@ public class TestAliasingFuzzer {
                         case Aliasing.CONTAINER_DIFFERENT,
                              Aliasing.CONTAINER_SAME_ALIASING_NEVER,
                              Aliasing.CONTAINER_UNKNOWN_ALIASING_NEVER ->
    -                        // We would have liked to check that there is no multiversioning.
    -                        //
    -                        // But sadly there are some cases that have issues with RCE and/or
    -                        // predicates, and so we end up using multiversioning anyway. We
    -                        // should fix those cases eventually, to strengthen the checks here.
    -                        //
    -                        // The array cases are a little more tame, and do not have the same
    -                        // issues as the MemorySegment cases.
    -                        (containerKind == ContainerKind.ARRAY)
    -                        ? """
    -                          // Aliasing check should never fail at runtime, so the predicate
    -                          // should never fail, and we do not have to use multiversioning.
    -                          // Failure could have a few causes:
    -                          // - issues with doing RCE / missing predicates
    -                          //   -> other loop-opts need to be fixed
    -                          // - predicate fails: recompile with multiversioning
    -                          //   -> logic in runtime check may be wrong
    -                          @IR(counts = {".*multiversion.*", "= 0"},
    -                              phase = CompilePhase.PRINT_IDEAL,
    -                              applyIf = {"UseAutoVectorizationPredicate", "true"},
    -                              applyIfPlatform = {"64-bit", "true"},
    -                              applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"})
    -                          """
    -                        : """
    -                          // Due to cases like JDK-8360204 and JDK-8365982, there can be issues
    -                          // with RCE leading cases where we remove predicates and then unroll again
    -                          // and then end up multiversioning. These cases seem relatively rare but
    -                          // prevent us from asserting that there is never multiversioning in these cases.
    -                          """;
    +                            """
    +                            // Aliasing check should never fail at runtime, so the predicate
    +                            // should never fail, and we do not have to use multiversioning.
    +                            // Failure could have a few causes:
    +                            // - issues with doing RCE / missing predicates
    +                            //   -> other loop-opts need to be fixed
    +                            // - predicate fails: recompile with multiversioning
    +                            //   -> logic in runtime check may be wrong
    +                            @IR(counts = {".*multiversion.*", "= 0"},
    +                                phase = CompilePhase.PRINT_IDEAL,
    +                                applyIf = {"UseAutoVectorizationPredicate", "true"},
    +                                applyIfPlatform = {"64-bit", "true"},
    +                                applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"})
    +                            """;
                        case Aliasing.CONTAINER_SAME_ALIASING_UNKNOWN,
                              Aliasing.CONTAINER_UNKNOWN_ALIASING_UNKNOWN ->
                                 """
    diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestLoadSliceWithMultipleMemoryInputStates.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestLoadSliceWithMultipleMemoryInputStates.java
    new file mode 100644
    index 00000000000..7bd85d343cd
    --- /dev/null
    +++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestLoadSliceWithMultipleMemoryInputStates.java
    @@ -0,0 +1,94 @@
    +/*
    + * Copyright (c) 2026, 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.
    + */
    +
    +/*
    + * @test id=all-flags
    + * @summary Test a case where we can have one memory slice that has only loads,
    + *          but the loads from the slice do not have all the same input memory
    + *          state from before the loop. This is rather rare but it can happen.
    + * @bug 8373453
    + * @run main/othervm
    + *      -XX:CompileCommand=compileonly,${test.main.class}::test
    + *      -Xbatch -XX:-TieredCompilation
    + *      ${test.main.class}
    + */
    +
    +/*
    + * @test id=fewer-flags
    + * @bug 8373453
    + * @run main/othervm
    + *      -XX:CompileCommand=compileonly,${test.main.class}::test
    + *      ${test.main.class}
    + */
    +
    +/*
    + * @test id=vanilla
    + * @bug 8373453
    + * @run main ${test.main.class}
    + */
    +
    +package compiler.loopopts.superword;
    +
    +public class TestLoadSliceWithMultipleMemoryInputStates {
    +    static void test() {
    +        // The relevant slice is the value field of the Byte Objects.
    +        Byte x = 1;
    +
    +        for (int i = 0; i < 2; i++) {
    +            if ((i & 1) == 0) {
    +                // Not sure what this loop is needed for, but it is very sensitive,
    +                // I cannot even replace N with 32.
    +                int N = 32;
    +                for (int j = 0; j < N; j++) {
    +                    if (j == 1) {
    +                        x = (byte) x;
    +                    }
    +                }
    +
    +                for (int j = 0; j < 32; j++) {
    +                    // The call below has an effect on the memory state
    +                    // If we optimize the Load for Byte::value, we can bypass
    +                    // this call, since we know that Byte::value cannot be
    +                    // modified during the call.
    +                    Object o = 1;
    +                    o.toString();
    +
    +                    for (int k = 0; k < 32; k++) { // OSR around here
    +                        // Loads of x byte field have different memory input states
    +                        // This is because some loads can split their memory state
    +                        // through a phi further up, and others are not put back on
    +                        // the IGVN worklist and are thus not optimized and keep
    +                        // the old memory state. Both are correct though.
    +                        x = (byte) (x + 1);
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    public static void main(String[] args) {
    +        for (int i = 0; i < 10_000; i++) {
    +            test();
    +        }
    +    }
    +}
    diff --git a/test/hotspot/jtreg/compiler/patches/java.base/java/lang/Helper.java b/test/hotspot/jtreg/compiler/patches/java.base/java/lang/Helper.java
    index 3985ad8ea90..e6c8b68fc6f 100644
    --- a/test/hotspot/jtreg/compiler/patches/java.base/java/lang/Helper.java
    +++ b/test/hotspot/jtreg/compiler/patches/java.base/java/lang/Helper.java
    @@ -39,11 +39,6 @@ public class Helper {
             return StringCoding.countPositives(ba, off, len);
         }
     
    -    @jdk.internal.vm.annotation.ForceInline
    -    public static int StringCodingEncodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len) {
    -        return StringCoding.encodeAsciiArray0(sa, sp, da, dp, len);
    -    }
    -
         @jdk.internal.vm.annotation.ForceInline
         public static byte[] compressByte(byte[] src, int srcOff, int dstSize, int dstOff, int len) {
             byte[] dst = new byte[dstSize];
    diff --git a/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java b/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java
    index 26a49aba7bf..53c1b89a203 100644
    --- a/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java
    +++ b/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2025, 2026, 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
    @@ -479,6 +479,32 @@ public class TestSubwordTruncation {
             return new Object[] { in, res };
         }
     
    +    @Test
    +    @IR(counts = { IRNode.CAST_II, ">0" })
    +    @Warmup(0)
    +    public Object[] testCastII() {
    +        byte[] bytes = new byte[400];
    +        intField = 6;
    +        int i = 0;
    +        int j = 1;
    +
    +        do {
    +            bytes[j] = (byte) i;
    +            int k = 1;
    +
    +            do {
    +                i <<= intField;
    +                i += (k ^ i);
    +                i -= j;
    +
    +                for (int u = 1; 1 > u; u++) {
    +                }
    +            } while (++k < 8);
    +        } while (++j < 191);
    +
    +        return new Object[] { bytes };
    +    }
    +
         public static void main(String[] args) {
             TestFramework.run();
         }
    diff --git a/test/hotspot/jtreg/containers/docker/ShareTmpDir.java b/test/hotspot/jtreg/containers/docker/ShareTmpDir.java
    index b7f807d76a3..986cd044737 100644
    --- a/test/hotspot/jtreg/containers/docker/ShareTmpDir.java
    +++ b/test/hotspot/jtreg/containers/docker/ShareTmpDir.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2022, 2026, 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
    @@ -66,31 +66,45 @@ public class ShareTmpDir {
         private static void test() throws Exception {
             File sharedtmpdir = new File("sharedtmpdir");
             File flag = new File(sharedtmpdir, "flag");
    -        File started = new File(sharedtmpdir, "started");
    +        File started1 = new File(sharedtmpdir, "started-1");
    +        File started2 = new File(sharedtmpdir, "started-2");
             sharedtmpdir.mkdir();
             flag.delete();
    -        started.delete();
    +        started1.delete();
    +        started2.delete();
             DockerRunOptions opts = new DockerRunOptions(imageName, "/jdk/bin/java", "WaitForFlagFile");
    +        Object lock = new Object();
             opts.addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/");
             opts.addDockerOpts("--volume", sharedtmpdir.getAbsolutePath() + ":/tmp/");
             opts.addJavaOpts("-Xlog:os+container=trace", "-Xlog:perf+memops=debug", "-cp", "/test-classes/");
     
             Thread t1 = new Thread() {
                     public void run() {
    +                    synchronized(lock) {
    +                        opts.addClassOptions("1");
    +                    }
                         try { out1 = Common.run(opts); } catch (Exception e) { e.printStackTrace(); }
                     }
                 };
             t1.start();
     
    +        while (!started1.exists()) {
    +            System.out.println("Waiting for first JVM to start");
    +            Thread.sleep(1000);
    +        }
    +
             Thread t2 = new Thread() {
                     public void run() {
    +                    synchronized(lock) {
    +                        opts.addClassOptions("2");
    +                    }
                         try { out2 = Common.run(opts); } catch (Exception e) { e.printStackTrace(); }
                     }
                 };
             t2.start();
     
    -        while (!started.exists()) {
    -            System.out.println("Wait for at least one JVM to start");
    +        while (!started2.exists()) {
    +            System.out.println("Waiting for second JVM to start");
                 Thread.sleep(1000);
             }
     
    diff --git a/test/hotspot/jtreg/containers/docker/WaitForFlagFile.java b/test/hotspot/jtreg/containers/docker/WaitForFlagFile.java
    index 64596830a3f..ed549e33cf1 100644
    --- a/test/hotspot/jtreg/containers/docker/WaitForFlagFile.java
    +++ b/test/hotspot/jtreg/containers/docker/WaitForFlagFile.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2022, 2025, 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
    @@ -28,7 +28,7 @@ public class WaitForFlagFile {
         public static void main(String[] args) throws Exception {
             System.out.println("WaitForFlagFile: Entering");
     
    -        File started = new File("/tmp/started");
    +        File started = new File("/tmp/started-" + args.length);
             FileOutputStream fout = new FileOutputStream(started);
             fout.close();
     
    diff --git a/test/hotspot/jtreg/gc/epsilon/TestInitAllocs.java b/test/hotspot/jtreg/gc/epsilon/TestInitAllocs.java
    new file mode 100644
    index 00000000000..353daaef8b6
    --- /dev/null
    +++ b/test/hotspot/jtreg/gc/epsilon/TestInitAllocs.java
    @@ -0,0 +1,76 @@
    +/*
    + * Copyright Amazon.com Inc. 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.
    + */
    +
    +package gc.epsilon;
    +
    +/**
    + * @test TestInitAllocs
    + * @requires vm.gc.Epsilon
    + * @summary Test that allocation path taken in early JVM phases works
    + *
    + * @run main/othervm -Xmx256m
    + *                   -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC
    + *                   gc.epsilon.TestInitAllocs
    + *
    + * @run main/othervm -Xmx256m
    + *                   -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC
    + *                   -XX:+UseTLAB
    + *                   -XX:+UseCompressedOops
    + *                   -XX:EpsilonMinHeapExpand=1024
    + *                   -XX:EpsilonUpdateCountersStep=1
    + *                   -XX:EpsilonPrintHeapSteps=1000000
    + *                   gc.epsilon.TestInitAllocs
    + *
    + * @run main/othervm -Xmx256m
    + *                   -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC
    + *                   -XX:+UseTLAB
    + *                   -XX:-UseCompressedOops
    + *                   -XX:EpsilonMinHeapExpand=1024
    + *                   -XX:EpsilonUpdateCountersStep=1
    + *                   -XX:EpsilonPrintHeapSteps=1000000
    + *                   gc.epsilon.TestInitAllocs
    + *
    + * @run main/othervm -Xmx256m
    + *                   -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC
    + *                   -XX:-UseTLAB
    + *                   -XX:+UseCompressedOops
    + *                   -XX:EpsilonMinHeapExpand=1024
    + *                   -XX:EpsilonUpdateCountersStep=1
    + *                   -XX:EpsilonPrintHeapSteps=1000000
    + *                   gc.epsilon.TestInitAllocs
    + *
    + * @run main/othervm -Xmx256m
    + *                   -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC
    + *                   -XX:-UseTLAB
    + *                   -XX:-UseCompressedOops
    + *                   -XX:EpsilonMinHeapExpand=1024
    + *                   -XX:EpsilonUpdateCountersStep=1
    + *                   -XX:EpsilonPrintHeapSteps=1000000
    + *                   gc.epsilon.TestInitAllocs
    + */
    +
    +public class TestInitAllocs {
    +  public static void main(String[] args) throws Exception {
    +    System.out.println("Hello World");
    +  }
    +}
    diff --git a/test/hotspot/jtreg/gc/g1/TestCodeCacheUnloadDuringConcCycle.java b/test/hotspot/jtreg/gc/g1/TestCodeCacheUnloadDuringConcCycle.java
    index af746ad206d..e36ccace9dc 100644
    --- a/test/hotspot/jtreg/gc/g1/TestCodeCacheUnloadDuringConcCycle.java
    +++ b/test/hotspot/jtreg/gc/g1/TestCodeCacheUnloadDuringConcCycle.java
    @@ -53,9 +53,9 @@ import java.util.regex.Matcher;
     import java.util.regex.Pattern;
     
     import jdk.test.lib.Asserts;
    +import jdk.test.lib.Platform;
     import jdk.test.lib.process.OutputAnalyzer;
     import jdk.test.lib.process.ProcessTools;
    -import static jdk.test.lib.Asserts.*;
     import jdk.test.whitebox.WhiteBox;
     
     public class TestCodeCacheUnloadDuringConcCycle {
    @@ -70,9 +70,10 @@ public class TestCodeCacheUnloadDuringConcCycle {
                                                                         "-Xbootclasspath/a:.",
                                                                         "-Xlog:gc=trace,codecache",
                                                                         "-XX:+WhiteBoxAPI",
    -                                                                    "-XX:ReservedCodeCacheSize=8M",
    +                                                                    "-XX:ReservedCodeCacheSize=" + (Platform.is32bit() ? "4M" : "8M"),
                                                                         "-XX:StartAggressiveSweepingAt=50",
                                                                         "-XX:CompileCommand=compileonly,gc.g1.SomeClass::*",
    +                                                                    "-XX:CompileCommand=compileonly,gc.g1.Foo*::*",
                                                                         TestCodeCacheUnloadDuringConcCycleRunner.class.getName(),
                                                                         concPhase);
             return output;
    @@ -140,7 +141,7 @@ class TestCodeCacheUnloadDuringConcCycleRunner {
                         System.out.println("Compiled " + i + " classes");
                     }
                     i++;
    -            } while (i < 1000);
    +            } while (i < 200);
                 System.out.println("Compilation done, compiled " + i + " classes");
             } catch (Throwable t) {
             }
    diff --git a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOption.java b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOption.java
    index 78a508343d6..d87ca25fc3c 100644
    --- a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOption.java
    +++ b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOption.java
    @@ -116,7 +116,7 @@ public abstract class JVMOption {
                 default:
                     throw new Error("Expected only \"int\", \"intx\", \"size_t\", "
                             + "\"uint\", \"uintx\", \"uint64_t\", or \"double\" "
    -                        + "option types! Got " + type + " type!");
    +                        + "option types! Got " + type + " type for option " + name + "!");
             }
     
             return parameter;
    diff --git a/test/hotspot/jtreg/runtime/cds/TestDefaultArchiveLoading.java b/test/hotspot/jtreg/runtime/cds/TestDefaultArchiveLoading.java
    index acff3191300..8b07cd86a72 100644
    --- a/test/hotspot/jtreg/runtime/cds/TestDefaultArchiveLoading.java
    +++ b/test/hotspot/jtreg/runtime/cds/TestDefaultArchiveLoading.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2024, 2026, Oracle and/or its affiliates. All rights reserved.
      * Copyright (c) 2024, Red Hat, Inc. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
    @@ -55,7 +55,7 @@
      * @requires vm.cds.default.archive.available
      * @requires vm.cds.write.archived.java.heap
      * @requires vm.bits == 64
    - * @requires !vm.gc.Z
    + * @requires vm.gc != "Z"
      * @library /test/lib
      * @modules java.base/jdk.internal.misc
      *          java.management
    @@ -69,7 +69,7 @@
      * @requires vm.cds.default.archive.available
      * @requires vm.cds.write.archived.java.heap
      * @requires vm.bits == 64
    - * @requires !vm.gc.Z
    + * @requires vm.gc != "Z"
      * @library /test/lib
      * @modules java.base/jdk.internal.misc
      *          java.management
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/DynamicDumpWithAOTLinkedStaticArchive.java b/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/DynamicDumpWithAOTLinkedStaticArchive.java
    new file mode 100644
    index 00000000000..8014ed685ee
    --- /dev/null
    +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/DynamicDumpWithAOTLinkedStaticArchive.java
    @@ -0,0 +1,60 @@
    +/*
    + * Copyright (c) 2025, 2026, 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.
    + *
    + */
    +
    +
    +/*
    + * @test
    + * @bug 8374639
    + * @requires vm.cds.supports.aot.class.linking
    + * @library /test/lib
    + * @build DynamicDumpWithAOTLinkedStaticArchive jdk.test.whitebox.WhiteBox
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar TestApp
    + * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. DynamicDumpWithAOTLinkedStaticArchive
    + */
    +
    +import jdk.test.lib.cds.SimpleCDSAppTester;
    +import jdk.test.lib.process.OutputAnalyzer;
    +
    +public class DynamicDumpWithAOTLinkedStaticArchive {
    +    public static void main(String... args) throws Exception {
    +        SimpleCDSAppTester.of("DynamicDumpWithAOTLinkedStaticArchive")
    +            .classpath("app.jar")
    +            .appCommandLine("TestApp")
    +            .setGenerateBaseArchive(true)
    +            .setBaseArchiveOptions("-XX:+AOTClassLinking")
    +            .setProductionChecker((OutputAnalyzer out) -> {
    +                    out.shouldContain("HelloWorld");
    +                })
    +            .runDynamicWorkflow();
    +    }
    +}
    +
    +class TestApp {
    +    public static void main(String[] args) {
    +        System.out.println("HelloWorld");
    +        System[][][] x = new System[0][0][0];
    +        System.out.println(x);
    +    }
    +}
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/ArrayKlasses.java b/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/ArrayKlasses.java
    deleted file mode 100644
    index e476382c8c9..00000000000
    --- a/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/ArrayKlasses.java
    +++ /dev/null
    @@ -1,170 +0,0 @@
    -/*
    - * Copyright (c) 2019, 2025, 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.
    - *
    - */
    -
    -/*
    - * @test
    - * @summary handling of the existence of InstanceKlass::array_klasses()
    - * @requires vm.cds
    - * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds
    - *          /test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/test-classes
    - * @build ArrayKlassesApp
    - * @build jdk.test.whitebox.WhiteBox
    - * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar ArrayKlasses.jar ArrayKlassesApp
    - * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    - * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. ArrayKlasses
    - */
    -
    -import jdk.test.lib.helpers.ClassFileInstaller;
    -
    -public class ArrayKlasses extends DynamicArchiveTestBase {
    -    public static void main(String[] args) throws Exception {
    -        runTest(ArrayKlasses::test);
    -    }
    -
    -    static void test() throws Exception {
    -        String topArchiveName = getNewArchiveName();
    -        final String appJar = ClassFileInstaller.getJarPath("ArrayKlasses.jar");
    -        final String mainClass = "ArrayKlassesApp";
    -        final String runtimeLogOptions =
    -            "-Xlog:class+load,class+load+array=debug,cds+dynamic=debug,cds=debug,aot+unshareable=trace";
    -
    -        // Case 1
    -        // Create a dynamic archive with the ArrayKlassesApp app class and its
    -        // array classes.
    -        dump2(null, topArchiveName,
    -              "-Xlog:cds+dynamic=debug,cds+class=debug",
    -              "-cp", appJar, mainClass)
    -              .assertNormalExit(output -> {
    -                     output.shouldMatch("cds.class.*klasses.*array \\[LArrayKlassesApp;")
    -                           .shouldMatch("cds.class.*klasses.*array \\[\\[LArrayKlassesApp;")
    -                           .shouldMatch("cds.class.*klasses.*array \\[\\[\\[LArrayKlassesApp;");
    -                 });
    -
    -        // Case 1
    -        // At runtime , the ArrayKlasesApp and its array class should be loaded
    -        // from the dynamic archive.
    -        run2(null, topArchiveName, runtimeLogOptions,
    -             "-cp", appJar, mainClass)
    -             .assertNormalExit(output -> {
    -                     output.shouldContain("ArrayKlassesApp source: shared objects file (top)")
    -                           .shouldContain("restore: ArrayKlassesApp with class loader: jdk.internal.loader.ClassLoaders$AppClassLoader")
    -                           .shouldContain("[LArrayKlassesApp; source: shared objects file (top)")
    -                           .shouldContain("restore: [LArrayKlassesApp; with class loader: jdk.internal.loader.ClassLoaders$AppClassLoader")
    -                           .shouldContain("[[LArrayKlassesApp; source: shared objects file (top)")
    -                           .shouldContain("restore: [[LArrayKlassesApp; with class loader: jdk.internal.loader.ClassLoaders$AppClassLoader")
    -                           .shouldContain("[[[LArrayKlassesApp; source: shared objects file (top)")
    -                           .shouldContain("restore: [[[LArrayKlassesApp; with class loader: jdk.internal.loader.ClassLoaders$AppClassLoader")
    -                           .shouldHaveExitValue(0);
    -                 });
    -
    -        // Case 2
    -        // Create a dynamic archive with the array classes of java/util/Date which
    -        // is in the default CDS archive.
    -        topArchiveName = getNewArchiveName();
    -        dump2(null, topArchiveName,
    -              "-Xlog:class+load,cds+dynamic=debug,cds+class=debug",
    -              "-cp", appJar, mainClass, "system")
    -              .assertNormalExit(output -> {
    -                     output.shouldContain("java.util.Date source: shared objects file")
    -                           .shouldMatch("cds.class.*klasses.*array \\[Ljava.util.Date;")
    -                           .shouldMatch("cds.class.*klasses.*array \\[\\[Ljava.util.Date;")
    -                           .shouldMatch("cds.class.*klasses.*array \\[\\[\\[Ljava.util.Date;");
    -                 });
    -
    -        // Case 2
    -        // At runtime, the java/util/Date class should be loaded from the default
    -        // CDS archive; its array class should be loaded from the dynamic archive.
    -        run2(null, topArchiveName, runtimeLogOptions,
    -             "-cp", appJar, mainClass, "system")
    -             .assertNormalExit(output -> {
    -                     output.shouldContain("java.util.Date source: shared objects file")
    -                           .shouldContain("restore: java.util.Date with class loader: boot")
    -                           .shouldContain("[Ljava.util.Date; source: shared objects file (top)")
    -                           .shouldContain("restore: [Ljava.util.Date; with class loader: boot")
    -                           .shouldContain("[[Ljava.util.Date; source: shared objects file (top)")
    -                           .shouldContain("restore: [[Ljava.util.Date; with class loader: boot")
    -                           .shouldContain("[[[Ljava.util.Date; source: shared objects file (top)")
    -                           .shouldContain("restore: [[[Ljava.util.Date; with class loader: boot")
    -                           .shouldHaveExitValue(0);
    -                 });
    -
    -        // Case 3
    -        // Create a dynamic archive with primitive arrays [[J and [[[J with [J
    -        // already in the default CDS archive
    -        topArchiveName = getNewArchiveName();
    -        dump2(null, topArchiveName,
    -              "-Xlog:class+load,cds+dynamic=debug,cds+class=debug",
    -              "-cp", appJar, mainClass, "primitive")
    -              .assertNormalExit(output -> {
    -                     output.shouldMatch("cds.class.*klasses.*array \\[\\[J")
    -                           .shouldMatch("cds.class.*klasses.*array \\[\\[\\[J");
    -                 });
    -
    -        // Case 3
    -        // At runtime, the [J should be loaded from the default CDS archive;
    -        // the higher-dimension array should be loaded from the dynamic archive.
    -        run2(null, topArchiveName, runtimeLogOptions,
    -             "-cp", appJar, mainClass, "primitive")
    -             .assertNormalExit(output -> {
    -                     output.shouldContain("[J source: shared objects file")
    -                           .shouldContain("restore: [J with class loader: boot")
    -                           .shouldContain("[[J source: shared objects file (top)")
    -                           .shouldContain("restore: [[J with class loader: boot")
    -                           .shouldContain("[[[J source: shared objects file (top)")
    -                           .shouldContain("restore: [[[J with class loader: boot")
    -                           .shouldHaveExitValue(0);
    -                 });
    -
    -        // Case 4
    -        // Create a dynamic archive with 2-, 3- and 4-dimension arrays of java/lang/Integer.
    -        // The java/lang/Integer class and the 1-dimension array is in the default archive.
    -        topArchiveName = getNewArchiveName();
    -        dump2(null, topArchiveName,
    -              "-Xlog:class+load,cds+dynamic=debug,cds+class=debug",
    -              "-cp", appJar, mainClass, "integer-array")
    -              .assertNormalExit(output -> {
    -                     output.shouldMatch("cds.class.*klasses.*array \\[\\[Ljava.lang.Integer;")
    -                           .shouldMatch("cds.class.*klasses.*array \\[\\[\\[Ljava.lang.Integer;")
    -                           .shouldMatch("cds.class.*klasses.*array \\[\\[\\[\\[Ljava.lang.Integer;");
    -                 });
    -
    -        // Case 4
    -        // At runtime, the 4-dimension array of java/lang/Integer should be
    -        // loaded from the dynamic archive.
    -        run2(null, topArchiveName, runtimeLogOptions,
    -             "-cp", appJar, mainClass, "integer-array")
    -             .assertNormalExit(output -> {
    -                     output.shouldContain("java.lang.Integer source: shared objects file")
    -                           .shouldContain("restore: java.lang.Integer with class loader: boot")
    -                           .shouldContain("restore: [Ljava.lang.Integer; with class loader: boot")
    -                           .shouldContain("[[Ljava.lang.Integer; source: shared objects file (top)")
    -                           .shouldContain("restore: [[Ljava.lang.Integer; with class loader: boot")
    -                           .shouldContain("[[[Ljava.lang.Integer; source: shared objects file (top)")
    -                           .shouldContain("restore: [[[Ljava.lang.Integer; with class loader: boot")
    -                           .shouldContain("[[[[Ljava.lang.Integer; source: shared objects file (top)")
    -                           .shouldContain("restore: [[[[Ljava.lang.Integer; with class loader: boot")
    -                           .shouldHaveExitValue(0);
    -                 });
    -    }
    -}
    diff --git a/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/test-classes/ArrayKlassesApp.java b/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/test-classes/ArrayKlassesApp.java
    deleted file mode 100644
    index 3c78e3e8dbe..00000000000
    --- a/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/test-classes/ArrayKlassesApp.java
    +++ /dev/null
    @@ -1,77 +0,0 @@
    -/*
    - * 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
    - * 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.Array;
    -import java.util.Date;
    -
    -public class ArrayKlassesApp {
    -    public static void main(String args[]) {
    -        if (args.length == 1) {
    -            if (args[0].equals("system")) {
    -                Date[][][] array = new Date[1][2][2];
    -                int count = 0;
    -                for (int i=0; i<1; i++) {
    -                    for (int j=0; j<2; j++) {
    -                        for (int k=0; k<2; k++) {
    -                            array[i][j][k] = new Date();
    -                            count++;
    -                            array[i][j][k].setTime(20000 * count);
    -                        }
    -                    }
    -                }
    -            } else if (args[0].equals("primitive")) {
    -                long[][][] larray = new long[1][2][2];
    -                long lcount = 0;
    -                for (int i=0; i<1; i++) {
    -                    for (int j=0; j<2; j++) {
    -                        for (int k=0; k<2; k++) {
    -                            lcount++;
    -                            larray[i][j][k] = lcount;
    -                        }
    -                    }
    -                }
    -            } else if (args[0].equals("integer-array")) {
    -                Integer[][][][] iarray = new Integer[4][4][4][4];
    -                int count = 0;
    -                for (int i = 0; i < 4; i++) {
    -                    for (int j = 0; j < 4; j++) {
    -                        for (int k = 0; k < 4; k++) {
    -                            for (int l = 0; l < 4; l++) {
    -                                count++;
    -                                iarray[i][j][k][l] = new Integer(count);
    -                            }
    -                        }
    -                    }
    -                }
    -                System.out.println(iarray);
    -                System.out.println(iarray.getClass());
    -            }
    -        } else {
    -            Object x = Array.newInstance(ArrayKlassesApp.class, 3,3,3);
    -            System.out.println(x);
    -            System.out.println(x.getClass());
    -            System.out.println(Array.getLength(x));
    -        }
    -    }
    -}
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/NMethodRelocation/NMethodRelocationTest.java b/test/hotspot/jtreg/serviceability/jvmti/NMethodRelocation/NMethodRelocationTest.java
    index 6c465b357d7..10888dce1b4 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/NMethodRelocation/NMethodRelocationTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/NMethodRelocation/NMethodRelocationTest.java
    @@ -23,23 +23,30 @@
     
     /*
      * @test
    - *
      * @bug 8316694
      * @summary Verify that nmethod relocation posts the correct JVMTI events
    - * @requires vm.jvmti
    - * @requires vm.gc == "null" | vm.gc == "Serial"
    + * @requires vm.jvmti &
    + *           vm.gc != "Epsilon" &
    + *           vm.flavor == "server" &
    + *           !vm.emulatedClient &
    + *           (vm.opt.TieredStopAtLevel == null | vm.opt.TieredStopAtLevel == 4)
      * @library /test/lib /test/hotspot/jtreg
      * @build jdk.test.whitebox.WhiteBox
      * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    - * @run main/othervm/native NMethodRelocationTest
    + * @run main/othervm/native -agentlib:NMethodRelocationTest
    + *                          --enable-native-access=ALL-UNNAMED
    + *                          -Xbootclasspath/a:.
    + *                          -Xbatch
    + *                          -XX:+UnlockDiagnosticVMOptions
    + *                          -XX:+WhiteBoxAPI
    + *                          -XX:+SegmentedCodeCache
    + *                          -XX:-TieredCompilation
    + *                          -XX:+UnlockExperimentalVMOptions
    + *                          -XX:+NMethodRelocation
    + *                          NMethodRelocationTest
      */
     
    -import static compiler.whitebox.CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION;
    -
     import java.lang.reflect.Executable;
    -import java.util.Objects;
    -import java.util.regex.Matcher;
    -import java.util.regex.Pattern;
     
     import jdk.test.lib.Asserts;
     import jdk.test.lib.process.OutputAnalyzer;
    @@ -48,52 +55,9 @@ import jdk.test.whitebox.WhiteBox;
     import jdk.test.whitebox.code.BlobType;
     import jdk.test.whitebox.code.NMethod;
     
    +import static compiler.whitebox.CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION;
     
     public class NMethodRelocationTest {
    -    public static void main(String[] args) throws Exception {
    -        ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
    -                "-agentlib:NMethodRelocationTest",
    -                "--enable-native-access=ALL-UNNAMED",
    -                "-Xbootclasspath/a:.",
    -                "-XX:+UseSerialGC",
    -                "-XX:+UnlockDiagnosticVMOptions",
    -                "-XX:+WhiteBoxAPI",
    -                "-XX:+SegmentedCodeCache",
    -                "-XX:-TieredCompilation",
    -                "-XX:+UnlockExperimentalVMOptions",
    -                "-XX:+NMethodRelocation",
    -                "DoWork");
    -
    -        OutputAnalyzer oa = new OutputAnalyzer(pb.start());
    -        String output = oa.getOutput();
    -        if (oa.getExitValue() != 0) {
    -            System.err.println(oa.getOutput());
    -            throw new RuntimeException("Non-zero exit code returned from the test");
    -        }
    -        Asserts.assertTrue(oa.getExitValue() == 0);
    -
    -        Pattern pattern = Pattern.compile("(?m)^Relocated nmethod from (0x[0-9a-f]{16}) to (0x[0-9a-f]{16})$");
    -        Matcher matcher = pattern.matcher(output);
    -
    -        if (matcher.find()) {
    -            String fromAddr = matcher.group(1);
    -            String toAddr = matcher.group(2);
    -
    -            // Confirm events sent for both original and relocated nmethod
    -            oa.shouldContain(":   name: compiledMethod, code: " + fromAddr);
    -            oa.shouldContain(":   name: compiledMethod, code: " + toAddr);
    -            oa.shouldContain(":   name: compiledMethod, code: " + fromAddr);
    -            oa.shouldContain(":   name: compiledMethod, code: " + toAddr);
    -        } else {
    -            System.err.println(oa.getOutput());
    -            throw new RuntimeException("Unable to find relocation information");
    -        }
    -    }
    -}
    -
    -class DoWork {
    -
    -    protected static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
     
         /** Load native library if required. */
         static {
    @@ -107,43 +71,18 @@ class DoWork {
             }
         }
     
    -    /**
    -     * Returns value of VM option.
    -     *
    -     * @param name option's name
    -     * @return value of option or {@code null}, if option doesn't exist
    -     * @throws NullPointerException if name is null
    -     */
    -    protected static String getVMOption(String name) {
    -        Objects.requireNonNull(name);
    -        return Objects.toString(WHITE_BOX.getVMFlag(name), null);
    -    }
    +    protected static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
     
    -    /**
    -     * Returns value of VM option or default value.
    -     *
    -     * @param name         option's name
    -     * @param defaultValue default value
    -     * @return value of option or {@code defaultValue}, if option doesn't exist
    -     * @throws NullPointerException if name is null
    -     * @see #getVMOption(String)
    -     */
    -    protected static String getVMOption(String name, String defaultValue) {
    -        String result = getVMOption(name);
    -        return result == null ? defaultValue : result;
    -    }
    +    native static boolean shouldExit();
     
    -    public static void main(String argv[]) throws Exception {
    -        run();
    -    }
    -
    -    public static void run() throws Exception {
    -        Executable method = DoWork.class.getDeclaredMethod("compiledMethod");
    +    public static void main(String[] argv) throws Exception {
    +        Executable method = NMethodRelocationTest.class.getDeclaredMethod("compiledMethod");
             WHITE_BOX.testSetDontInlineMethod(method, true);
     
             WHITE_BOX.enqueueMethodForCompilation(method, COMP_LEVEL_FULL_OPTIMIZATION);
    -        while (WHITE_BOX.isMethodQueuedForCompilation(method)) {
    -            Thread.onSpinWait();
    +
    +        if (!WHITE_BOX.isMethodCompiled(method)) {
    +            throw new AssertionError("Method not compiled");
             }
     
             NMethod originalNMethod = NMethod.get(method, false);
    @@ -164,13 +103,9 @@ class DoWork {
     
             WHITE_BOX.deoptimizeAll();
     
    -        WHITE_BOX.fullGC();
    -        WHITE_BOX.fullGC();
    -
    -        WHITE_BOX.lockCompilation();
    -
    -        System.out.printf("Relocated nmethod from 0x%016x to 0x%016x%n", originalNMethod.code_begin, relocatedNMethod.code_begin);
    -        System.out.flush();
    +        while (!shouldExit()) {
    +            WHITE_BOX.fullGC();
    +        }
         }
     
         public static long compiledMethod() {
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/NMethodRelocation/libNMethodRelocationTest.cpp b/test/hotspot/jtreg/serviceability/jvmti/NMethodRelocation/libNMethodRelocationTest.cpp
    index 41ba6b10608..7f8ab7b78bc 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/NMethodRelocation/libNMethodRelocationTest.cpp
    +++ b/test/hotspot/jtreg/serviceability/jvmti/NMethodRelocation/libNMethodRelocationTest.cpp
    @@ -21,10 +21,20 @@
      * questions.
      */
     
    +#include 
     #include 
    -#include 
    -#include 
    -#include 
    +#include "jvmti_common.hpp"
    +
    +extern "C" {
    +
    +// Track nmethod addresses for LOAD and UNLOAD events
    +static const void* first_load_addr      = nullptr;
    +static const void* second_load_addr     = nullptr;
    +static const void* first_unload_addr    = nullptr;
    +static const void* second_unload_addr   = nullptr;
    +
    +// Keep track of test completion
    +static std::atomic should_exit{false};
     
     /**
      * Callback for COMPILED_METHOD_LOAD event.
    @@ -34,18 +44,27 @@ callbackCompiledMethodLoad(jvmtiEnv* jvmti, jmethodID method,
                                 jint code_size, const void* code_addr,
                                 jint map_length, const jvmtiAddrLocationMap* map,
                                 const void* compile_info) {
    -    char* name = nullptr;
    -    char* sig = nullptr;
     
    -    if (jvmti->GetMethodName(method, &name, &sig, nullptr) != JVMTI_ERROR_NONE) {
    -        printf("    [Could not retrieve method name]\n");
    -        fflush(stdout);
    +    // Only track events for "compiledMethod"
    +    char* name = get_method_name(jvmti, method);
    +    if (strcmp(name, "compiledMethod") != 0) {
             return;
         }
     
    -    printf(":   name: %s, code: 0x%016" PRIxPTR "\n",
    -        name, (uintptr_t)code_addr);
    -    fflush(stdout);
    +    LOG(":   name: %s, code: 0x%016" PRIxPTR "\n", name, (uintptr_t)code_addr);
    +
    +    if (first_load_addr == nullptr) {
    +        first_load_addr = code_addr;
    +    } else if (second_load_addr == nullptr) {
    +        second_load_addr = code_addr;
    +
    +        // Verify that the addresses are different
    +        if (first_load_addr == second_load_addr) {
    +            fatal("Load events for 'compiledMethod' are expected to use different addresses");
    +        }
    +    } else {
    +        fatal("Received too many load events for 'compiledMethod'");
    +    }
     }
     
     /**
    @@ -54,25 +73,50 @@ callbackCompiledMethodLoad(jvmtiEnv* jvmti, jmethodID method,
     JNIEXPORT void JNICALL
     callbackCompiledMethodUnload(jvmtiEnv* jvmti, jmethodID method,
                                  const void* code_addr) {
    -    char* name = nullptr;
    -    char* sig = nullptr;
     
    -    if (jvmti->GetMethodName(method, &name, &sig, nullptr) != JVMTI_ERROR_NONE) {
    -        printf("    [Could not retrieve method name]\n");
    -        fflush(stdout);
    +    // Only track events for "compiledMethod"
    +    char* name = get_method_name(jvmti, method);
    +    if (strcmp(name, "compiledMethod") != 0) {
             return;
         }
    -    printf(":   name: %s, code: 0x%016" PRIxPTR "\n",
    -        name, (uintptr_t)code_addr);
    -    fflush(stdout);
    +
    +    LOG(":   name: %s, code: 0x%016" PRIxPTR "\n", name, (uintptr_t)code_addr);
    +
    +    // Validate both loads have occurred
    +    if (first_load_addr == nullptr || second_load_addr == nullptr) {
    +        fatal("UNLOAD event for 'compiledMethod' occurred before both LOAD events");
    +    }
    +
    +    if (first_unload_addr == nullptr) {
    +        first_unload_addr = code_addr;
    +    } else if (second_unload_addr == nullptr) {
    +        second_unload_addr = code_addr;
    +
    +        // Verify that the addresses are different
    +        if (first_unload_addr == second_unload_addr) {
    +            fatal("Unload events for 'compiledMethod' are expected to use different addresses");
    +        }
    +
    +        // LOAD and UNLOAD events should report the same two addresses, but the order of
    +        // the UNLOADs is not guaranteed, since the GC may unload either nmethod first.
    +        if ((first_load_addr == first_unload_addr  && second_load_addr == second_unload_addr) ||
    +            (first_load_addr == second_unload_addr && second_load_addr == first_unload_addr)) {
    +
    +            // Update should_exit to signal test completion
    +            should_exit.store(true);
    +        } else {
    +            fatal("Address mismatch for 'compiledMethod' events");
    +        }
    +    } else {
    +        fatal("Received too many unload events for 'compiledMethod'");
    +    }
     }
     
     JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
         jvmtiEnv* jvmti = nullptr;
    -    jvmtiError error;
     
         if (jvm->GetEnv((void **)&jvmti, JVMTI_VERSION_1_0) != JNI_OK) {
    -        printf("Unable to access JVMTI!\n");
    +        LOG("Unable to access JVMTI!\n");
             return JNI_ERR;
         }
     
    @@ -80,11 +124,8 @@ JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved)
         jvmtiCapabilities caps;
         memset(&caps, 0, sizeof(caps));
         caps.can_generate_compiled_method_load_events = 1;
    -    error = jvmti->AddCapabilities(&caps);
    -    if (error != JVMTI_ERROR_NONE) {
    -        printf("ERROR: Unable to add capabilities, error=%d\n", error);
    -        return JNI_ERR;
    -    }
    +    jvmtiError error = jvmti->AddCapabilities(&caps);
    +    check_jvmti_error(error, "Unable to add capabilities");
     
         // Set event callbacks
         jvmtiEventCallbacks eventCallbacks;
    @@ -92,23 +133,21 @@ JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved)
         eventCallbacks.CompiledMethodLoad = callbackCompiledMethodLoad;
         eventCallbacks.CompiledMethodUnload = callbackCompiledMethodUnload;
         error = jvmti->SetEventCallbacks(&eventCallbacks, sizeof(eventCallbacks));
    -    if (error != JVMTI_ERROR_NONE) {
    -        printf("ERROR: Unable to set event callbacks, error=%d\n", error);
    -        return JNI_ERR;
    -    }
    +    check_jvmti_error(error, "Unable to set event callbacks");
     
         // Enable events
         error = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, nullptr);
    -    if (error != JVMTI_ERROR_NONE) {
    -        printf("ERROR: Unable to enable COMPILED_METHOD_LOAD event, error=%d\n", error);
    -        return JNI_ERR;
    -    }
    +    check_jvmti_error(error, "Unable to enable COMPILED_METHOD_LOAD event");
     
         error = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_UNLOAD, nullptr);
    -    if (error != JVMTI_ERROR_NONE) {
    -        printf("ERROR: Unable to enable COMPILED_METHOD_UNLOAD event, error=%d\n", error);
    -        return JNI_ERR;
    -    }
    +    check_jvmti_error(error, "Unable to enable COMPILED_METHOD_UNLOAD event");
     
         return JNI_OK;
     }
    +
    +JNIEXPORT jboolean JNICALL
    +Java_NMethodRelocationTest_shouldExit(JNIEnv *env, jclass cls) {
    +  return should_exit.load();
    +}
    +
    +}
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/events/Breakpoint/breakpoint01/breakpoint01.java b/test/hotspot/jtreg/serviceability/jvmti/events/Breakpoint/breakpoint01/breakpoint01.java
    index 82d4dccd5f7..946d46f7deb 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/events/Breakpoint/breakpoint01/breakpoint01.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/events/Breakpoint/breakpoint01/breakpoint01.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2003, 2026, 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
    @@ -38,6 +38,7 @@ import java.io.*;
      *     SetBreakpoint().
      * COMMENTS
      *
    + * @requires test.thread.factory == null
      * @library /test/lib
      *
      * @comment make sure breakpoint01 is compiled with full debug info
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/events/ClassLoad/classload01/classload01.java b/test/hotspot/jtreg/serviceability/jvmti/events/ClassLoad/classload01/classload01.java
    index f163777d1f8..8d8c6a3a1f6 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/events/ClassLoad/classload01/classload01.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/events/ClassLoad/classload01/classload01.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2003, 2026, 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
    @@ -42,6 +42,7 @@ import java.io.*;
      * COMMENTS
      *     Fixed the 5031200 bug.
      *
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile classload01.java
      * @run main/othervm/native -agentlib:classload01 classload01
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/events/ClassPrepare/classprep01/classprep01.java b/test/hotspot/jtreg/serviceability/jvmti/events/ClassPrepare/classprep01/classprep01.java
    index eafe06587e2..eda93ded012 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/events/ClassPrepare/classprep01/classprep01.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/events/ClassPrepare/classprep01/classprep01.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2003, 2026, 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
    @@ -37,6 +37,7 @@
      *     Fixed according to the bug 4651181.
      *     Ported from JVMDI.
      *
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile classprep01.java
      * @run main/othervm/native -agentlib:classprep01 classprep01
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/events/MethodEntry/mentry02/mentry02.java b/test/hotspot/jtreg/serviceability/jvmti/events/MethodEntry/mentry02/mentry02.java
    index bcfb682e749..3df2e28299f 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/events/MethodEntry/mentry02/mentry02.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/events/MethodEntry/mentry02/mentry02.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2003, 2026, 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
    @@ -37,6 +37,7 @@
      *     The test reproduced the bug on winNT 1.0fcs-E build.
      *     Ported from JVMDI test /nsk/regression/b4248826.
      *
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile mentry02.java
      * @run main/othervm/native -agentlib:mentry02 mentry02
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/events/MonitorWaited/monitorwaited01/monitorwaited01.java b/test/hotspot/jtreg/serviceability/jvmti/events/MonitorWaited/monitorwaited01/monitorwaited01.java
    index db246c17d8f..b56a0f2b781 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/events/MonitorWaited/monitorwaited01/monitorwaited01.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/events/MonitorWaited/monitorwaited01/monitorwaited01.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2003, 2026, 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,6 +41,7 @@ import jdk.test.lib.jvmti.DebugeeClass;
      *       and save JNIEnv pointer now passed as argument.
      *
      * @requires vm.continuations
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile monitorwaited01.java
      * @run main/othervm/native -agentlib:monitorwaited01 monitorwaited01 platform
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/negative/thrinfo02/thrinfo02.java b/test/hotspot/jtreg/serviceability/jvmti/negative/thrinfo02/thrinfo02.java
    index 55f60355cfe..fdcbe879d37 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/negative/thrinfo02/thrinfo02.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/negative/thrinfo02/thrinfo02.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2003, 2026, 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
    @@ -35,6 +35,7 @@
      * COMMENTS
      *     Ported from JVMDI.
      *
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @run main/othervm/native -agentlib:thrinfo02 thrinfo02
      */
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/thread/GetThreadInfo/thrinfo01/thrinfo01.java b/test/hotspot/jtreg/serviceability/jvmti/thread/GetThreadInfo/thrinfo01/thrinfo01.java
    index 1b9dd583f6a..385a838f726 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/thread/GetThreadInfo/thrinfo01/thrinfo01.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/thread/GetThreadInfo/thrinfo01/thrinfo01.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2003, 2026, 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,6 +41,7 @@
      *     Fixed according to the 4480280 bug.
      *     Ported from JVMDI.
      *
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile thrinfo01.java
      * @run main/othervm/native -agentlib:thrinfo01 thrinfo01
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/BoundVThreadTest/BoundVThreadTest.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/BoundVThreadTest/BoundVThreadTest.java
    index e1ce4e3d902..1ba3a114317 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/BoundVThreadTest/BoundVThreadTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/BoundVThreadTest/BoundVThreadTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2023, 2026, 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,6 +23,7 @@
     
     /**
      * @test
    + * @requires test.thread.factory == null
      * @summary Verifies correct JVMTI behavior for BoundVirtualThreads.
      * @run main/othervm/native -agentlib:BoundVThreadTest -XX:+UnlockExperimentalVMOptions -XX:-VMContinuations BoundVThreadTest
      */
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/ContinuationTest/ContinuationTest.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/ContinuationTest/ContinuationTest.java
    index bd7626e7a7e..939eb450d5c 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/ContinuationTest/ContinuationTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/ContinuationTest/ContinuationTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2018, 2026, 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
      * @summary Verifies JVMTI support for Continuations
      * @requires vm.continuations
    + * @requires test.thread.factory == null
      * @compile ContinuationTest.java
      * @modules java.base/jdk.internal.vm
      * @run main/othervm/native -agentlib:ContinuationTest ContinuationTest
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/FollowReferences/VThreadStackRefTest.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/FollowReferences/VThreadStackRefTest.java
    index 7b8b8e47519..880df734383 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/FollowReferences/VThreadStackRefTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/FollowReferences/VThreadStackRefTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2023, 2026, 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 id=default
      * @requires vm.jvmti
      * @requires vm.continuations
    + * @requires test.thread.factory == null
      * @run main/othervm/native
      *      -Djdk.virtualThreadScheduler.maxPoolSize=1
      *      -agentlib:VThreadStackRefTest
    @@ -34,6 +35,7 @@
     /**
      * @test id=no-vmcontinuations
      * @requires vm.jvmti
    + * @requires test.thread.factory == null
      * @run main/othervm/native
      *      -XX:+UnlockExperimentalVMOptions -XX:-VMContinuations
      *      -agentlib:VThreadStackRefTest
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/SelfSuspendDisablerTest/SelfSuspendDisablerTest.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/SelfSuspendDisablerTest/SelfSuspendDisablerTest.java
    index 0c447610013..b596a5c7ee2 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/SelfSuspendDisablerTest/SelfSuspendDisablerTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/SelfSuspendDisablerTest/SelfSuspendDisablerTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2021, 2026, 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,6 +24,7 @@
     /*
      * @test id=default
      * @summary Test verifies that selfsuspend doesn' block unmount by VTMTDisabler
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile SelfSuspendDisablerTest.java
      * @run main/othervm/native -agentlib:SelfSuspendDisablerTest SelfSuspendDisablerTest
    @@ -32,6 +33,7 @@
     /*
      * @test id=no-vmcontinuations
      * @requires vm.continuations
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile SelfSuspendDisablerTest.java
      * @run main/othervm/native -agentlib:SelfSuspendDisablerTest -XX:+UnlockExperimentalVMOptions -XX:-VMContinuations SelfSuspendDisablerTest
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResume1/SuspendResume1.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResume1/SuspendResume1.java
    index 39f9a1ab2ae..4610516121e 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResume1/SuspendResume1.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResume1/SuspendResume1.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2021, 2026, 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 @@
      * @summary Test SuspendThread/ResumeThread, SuspendThreadList/ResumeThreadList
      *          for virtual threads.
      * @requires vm.debug != true
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile SuspendResume1.java
      * @run driver jdk.test.lib.FileInstaller . .
    @@ -38,6 +39,7 @@
     /*
      * @test id=debug
      * @requires vm.debug == true
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile SuspendResume1.java
      * @run driver jdk.test.lib.FileInstaller . .
    @@ -51,6 +53,7 @@
      /*
      * @test id=no-vmcontinuations
      * @requires vm.continuations
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile SuspendResume1.java
      * @run driver jdk.test.lib.FileInstaller . .
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResume2/SuspendResume2.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResume2/SuspendResume2.java
    index 80dd42c480a..d38391b91dd 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResume2/SuspendResume2.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResume2/SuspendResume2.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2021, 2026, 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 id=default
      * @summary Test SuspendAllVirtualThreads/ResumeAllVirtualThreads
      * @requires vm.debug != true
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile SuspendResume2.java
      * @run driver jdk.test.lib.FileInstaller . .
    @@ -37,6 +38,7 @@
     /*
      * @test id=debug
      * @requires vm.debug == true
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile SuspendResume2.java
      * @run driver jdk.test.lib.FileInstaller . .
    @@ -50,6 +52,7 @@
     /*
      * @test id=no-vmcontinuations
      * @requires vm.continuations
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile SuspendResume2.java
      * @run driver jdk.test.lib.FileInstaller . .
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResumeAll/SuspendResumeAll.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResumeAll/SuspendResumeAll.java
    index 35ea1611453..54fb4f6605f 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResumeAll/SuspendResumeAll.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/SuspendResumeAll/SuspendResumeAll.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2021, 2026, 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,6 +24,7 @@
     /*
      * @test id=default
      * @summary Test SuspendAllVirtualThreads/ResumeAllVirtualThreads
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile SuspendResumeAll.java
      * @run driver jdk.test.lib.FileInstaller . .
    @@ -36,6 +37,7 @@
     /*
      * @test id=no-vmcontinuations
      * @requires vm.continuations
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile SuspendResumeAll.java
      * @run driver jdk.test.lib.FileInstaller . .
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/ThreadListStackTracesTest/ThreadListStackTracesTest.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/ThreadListStackTracesTest/ThreadListStackTracesTest.java
    index 079f65620d8..2a5c9bea111 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/ThreadListStackTracesTest/ThreadListStackTracesTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/ThreadListStackTracesTest/ThreadListStackTracesTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2023, 2026, 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
    @@ -45,8 +45,9 @@ abstract class TestTask implements Runnable {
         }
     
         public void ensureReadyAndWaiting(Thread vt, Thread.State expState, ReentrantLock rlock) {
    +        sleep(50); // reliability: wait for a potential class loading to complete
             // wait while the thread is not ready or thread state is unexpected
    -        while (!threadReady || (vt.getState() != expState) || !rlock.hasQueuedThreads()) {
    +        while (!threadReady || (vt.getState() != expState) || !rlock.hasQueuedThread(vt)) {
                 sleep(1);
             }
         }
    @@ -125,11 +126,12 @@ public class ThreadListStackTracesTest {
             int jvmtiExpState = (expState == Thread.State.WAITING) ?
                                 JVMTI_THREAD_STATE_WAITING :
                                 JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER;
    +        Thread.State state = vt.getState();
     
    -        System.out.printf("State: expected: %s single: %x multi: %x\n",
    -                          vt.getState(), singleState, multiState);
    +        System.out.printf("State: expected: %s, vt.getState(): %s, jvmtiExpState: %x single: %x multi: %x\n",
    +                          expState, state, jvmtiExpState, singleState, multiState);
     
    -        if (vt.getState() != expState) {
    +        if (state != expState) {
                 failed("Java thread state is wrong");
             }
             if ((singleState & jvmtiExpState) == 0) {
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadTLSTest/VThreadTLSTest.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadTLSTest/VThreadTLSTest.java
    index 34d480991bb..6bde3846bfc 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadTLSTest/VThreadTLSTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadTLSTest/VThreadTLSTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2026, 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 @@
      * @summary Verifies JVMTI GetLocalStorage/SetLocalStorage
      * @requires vm.continuations
      * @requires vm.jvmti
    + * @requires test.thread.factory == null
      * @run main/othervm/native -agentlib:VThreadTLSTest VThreadTLSTest
      */
     
    @@ -35,6 +36,7 @@
      * @summary Verifies JVMTI GetLocalStorage/SetLocalStorage
      * @requires vm.continuations
      * @requires vm.jvmti
    + * @requires test.thread.factory == null
      * @run main/othervm/native -Djdk.attach.allowAttachSelf=true -XX:+EnableDynamicAgentLoading VThreadTLSTest attach
      */
     
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadTest/VThreadTest.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadTest/VThreadTest.java
    index 6b65f0d7574..7330f4c061d 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadTest/VThreadTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadTest/VThreadTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2018, 2026, 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
      * @summary Verifies JVMTI support for VThreads.
      * @requires vm.continuations
    + * @requires test.thread.factory == null
      * @compile VThreadTest.java
      * @run main/othervm/native -agentlib:VThreadTest VThreadTest
      */
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadUnsupportedTest/VThreadUnsupportedTest.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadUnsupportedTest/VThreadUnsupportedTest.java
    index 5eb23df9dc4..48840b1f837 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadUnsupportedTest/VThreadUnsupportedTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/VThreadUnsupportedTest/VThreadUnsupportedTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2020, 2026, 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 @@
      * @summary Verifies that specific JVMTI functions return UNSUPPORTED_OPERATION
      *          or OPAQUE_FRAME if called with virtual threads.
      * @requires vm.continuations
    + * @requires test.thread.factory == null
      * @compile VThreadUnsupportedTest.java
      * @run main/othervm/native -agentlib:VThreadUnsupportedTest VThreadUnsupportedTest
      */
    diff --git a/test/hotspot/jtreg/serviceability/jvmti/vthread/WaitNotifySuspendedVThreadTest/WaitNotifySuspendedVThreadTest.java b/test/hotspot/jtreg/serviceability/jvmti/vthread/WaitNotifySuspendedVThreadTest/WaitNotifySuspendedVThreadTest.java
    index 5af72902280..fe169e1fb92 100644
    --- a/test/hotspot/jtreg/serviceability/jvmti/vthread/WaitNotifySuspendedVThreadTest/WaitNotifySuspendedVThreadTest.java
    +++ b/test/hotspot/jtreg/serviceability/jvmti/vthread/WaitNotifySuspendedVThreadTest/WaitNotifySuspendedVThreadTest.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2003, 2026, 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
    @@ -28,6 +28,7 @@
      * suspended virtual thread.
      *
      * @requires vm.continuations
    + * @requires test.thread.factory == null
      * @library /test/lib
      * @compile WaitNotifySuspendedVThreadTest.java
      * @run main/othervm/native
    diff --git a/test/hotspot/jtreg/vmTestbase/gc/gctests/MemoryEaterMT/MemoryEaterMT.java b/test/hotspot/jtreg/vmTestbase/gc/gctests/MemoryEaterMT/MemoryEaterMT.java
    index c97353006d4..d88e34ae5e0 100644
    --- a/test/hotspot/jtreg/vmTestbase/gc/gctests/MemoryEaterMT/MemoryEaterMT.java
    +++ b/test/hotspot/jtreg/vmTestbase/gc/gctests/MemoryEaterMT/MemoryEaterMT.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2007, 2020, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2007, 2026, 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
    @@ -28,6 +28,7 @@
      * @summary converted from VM Testbase gc/gctests/MemoryEaterMT.
      * VM Testbase keywords: [gc, stress, stressopt, nonconcurrent]
      *
    + * @requires test.thread.factory != "Virtual"
      * @library /vmTestbase
      *          /test/lib
      * @run main/othervm -XX:-UseGCOverheadLimit gc.gctests.MemoryEaterMT.MemoryEaterMT
    diff --git a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters001/CollectionCounters001.java b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters001/CollectionCounters001.java
    index 7c089abb6ec..e2f1b9cbc71 100644
    --- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters001/CollectionCounters001.java
    +++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters001/CollectionCounters001.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2007, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2007, 2026, 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,15 +24,19 @@
     
     /*
      * @test
    - * @key randomness
      *
      * @summary converted from VM Testbase nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters001.
      * VM Testbase keywords: [monitoring]
      *
    - * @requires vm.opt.DisableExplicitGC != "true"
      * @library /vmTestbase
      *          /test/lib
    - * @run main/othervm -XX:-UseGCOverheadLimit
    + *
    + * @build jdk.test.whitebox.WhiteBox
    + * @requires vm.opt.DisableExplicitGC != "true"
    + * @requires vm.compMode != "Xcomp"
    + *
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:-UseGCOverheadLimit
      *      nsk.monitoring.GarbageCollectorMXBean.CollectionCounters.CollectionCounters001.CollectionCounters001
      *      -testMode=directly
      *      -iterations=5
    @@ -42,10 +46,12 @@ package nsk.monitoring.GarbageCollectorMXBean.CollectionCounters.CollectionCount
     
     import java.util.List;
     import java.lang.management.*;
    +
    +import jdk.test.whitebox.WhiteBox;
    +
     import nsk.share.TestFailure;
     import nsk.share.test.*;
     import nsk.monitoring.share.*;
    -import nsk.share.gc.Algorithms;
     import nsk.share.runner.RunParams;
     import nsk.share.runner.RunParamsAware;
     
    @@ -80,12 +86,15 @@ public class CollectionCounters001 extends MonitoringTestBase implements RunPara
             private void runOne(ExecutionController stresser) {
                     updateCounters();
                     validate(false /* don't check gc count increases */);
    -                Algorithms.eatMemory(stresser);
    +
    +                WhiteBox.getWhiteBox().fullGC();
                     updateCounters();
                     validate(true);
    +
                     System.gc();
                     updateCounters();
                     validate(true);
    +
                     memory.gc();
                     updateCounters();
                     validate(true);
    diff --git a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters002/TestDescription.java b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters002/TestDescription.java
    index 51abb4e7a0b..2c1e21fcb15 100644
    --- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters002/TestDescription.java
    +++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters002/TestDescription.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2017, 2026, 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,15 +24,19 @@
     
     /*
      * @test
    - * @key randomness
      *
      * @summary converted from VM Testbase nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters002.
      * VM Testbase keywords: [monitoring]
      *
    - * @requires vm.opt.DisableExplicitGC != "true"
      * @library /vmTestbase
      *          /test/lib
    - * @run main/othervm -XX:-UseGCOverheadLimit
    + *
    + * @build jdk.test.whitebox.WhiteBox
    + * @requires vm.opt.DisableExplicitGC != "true"
    + * @requires vm.compMode != "Xcomp"
    + *
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:-UseGCOverheadLimit
      *      nsk.monitoring.GarbageCollectorMXBean.CollectionCounters.CollectionCounters001.CollectionCounters001
      *      -testMode=server
      *      -MBeanServer=default
    diff --git a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters003/TestDescription.java b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters003/TestDescription.java
    index 20e266f50f1..241b1912d0f 100644
    --- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters003/TestDescription.java
    +++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters003/TestDescription.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2017, 2026, 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,15 +24,19 @@
     
     /*
      * @test
    - * @key randomness
      *
      * @summary converted from VM Testbase nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters003.
      * VM Testbase keywords: [monitoring]
      *
    - * @requires vm.opt.DisableExplicitGC != "true"
      * @library /vmTestbase
      *          /test/lib
    - * @run main/othervm -XX:-UseGCOverheadLimit
    + *
    + * @build jdk.test.whitebox.WhiteBox
    + * @requires vm.opt.DisableExplicitGC != "true"
    + * @requires vm.compMode != "Xcomp"
    + *
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:-UseGCOverheadLimit
      *      nsk.monitoring.GarbageCollectorMXBean.CollectionCounters.CollectionCounters001.CollectionCounters001
      *      -testMode=server
      *      -MBeanServer=custom
    diff --git a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters004/TestDescription.java b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters004/TestDescription.java
    index db5a04cede8..cd0ed660ed0 100644
    --- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters004/TestDescription.java
    +++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters004/TestDescription.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2017, 2026, 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,15 +24,19 @@
     
     /*
      * @test
    - * @key randomness
      *
      * @summary converted from VM Testbase nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters004.
      * VM Testbase keywords: [monitoring]
      *
    - * @requires vm.opt.DisableExplicitGC != "true"
      * @library /vmTestbase
      *          /test/lib
    - * @run main/othervm -XX:-UseGCOverheadLimit
    + *
    + * @build jdk.test.whitebox.WhiteBox
    + * @requires vm.opt.DisableExplicitGC != "true"
    + * @requires vm.compMode != "Xcomp"
    + *
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:-UseGCOverheadLimit
      *      nsk.monitoring.GarbageCollectorMXBean.CollectionCounters.CollectionCounters001.CollectionCounters001
      *      -testMode=proxy
      *      -MBeanServer=default
    diff --git a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters005/TestDescription.java b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters005/TestDescription.java
    index 68c50f026b7..c3c6fac62e7 100644
    --- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters005/TestDescription.java
    +++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters005/TestDescription.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2017, 2026, 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,15 +24,19 @@
     
     /*
      * @test
    - * @key randomness
      *
      * @summary converted from VM Testbase nsk/monitoring/GarbageCollectorMXBean/CollectionCounters/CollectionCounters005.
      * VM Testbase keywords: [monitoring]
      *
    - * @requires vm.opt.DisableExplicitGC != "true"
      * @library /vmTestbase
      *          /test/lib
    - * @run main/othervm -XX:-UseGCOverheadLimit
    + *
    + * @build jdk.test.whitebox.WhiteBox
    + * @requires vm.opt.DisableExplicitGC != "true"
    + * @requires vm.compMode != "Xcomp"
    + *
    + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
    + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:-UseGCOverheadLimit
      *      nsk.monitoring.GarbageCollectorMXBean.CollectionCounters.CollectionCounters001.CollectionCounters001
      *      -testMode=proxy
      *      -MBeanServer=custom
    diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/gc/Algorithms.java b/test/hotspot/jtreg/vmTestbase/nsk/share/gc/Algorithms.java
    index 404dc6498f7..518a932e16b 100644
    --- a/test/hotspot/jtreg/vmTestbase/nsk/share/gc/Algorithms.java
    +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/gc/Algorithms.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2003, 2026, 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
    @@ -73,10 +73,7 @@ public class Algorithms {
              * 

    * * Note that this method can throw Failure if any exception - * is thrown while eating memory. To avoid OOM while allocating - * exception we preallocate it before the lunch starts. It means - * that exception stack trace does not correspond to the place - * where exception is thrown, but points at start of the method. + * is thrown while eating memory. * * This method uses nsk.share.test.Stresser class to control * it's execution. Consumed number of iterations depends on diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/gc/gp/GarbageUtils.java b/test/hotspot/jtreg/vmTestbase/nsk/share/gc/gp/GarbageUtils.java index 1c7a8c6172c..529b299fd15 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/gc/gp/GarbageUtils.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/gc/gp/GarbageUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2026, 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 @@ -181,10 +181,7 @@ public final class GarbageUtils { * Eat memory using default(byte[]) garbage producer. * * Note that this method can throw Failure if any exception - * is thrown while eating memory. To avoid OOM while allocating - * exception we preallocate it before the lunch starts. It means - * that exception stack trace does not correspond to the place - * where exception is thrown, but points at start of the method. + * is thrown while eating memory. * * @param stresser stresser * @param initialFactor determines which portion of initial memory initial chunk will be @@ -200,10 +197,7 @@ public final class GarbageUtils { * Eat memory using given garbage producer. * * Note that this method can throw Failure if any exception - * is thrown while eating memory. To avoid OOM while allocating - * exception we preallocate it before the lunch starts. It means - * that exception stack trace does not correspond to the place - * where exception is thrown, but points at start of the method. + * is thrown while eating memory. * * @param stresser stresser to use * @param gp garbage producer @@ -270,10 +264,7 @@ public final class GarbageUtils { * Eat memory using given garbage producer. * * Note that this method can throw Failure if any exception - * is thrown while eating memory. To avoid OOM while allocating - * exception we preallocate it before the lunch starts. It means - * that exception stack trace does not correspond to the place - * where exception is thrown, but points at start of the method. + * is thrown while eating memory. * * @param stresser stresser to use * @param gp garbage producer diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index addcc8830af..9cfc23ea8da 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -1,6 +1,6 @@ ########################################################################### # -# Copyright (c) 2009, 2025, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2009, 2026, 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 @@ -561,8 +561,6 @@ java/net/MulticastSocket/Test.java 7145658,8308807 # jdk_nio -java/nio/channels/AsyncCloseAndInterrupt.java 8368290 macosx-26.0.1 - java/nio/channels/DatagramChannel/AdaptorMulticasting.java 8308807,8144003 aix-ppc64,macosx-all java/nio/channels/DatagramChannel/AfterDisconnect.java 8308807 aix-ppc64 java/nio/channels/DatagramChannel/ManySourcesAndTargets.java 8264385 macosx-aarch64 diff --git a/test/jdk/com/sun/net/httpserver/ClearTextServerSSL.java b/test/jdk/com/sun/net/httpserver/ClearTextServerSSL.java index 75e4f3fcf45..896f02b178d 100644 --- a/test/jdk/com/sun/net/httpserver/ClearTextServerSSL.java +++ b/test/jdk/com/sun/net/httpserver/ClearTextServerSSL.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2026, 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 @@ -79,7 +79,7 @@ public class ClearTextServerSSL { @Test public void test() throws Exception { - var sslContext = new SimpleSSLContext().get(); + var sslContext = SimpleSSLContext.findSSLContext(); var handler = new TestHandler(); var server = HttpServer.create(new InetSocketAddress(LOOPBACK_ADDR, 0), 0); server.createContext(path(""), handler); diff --git a/test/jdk/java/awt/font/TextLayout/TestGetPixelBoundsWithColors.java b/test/jdk/java/awt/font/TextLayout/TestGetPixelBoundsWithColors.java new file mode 100644 index 00000000000..2a2140c2ebf --- /dev/null +++ b/test/jdk/java/awt/font/TextLayout/TestGetPixelBoundsWithColors.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2026, 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. + */ + +/* + * @test + * @bug 6562639 + * @summary Verify correct getPixelBounds() behavior regardless of text color. + */ + +import java.awt.Color; +import java.awt.Font; +import java.awt.Rectangle; +import java.awt.font.FontRenderContext; +import java.awt.font.TextAttribute; +import java.awt.font.TextLayout; +import java.awt.geom.Rectangle2D; +import java.util.HashMap; +import java.util.Map; + +public class TestGetPixelBoundsWithColors { + + private static final Color TRANSPARENT_BLACK = new Color(0, 0, 0, 0); + private static final Color TRANSPARENT_WHITE = new Color(255, 255, 255, 0); + + public static void main(String[] args) throws Exception { + + Color[] colors = new Color[] { + Color.WHITE, Color.BLACK, Color.YELLOW, Color.RED, Color.GREEN, + Color.GRAY, Color.LIGHT_GRAY, Color.DARK_GRAY, Color.PINK, + Color.CYAN, Color.MAGENTA, Color.BLUE, null + }; + + for (Color color : colors) { + test(color); + } + + testTransparent(TRANSPARENT_BLACK); + testTransparent(TRANSPARENT_WHITE); + } + + private static void test(Color c) { + Map< TextAttribute, Object > underline = new HashMap<>(); + underline.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); + Font font1 = new Font(Font.DIALOG, Font.PLAIN, 60).deriveFont(underline); + Map< TextAttribute, Object > foreground = new HashMap<>(); + foreground.put(TextAttribute.FOREGROUND, c); + Font font2 = font1.deriveFont(foreground); + FontRenderContext frc = new FontRenderContext(null, true, true); + TextLayout layout1 = new TextLayout("TEST", font1, frc); + TextLayout layout2 = new TextLayout("TEST", font2, frc); + Rectangle r1 = layout1.getPixelBounds(frc, 0, 0); + Rectangle r2 = layout2.getPixelBounds(frc, 0, 0); + if (!r1.equals(r2)) { + throw new RuntimeException("For color " + c + ", " + r1 + " != " + r2); + } + Rectangle2D bounds = layout1.getBounds(); + if (Math.abs(bounds.getX() - r1.x) > 3 || + Math.abs(bounds.getY() - r1.y) > 3 || + Math.abs(bounds.getWidth() - r1.width) > 6 || + Math.abs(bounds.getHeight() - r1.height) > 6) { + throw new RuntimeException("For color " + c + ", pixel bounds " + + r1 + " not similar to " + bounds); + } + } + + private static void testTransparent(Color c) { + Font font1 = new Font(Font.DIALOG, Font.PLAIN, 60); + Map< TextAttribute, Object > attributes = new HashMap<>(); + attributes.put(TextAttribute.FOREGROUND, c); + Font font2 = font1.deriveFont(attributes); + FontRenderContext frc = new FontRenderContext(null, true, true); + TextLayout layout = new TextLayout("TEST", font2, frc); + Rectangle r = layout.getPixelBounds(frc, 0, 0); + if (!r.isEmpty()) { + throw new RuntimeException("Expected empty pixel bounds for " + c + " but got " + r); + } + } +} diff --git a/test/jdk/java/io/File/GetXSpace.java b/test/jdk/java/io/File/GetXSpace.java index 96ce4ede1b2..f1529c18fb2 100644 --- a/test/jdk/java/io/File/GetXSpace.java +++ b/test/jdk/java/io/File/GetXSpace.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, 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 @@ -44,7 +44,6 @@ import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import jdk.test.lib.Platform; -import jdk.test.lib.Platform; import static java.lang.System.err; import static java.lang.System.out; @@ -103,16 +102,11 @@ public class GetXSpace { private final long free; private final long available; - Space(String name) { + Space(String name) throws IOException { this.name = name; long[] sizes = new long[4]; if (Platform.isWindows() && isCDDrive(name)) { - try { - getCDDriveSpace(name, sizes); - } catch (IOException e) { - e.printStackTrace(); - throw new RuntimeException("can't get CDDrive sizes"); - } + getCDDriveSpace(name, sizes); } else { if (getSpace(name, sizes)) System.err.println("WARNING: total space is estimated"); @@ -170,7 +164,7 @@ public class GetXSpace { return al; } - private static void compare(Space s) { + private static void compare(Space s) throws IOException { File f = new File(s.name()); long ts = f.getTotalSpace(); long fs = f.getFreeSpace(); @@ -318,7 +312,7 @@ public class GetXSpace { } } - private static int testFile(Path dir) { + private static int testFile(Path dir) throws IOException { String dirName = dir.toString(); out.format("--- Testing %s%n", dirName); compare(new Space(dir.getRoot().toString())); @@ -333,10 +327,11 @@ public class GetXSpace { return fail != 0 ? 1 : 0; } - private static int testVolumes() { + private static int testVolumes() throws IOException { out.println("--- Testing volumes"); // Find all of the partitions on the machine and verify that the sizes - // returned by File::getXSpace are equivalent to those from getSpace or getCDDriveSpace + // returned by File::getXSpace are equivalent to those from getSpace + // or getCDDriveSpace ArrayList l; try { l = paths(); @@ -350,7 +345,18 @@ public class GetXSpace { throw new RuntimeException("no partitions?"); for (var p : l) { - Space s = new Space(p); + Space s; + try { + s = new Space(p); + } catch (IOException x) { + // Avoid failing for transient file systems on Windows + if (Platform.isWindows()) { + File f = new File(p); + if (!f.exists()) + continue; + } + throw new IOException("Failure for volume " + p, x); + } compare(s); compareZeroNonExist(); compareZeroExist(); @@ -408,19 +414,19 @@ public class GetXSpace { // size[2] free space: number of free bytes in the volume // size[3] usable space: number of bytes available to the caller // - private static native boolean getSpace0(String root, long[] space); + private static native boolean getSpace0(String root, long[] space) + throws IOException; private static native boolean isCDDrive(String root); - private static boolean getSpace(String root, long[] space) { + private static boolean getSpace(String root, long[] space) + throws IOException { try { return getSpace0(root, space); - } catch (RuntimeException e) { + } catch (IOException e) { File f = new File(root); - boolean exists = f.exists(); - boolean readable = f.canRead(); System.err.printf("getSpace0 failed for %s (%s, %s)%n", - root, exists, readable); + root, f.exists(), f.canRead()); throw e; } } diff --git a/test/jdk/java/io/File/libGetXSpace.c b/test/jdk/java/io/File/libGetXSpace.c index 59805e0adcb..9297721b8f4 100644 --- a/test/jdk/java/io/File/libGetXSpace.c +++ b/test/jdk/java/io/File/libGetXSpace.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, 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 @@ -85,7 +85,7 @@ Java_GetXSpace_getSpace0 BOOL hres = pfnGetDiskSpaceInformation(path, &diskSpaceInfo); (*env)->ReleaseStringChars(env, root, strchars); if (FAILED(hres)) { - JNU_ThrowByNameWithLastError(env, "java/lang/RuntimeException", + JNU_ThrowByNameWithLastError(env, "java/io/IOException", "GetDiskSpaceInformationW"); return totalSpaceIsEstimated; } @@ -113,7 +113,7 @@ Java_GetXSpace_getSpace0 &totalNumberOfBytes, &totalNumberOfFreeBytes); (*env)->ReleaseStringChars(env, root, strchars); if (FAILED(hres)) { - JNU_ThrowByNameWithLastError(env, "java/lang/RuntimeException", + JNU_ThrowByNameWithLastError(env, "java/io/IOException", "GetDiskFreeSpaceExW"); return totalSpaceIsEstimated; } @@ -131,8 +131,7 @@ Java_GetXSpace_getSpace0 char* chars = (char*)malloc((len + 1)*sizeof(char)); if (chars == NULL) { (*env)->ReleaseStringChars(env, root, strchars); - JNU_ThrowByNameWithLastError(env, "java/lang/RuntimeException", - "malloc"); + JNU_ThrowOutOfMemoryError(env, "malloc"); return JNI_FALSE; } @@ -146,7 +145,7 @@ Java_GetXSpace_getSpace0 int result = statfs(chars, &buf); free(chars); if (result < 0) { - JNU_ThrowByNameWithLastError(env, "java/lang/RuntimeException", + JNU_ThrowByNameWithLastError(env, "java/io/IOException", strerror(errno)); return totalSpaceIsEstimated; } diff --git a/test/jdk/java/lang/RuntimeTests/exec/SleepyCat.java b/test/jdk/java/lang/RuntimeTests/exec/SleepyCat.java index 7e6e9837c40..9ab4ba33f45 100644 --- a/test/jdk/java/lang/RuntimeTests/exec/SleepyCat.java +++ b/test/jdk/java/lang/RuntimeTests/exec/SleepyCat.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, 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 @@ -66,26 +66,19 @@ public class SleepyCat { * @param pids the processes to dump status for */ static void dumpState(Process... pids) { - if (!System.getProperty("os.name").contains("SunOS")) { - return; - } try { String[] psArgs = {"ps", "-elf"}; - Process ps = new ProcessBuilder(psArgs).inheritIO().start(); - ps.waitFor(); - String[] sfiles = {"pfiles", "self"}; - Process fds = new ProcessBuilder(sfiles).inheritIO().start(); - fds.waitFor(); + try (Process ps = new ProcessBuilder(psArgs).inheritIO().start()) { + ps.waitFor(); + } for (Process p : pids) { if (p == null) continue; - String[] pfiles = {"pfiles", Long.toString(p.pid())}; - fds = new ProcessBuilder(pfiles).inheritIO().start(); - fds.waitFor(); - String[] pstack = {"pstack", Long.toString(p.pid())}; - fds = new ProcessBuilder(pstack).inheritIO().start(); - fds.waitFor(); + String[] pfiles = {"lsof", "-p", Long.toString(p.pid())}; + try (Process fds = new ProcessBuilder(pfiles).inheritIO().start()) { + fds.waitFor(); + } } } catch (IOException | InterruptedException i) { i.printStackTrace(); diff --git a/test/jdk/java/lang/RuntimeTests/exec/TEST.properties b/test/jdk/java/lang/RuntimeTests/exec/TEST.properties new file mode 100644 index 00000000000..c7e8a6850ca --- /dev/null +++ b/test/jdk/java/lang/RuntimeTests/exec/TEST.properties @@ -0,0 +1 @@ +maxOutputSize=6000000 diff --git a/test/jdk/java/lang/Thread/virtual/stress/ParkAfterTimedPark.java b/test/jdk/java/lang/Thread/virtual/stress/ParkAfterTimedPark.java new file mode 100644 index 00000000000..1b173271a79 --- /dev/null +++ b/test/jdk/java/lang/Thread/virtual/stress/ParkAfterTimedPark.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2025, 2026, 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. + */ + +/* + * @test id=parked + * @bug 8369227 + * @summary Stress test untimed park after a timed park when a thread is unparked around the + * same time that the timeout expires. + * @library /test/lib + * @run main/othervm --enable-native-access=ALL-UNNAMED ParkAfterTimedPark 200 false + */ + +/* + * @test id=pinned + * @summary Stress test untimed park, while pinned, and after a timed park when a thread is + * unparked around the same time that the timeout expires. + * @library /test/lib + * @run main/othervm --enable-native-access=ALL-UNNAMED ParkAfterTimedPark 200 true + */ + +import java.time.Instant; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; +import jdk.test.lib.thread.VThreadPinner; + +public class ParkAfterTimedPark { + public static void main(String[] args) throws Exception { + int iterations = (args.length > 0) ? Integer.parseInt(args[0]) : 100; + boolean pinned = (args.length > 1) ? Boolean.parseBoolean(args[1]) : false; + + for (int i = 1; i <= iterations; i++) { + System.out.println(Instant.now() + " => " + i + " of " + iterations); + for (int timeout = 1; timeout <= 10; timeout++) { + test(timeout, true); + } + } + } + + /** + * Creates two virtual threads. The first does a timed-park for the given time, + * then parks in CountDownLatch.await. A second virtual thread unparks the first + * around the same time that the timeout for the first expires. + */ + private static void test(int millis, boolean pinned) throws Exception { + long nanos = TimeUnit.MILLISECONDS.toNanos(millis); + + var finish = new CountDownLatch(1); + + Thread thread1 = Thread.startVirtualThread(() -> { + LockSupport.parkNanos(nanos); + boolean done = false; + while (!done) { + try { + if (pinned) { + VThreadPinner.runPinned(() -> { + finish.await(); + }); + } else { + finish.await(); + } + done = true; + } catch (InterruptedException e) { } + } + }); + + Thread thread2 = Thread.startVirtualThread(() -> { + int delta = ThreadLocalRandom.current().nextInt(millis); + boolean done = false; + while (!done) { + try { + Thread.sleep(millis - delta); + done = true; + } catch (InterruptedException e) { } + } + LockSupport.unpark(thread1); + }); + + // wait for first thread to park before count down + await(thread1, Thread.State.WAITING); + finish.countDown(); + + thread1.join(); + thread2.join(); + } + + /** + * Waits for the given thread to reach a given state. + */ + private static void await(Thread thread, Thread.State expectedState) throws Exception { + Thread.State state = thread.getState(); + while (state != expectedState) { + if (state == Thread.State.TERMINATED) + throw new RuntimeException("Thread has terminated"); + Thread.sleep(10); + state = thread.getState(); + } + } +} diff --git a/test/jdk/java/lang/Thread/virtual/stress/TimedWaitALot.java b/test/jdk/java/lang/Thread/virtual/stress/TimedWaitALot.java index 6a81a7c5fee..704e299ad8b 100644 --- a/test/jdk/java/lang/Thread/virtual/stress/TimedWaitALot.java +++ b/test/jdk/java/lang/Thread/virtual/stress/TimedWaitALot.java @@ -94,17 +94,20 @@ public class TimedWaitALot { // start thread to Object.notifyAll at around time that the timeout expires if (notify) { - if (ThreadLocalRandom.current().nextBoolean()) { - synchronized (lock) { + executor.submit(() -> { + if (ThreadLocalRandom.current().nextBoolean()) { + synchronized (lock) { + sleepLessThan(timeout); + lock.notifyAll(); + } + } else { sleepLessThan(timeout); - lock.notifyAll(); + synchronized (lock) { + lock.notifyAll(); + } } - } else { - sleepLessThan(timeout); - synchronized (lock) { - lock.notifyAll(); - } - } + return null; + }); } // start thread to interrupt first thread at around time that the timeout expires diff --git a/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTest.java b/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTest.java index 2dc6963a63e..8965a942153 100644 --- a/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTest.java +++ b/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2026, 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 @@ -142,16 +142,12 @@ public class HTTPTest { } static { - try { - HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { - public boolean verify(String hostname, SSLSession session) { - return true; - } - }); - SSLContext.setDefault(new SimpleSSLContext().get()); - } catch (IOException ex) { - throw new ExceptionInInitializerError(ex); - } + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }); + SSLContext.setDefault(SimpleSSLContext.findSSLContext()); } static final Logger logger = Logger.getLogger ("com.sun.net.httpserver"); diff --git a/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTestClient.java b/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTestClient.java index 3f436ef6d02..57790da171f 100644 --- a/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTestClient.java +++ b/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTestClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2026, 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 @@ -112,7 +112,7 @@ public class HTTPTestClient extends HTTPTest { // anything here. Otherwise it could look like: // HttpsURLConnection httpsConn = (HttpsURLConnection)conn; // httpsConn.setSSLSocketFactory( - // new SimpleSSLContext().get().getSocketFactory()); + // SimpleSSLContext.findSSLContext().getSocketFactory()); } } diff --git a/test/jdk/java/net/URLPermission/URLTest.java b/test/jdk/java/net/URLPermission/URLTest.java index 907ba6072ec..9d1b4e840e6 100644 --- a/test/jdk/java/net/URLPermission/URLTest.java +++ b/test/jdk/java/net/URLPermission/URLTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2026, 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 @@ -223,7 +223,7 @@ public class URLTest { static HttpsServer httpsServer; static HttpContext c, cs; static ExecutorService e, es; - static SSLContext ctx; + private static final SSLContext ctx = SimpleSSLContext.findSSLContext(); static int httpPort; static int httpsPort; static String httpAuth; @@ -243,8 +243,6 @@ public class URLTest { es = Executors.newCachedThreadPool(); httpServer.setExecutor(e); httpsServer.setExecutor(es); - - ctx = new SimpleSSLContext().get(); httpsServer.setHttpsConfigurator(new HttpsConfigurator (ctx)); httpServer.start(); diff --git a/test/jdk/java/net/httpclient/ALPNProxyFailureTest.java b/test/jdk/java/net/httpclient/ALPNProxyFailureTest.java index ca2e95b70fe..4dedfed97b1 100644 --- a/test/jdk/java/net/httpclient/ALPNProxyFailureTest.java +++ b/test/jdk/java/net/httpclient/ALPNProxyFailureTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -44,14 +44,9 @@ import java.net.http.HttpClient; public class ALPNProxyFailureTest extends ALPNFailureTest { - static final SSLContext context; + private static final SSLContext context = SimpleSSLContext.findSSLContext(); static { - try { - context = new SimpleSSLContext().get(); - SSLContext.setDefault(context); - } catch (Exception x) { - throw new ExceptionInInitializerError(x); - } + SSLContext.setDefault(context); } public static void main(String[] args) throws Exception{ diff --git a/test/jdk/java/net/httpclient/AbstractNoBody.java b/test/jdk/java/net/httpclient/AbstractNoBody.java index 9cc26704bb5..d0908a6e4cd 100644 --- a/test/jdk/java/net/httpclient/AbstractNoBody.java +++ b/test/jdk/java/net/httpclient/AbstractNoBody.java @@ -53,7 +53,7 @@ import static org.testng.Assert.assertEquals; public abstract class AbstractNoBody implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -186,9 +186,6 @@ public abstract class AbstractNoBody implements HttpServerAdapters { public void setup() throws Exception { printStamp(START, "setup"); HttpServerAdapters.enableServerLogging(); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); // HTTP/1.1 HttpTestHandler h1_fixedLengthNoBodyHandler = new FixedLengthNoBodyHandler(); diff --git a/test/jdk/java/net/httpclient/AbstractThrowingPublishers.java b/test/jdk/java/net/httpclient/AbstractThrowingPublishers.java index 0fb6889c198..992b215ade0 100644 --- a/test/jdk/java/net/httpclient/AbstractThrowingPublishers.java +++ b/test/jdk/java/net/httpclient/AbstractThrowingPublishers.java @@ -82,7 +82,7 @@ import org.junit.jupiter.api.extension.TestWatcher; public abstract class AbstractThrowingPublishers implements HttpServerAdapters { - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] static HttpTestServer httpsTestServer; // HTTPS/1.1 static HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -757,10 +757,6 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { System.out.println(now() + "setup"); System.err.println(now() + "setup"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler(); HttpTestHandler h1_chunkHandler = new HTTP_ChunkedHandler(); diff --git a/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java b/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java index cebcbf2e292..ddd9c52fc58 100644 --- a/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java +++ b/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java @@ -98,7 +98,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; @@ -108,7 +107,7 @@ import org.junit.jupiter.api.extension.TestWatcher; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public abstract class AbstractThrowingPushPromises implements HttpServerAdapters { - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static HttpTestServer http2TestServer; // HTTP/2 ( h2c ) static HttpTestServer https2TestServer; // HTTP/2 ( h2 ) static HttpTestServer http3TestServer; // HTTP/3 ( h3 ) @@ -758,10 +757,6 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters @BeforeAll public static void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/2 HttpTestHandler fixedLengthHandler = new HTTP_FixedLengthHandler(); HttpTestHandler chunkedHandler = new HTTP_ChunkedHandler(); diff --git a/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java b/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java index d0eda646a4c..33063775243 100644 --- a/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java +++ b/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java @@ -81,7 +81,7 @@ import org.junit.jupiter.api.extension.TestWatcher; public abstract class AbstractThrowingSubscribers implements HttpServerAdapters { - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] static HttpTestServer httpsTestServer; // HTTPS/1.1 static HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -821,10 +821,6 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters System.out.println(now() + "setup"); System.err.println(now() + "setup"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - System.out.println(now() + "HTTP/1.1 server created"); // HTTP/1.1 diff --git a/test/jdk/java/net/httpclient/AggregateRequestBodyTest.java b/test/jdk/java/net/httpclient/AggregateRequestBodyTest.java index 8ec3b256e62..608b6489181 100644 --- a/test/jdk/java/net/httpclient/AggregateRequestBodyTest.java +++ b/test/jdk/java/net/httpclient/AggregateRequestBodyTest.java @@ -93,7 +93,7 @@ import static org.testng.Assert.expectThrows; public class AggregateRequestBodyTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer http1TestServer; // HTTP/1.1 ( http ) HttpTestServer https1TestServer; // HTTPS/1.1 ( https ) HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -855,10 +855,6 @@ public class AggregateRequestBodyTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - HttpTestHandler handler = new HttpTestEchoHandler(); http1TestServer = HttpTestServer.create(HTTP_1_1); http1TestServer.addHandler(handler, "/http1/echo/"); diff --git a/test/jdk/java/net/httpclient/AltServiceUsageTest.java b/test/jdk/java/net/httpclient/AltServiceUsageTest.java index 673357a59aa..41f3aef9bd1 100644 --- a/test/jdk/java/net/httpclient/AltServiceUsageTest.java +++ b/test/jdk/java/net/httpclient/AltServiceUsageTest.java @@ -59,7 +59,7 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY; */ public class AltServiceUsageTest implements HttpServerAdapters { - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private HttpTestServer originServer; private HttpTestServer altServer; @@ -67,11 +67,6 @@ public class AltServiceUsageTest implements HttpServerAdapters { @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } - // attempt to create an HTTP/3 server, an HTTP/2 server, and a // DatagramChannel bound to the same port as the HTTP/2 server int count = 0; diff --git a/test/jdk/java/net/httpclient/AsFileDownloadTest.java b/test/jdk/java/net/httpclient/AsFileDownloadTest.java index 42567602dff..88bf95dab02 100644 --- a/test/jdk/java/net/httpclient/AsFileDownloadTest.java +++ b/test/jdk/java/net/httpclient/AsFileDownloadTest.java @@ -90,7 +90,7 @@ import static org.testng.Assert.fail; */ public class AsFileDownloadTest { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpsServer httpsTestServer; // HTTPS/1.1 Http2TestServer http2TestServer; // HTTP/2 ( h2c ) @@ -351,10 +351,6 @@ public class AsFileDownloadTest { //ch.setLevel(Level.ALL); //logger.addHandler(ch); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); httpTestServer = HttpServer.create(sa, 0); httpTestServer.createContext("/http1/afdt", new Http1FileDispoHandler()); diff --git a/test/jdk/java/net/httpclient/AsyncExecutorShutdown.java b/test/jdk/java/net/httpclient/AsyncExecutorShutdown.java index 5338d64892b..14ed4f63124 100644 --- a/test/jdk/java/net/httpclient/AsyncExecutorShutdown.java +++ b/test/jdk/java/net/httpclient/AsyncExecutorShutdown.java @@ -93,7 +93,7 @@ public class AsyncExecutorShutdown implements HttpServerAdapters { static final Random RANDOM = RandomFactory.getRandom(); ExecutorService readerService; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 6 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -412,9 +412,6 @@ public class AsyncExecutorShutdown implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { out.println("\n**** Setup ****\n"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); readerService = Executors.newCachedThreadPool(); httpTestServer = HttpTestServer.create(HTTP_1_1); diff --git a/test/jdk/java/net/httpclient/AsyncShutdownNow.java b/test/jdk/java/net/httpclient/AsyncShutdownNow.java index 2617b60ee1c..56b0378cf66 100644 --- a/test/jdk/java/net/httpclient/AsyncShutdownNow.java +++ b/test/jdk/java/net/httpclient/AsyncShutdownNow.java @@ -97,7 +97,7 @@ public class AsyncShutdownNow implements HttpServerAdapters { static final Random RANDOM = RandomFactory.getRandom(); ExecutorService readerService; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -406,9 +406,6 @@ public class AsyncShutdownNow implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { out.println("\n**** Setup ****\n"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); readerService = Executors.newCachedThreadPool(); httpTestServer = HttpTestServer.create(HTTP_1_1); diff --git a/test/jdk/java/net/httpclient/AuthFilterCacheTest.java b/test/jdk/java/net/httpclient/AuthFilterCacheTest.java index 32026db57fb..6d64caa1950 100644 --- a/test/jdk/java/net/httpclient/AuthFilterCacheTest.java +++ b/test/jdk/java/net/httpclient/AuthFilterCacheTest.java @@ -75,15 +75,10 @@ public class AuthFilterCacheTest implements HttpServerAdapters { static final int REQUEST_COUNT = 5; static final int URI_COUNT = 8; static final CyclicBarrier barrier = new CyclicBarrier(REQUEST_COUNT * URI_COUNT); - static final SSLContext context; + private static final SSLContext context = jdk.test.lib.net.SimpleSSLContext.findSSLContext(); static { - try { - context = new jdk.test.lib.net.SimpleSSLContext().get(); - SSLContext.setDefault(context); - } catch (Exception x) { - throw new ExceptionInInitializerError(x); - } + SSLContext.setDefault(context); } HttpTestServer http1Server; diff --git a/test/jdk/java/net/httpclient/BasicAuthTest.java b/test/jdk/java/net/httpclient/BasicAuthTest.java index 35d5a7803d6..fc1f1d4e5aa 100644 --- a/test/jdk/java/net/httpclient/BasicAuthTest.java +++ b/test/jdk/java/net/httpclient/BasicAuthTest.java @@ -71,7 +71,7 @@ public class BasicAuthTest implements HttpServerAdapters { ExecutorService e = Executors.newCachedThreadPool(); Handler h = new Handler(); SSLContext sslContext = secure || version == Version.HTTP_3 - ? new SimpleSSLContext().get() : null; + ? SimpleSSLContext.findSSLContext() : null; HttpTestServer server = HttpTestServer.create(version, sslContext, e); HttpTestContext serverContext = server.addHandler(h,"/test/"); ServerAuth sa = new ServerAuth("foo realm"); diff --git a/test/jdk/java/net/httpclient/BasicHTTP2Test.java b/test/jdk/java/net/httpclient/BasicHTTP2Test.java index 8233da37c42..586673d62ab 100644 --- a/test/jdk/java/net/httpclient/BasicHTTP2Test.java +++ b/test/jdk/java/net/httpclient/BasicHTTP2Test.java @@ -71,7 +71,7 @@ import static org.testng.Assert.assertTrue; public class BasicHTTP2Test implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer https2TestServer; // HTTP/2 ( h2 ) String https2URI; DatagramSocket udp; @@ -239,10 +239,6 @@ public class BasicHTTP2Test implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/2 HttpTestHandler handler = new Handler(); HttpTestHandler h3Handler = new Handler(); diff --git a/test/jdk/java/net/httpclient/BasicHTTP3Test.java b/test/jdk/java/net/httpclient/BasicHTTP3Test.java index 32dd1dea832..4508b32e544 100644 --- a/test/jdk/java/net/httpclient/BasicHTTP3Test.java +++ b/test/jdk/java/net/httpclient/BasicHTTP3Test.java @@ -78,7 +78,7 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.ALT_SVC; */ public class BasicHTTP3Test implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer https2TestServer; // HTTP/2 ( h2 ) String https2URI; HttpTestServer h3TestServer; // HTTP/2 ( h2 + h3) @@ -343,10 +343,6 @@ public class BasicHTTP3Test implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } https2TestServer = HttpTestServer.create(HTTP_2, sslContext); https2TestServer.addHandler(new Handler(), "/https2/test/"); https2URI = "https://" + https2TestServer.serverAuthority() + "/https2/test/x"; diff --git a/test/jdk/java/net/httpclient/BasicRedirectTest.java b/test/jdk/java/net/httpclient/BasicRedirectTest.java index a19b1444ac6..d79c39fe47a 100644 --- a/test/jdk/java/net/httpclient/BasicRedirectTest.java +++ b/test/jdk/java/net/httpclient/BasicRedirectTest.java @@ -68,7 +68,7 @@ import static org.testng.Assert.assertTrue; public class BasicRedirectTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -270,10 +270,6 @@ public class BasicRedirectTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new BasicHttpRedirectHandler(), "/http1/same/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/same/redirect"; diff --git a/test/jdk/java/net/httpclient/BufferSize1Test.java b/test/jdk/java/net/httpclient/BufferSize1Test.java index 842dc06a630..e4f2b998cc7 100644 --- a/test/jdk/java/net/httpclient/BufferSize1Test.java +++ b/test/jdk/java/net/httpclient/BufferSize1Test.java @@ -79,7 +79,7 @@ class BufferSize1Test implements HttpServerAdapters { void test(Version version, boolean secure) throws Exception { // Create the server - var sslContext = secure || HTTP_3.equals(version) ? new SimpleSSLContext().get() : null; + var sslContext = secure || HTTP_3.equals(version) ? SimpleSSLContext.findSSLContext() : null; try (var server = switch (version) { case HTTP_1_1, HTTP_2 -> HttpTestServer.create(version, sslContext); case HTTP_3 -> HttpTestServer.create(HTTP_3_URI_ONLY, sslContext); diff --git a/test/jdk/java/net/httpclient/CancelRequestTest.java b/test/jdk/java/net/httpclient/CancelRequestTest.java index 23e4a042179..86e06bb78f7 100644 --- a/test/jdk/java/net/httpclient/CancelRequestTest.java +++ b/test/jdk/java/net/httpclient/CancelRequestTest.java @@ -93,7 +93,7 @@ public class CancelRequestTest implements HttpServerAdapters { private static final Random random = RandomFactory.getRandom(); - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -642,10 +642,6 @@ public class CancelRequestTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpTestHandler h1_chunkHandler = new HTTPSlowHandler(); httpTestServer = HttpTestServer.create(HTTP_1_1); diff --git a/test/jdk/java/net/httpclient/CancelStreamedBodyTest.java b/test/jdk/java/net/httpclient/CancelStreamedBodyTest.java index e304168ba33..0035a3f4302 100644 --- a/test/jdk/java/net/httpclient/CancelStreamedBodyTest.java +++ b/test/jdk/java/net/httpclient/CancelStreamedBodyTest.java @@ -78,7 +78,7 @@ import static org.testng.Assert.assertTrue; public class CancelStreamedBodyTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -352,10 +352,6 @@ public class CancelStreamedBodyTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpTestHandler h1_chunkHandler = new HTTPSlowHandler(); httpTestServer = HttpTestServer.create(HTTP_1_1); diff --git a/test/jdk/java/net/httpclient/CancelledPartialResponseTest.java b/test/jdk/java/net/httpclient/CancelledPartialResponseTest.java index 41493bbdaff..bb190cfc348 100644 --- a/test/jdk/java/net/httpclient/CancelledPartialResponseTest.java +++ b/test/jdk/java/net/httpclient/CancelledPartialResponseTest.java @@ -85,7 +85,7 @@ public class CancelledPartialResponseTest { URI warmup, h2PartialResponseResetNoError, h2PartialResponseResetError, h2FullResponseResetNoError, h2FullResponseResetError; URI h3PartialResponseStopSending, h3FullResponseStopSending; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static PrintStream err = new PrintStream(System.err); static PrintStream out = System.out; @@ -163,10 +163,6 @@ public class CancelledPartialResponseTest { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - http2TestServer = new Http2TestServer(false, 0); http3TestServer = HttpTestServer.create(Http3DiscoveryMode.HTTP_3_URI_ONLY, sslContext); diff --git a/test/jdk/java/net/httpclient/CancelledResponse.java b/test/jdk/java/net/httpclient/CancelledResponse.java index 1f28ce87221..5449a68418a 100644 --- a/test/jdk/java/net/httpclient/CancelledResponse.java +++ b/test/jdk/java/net/httpclient/CancelledResponse.java @@ -93,11 +93,10 @@ public class CancelledResponse { static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; final ServerSocketFactory factory; - final SSLContext context; + private static final SSLContext context = SimpleSSLContext.findSSLContext(); final boolean useSSL; CancelledResponse(boolean useSSL) throws IOException { this.useSSL = useSSL; - context = new SimpleSSLContext().get(); SSLContext.setDefault(context); factory = useSSL ? SSLServerSocketFactory.getDefault() : ServerSocketFactory.getDefault(); diff --git a/test/jdk/java/net/httpclient/CancelledResponse2.java b/test/jdk/java/net/httpclient/CancelledResponse2.java index dfcdb03f06e..48223e84135 100644 --- a/test/jdk/java/net/httpclient/CancelledResponse2.java +++ b/test/jdk/java/net/httpclient/CancelledResponse2.java @@ -81,7 +81,7 @@ public class CancelledResponse2 implements HttpServerAdapters { URI h3TestServerURI; HttpTestServer h2h3TestServer; HttpTestServer h3TestServer; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); @DataProvider(name = "versions") public Object[][] positive() { @@ -152,8 +152,6 @@ public class CancelledResponse2 implements HttpServerAdapters { @BeforeTest public void setup() throws IOException { - sslContext = new SimpleSSLContext().get(); - h2TestServer = HttpTestServer.create(HTTP_2, sslContext); h2TestServer.addHandler(new CancelledResponseHandler(), "/h2"); h2TestServerURI = URI.create("https://" + h2TestServer.serverAuthority() + "/h2"); diff --git a/test/jdk/java/net/httpclient/ConcurrentResponses.java b/test/jdk/java/net/httpclient/ConcurrentResponses.java index 1cabe461e80..c44452bf4d2 100644 --- a/test/jdk/java/net/httpclient/ConcurrentResponses.java +++ b/test/jdk/java/net/httpclient/ConcurrentResponses.java @@ -89,7 +89,7 @@ import static org.testng.Assert.fail; public class ConcurrentResponses { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpsServer httpsTestServer; // HTTPS/1.1 Http2TestServer http2TestServer; // HTTP/2 ( h2c ) @@ -303,10 +303,6 @@ public class ConcurrentResponses { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); httpTestServer = HttpServer.create(sa, 0); httpTestServer.createContext("/http1/fixed", new Http1FixedHandler()); diff --git a/test/jdk/java/net/httpclient/ContentLengthHeaderTest.java b/test/jdk/java/net/httpclient/ContentLengthHeaderTest.java index d7c77d0690a..75c7c984a6b 100644 --- a/test/jdk/java/net/httpclient/ContentLengthHeaderTest.java +++ b/test/jdk/java/net/httpclient/ContentLengthHeaderTest.java @@ -77,7 +77,7 @@ public class ContentLengthHeaderTest implements HttpServerAdapters { static HttpTestServer testContentLengthServerH2; static HttpTestServer testContentLengthServerH3; static PrintStream testLog = System.err; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpClient hc; URI testContentLengthURIH1; @@ -86,7 +86,6 @@ public class ContentLengthHeaderTest implements HttpServerAdapters { @BeforeTest public void setup() throws IOException, URISyntaxException, InterruptedException { - sslContext = new SimpleSSLContext().get(); testContentLengthServerH1 = HttpTestServer.create(HTTP_1_1); testContentLengthServerH2 = HttpTestServer.create(HTTP_2, sslContext); testContentLengthServerH3 = HttpTestServer.create(HTTP_3, sslContext); diff --git a/test/jdk/java/net/httpclient/CookieHeaderTest.java b/test/jdk/java/net/httpclient/CookieHeaderTest.java index 455b1048b06..cd47262825c 100644 --- a/test/jdk/java/net/httpclient/CookieHeaderTest.java +++ b/test/jdk/java/net/httpclient/CookieHeaderTest.java @@ -83,7 +83,7 @@ import static org.testng.Assert.assertTrue; public class CookieHeaderTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 6 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -194,10 +194,6 @@ public class CookieHeaderTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new CookieValidationHandler(), "/http1/cookie/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/cookie/retry"; diff --git a/test/jdk/java/net/httpclient/CustomRequestPublisher.java b/test/jdk/java/net/httpclient/CustomRequestPublisher.java index c8d33030a06..f26def9a44c 100644 --- a/test/jdk/java/net/httpclient/CustomRequestPublisher.java +++ b/test/jdk/java/net/httpclient/CustomRequestPublisher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -69,7 +69,7 @@ import static org.testng.Assert.fail; public class CustomRequestPublisher implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -339,10 +339,6 @@ public class CustomRequestPublisher implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new HttpTestEchoHandler(), "/http1/echo"); diff --git a/test/jdk/java/net/httpclient/CustomResponseSubscriber.java b/test/jdk/java/net/httpclient/CustomResponseSubscriber.java index e8b5073d9a2..c581491a214 100644 --- a/test/jdk/java/net/httpclient/CustomResponseSubscriber.java +++ b/test/jdk/java/net/httpclient/CustomResponseSubscriber.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -70,7 +70,7 @@ import static org.testng.Assert.assertTrue; public class CustomResponseSubscriber { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpsServer httpsTestServer; // HTTPS/1.1 Http2TestServer http2TestServer; // HTTP/2 ( h2c ) @@ -187,10 +187,6 @@ public class CustomResponseSubscriber { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpHandler h1_fixedLengthHandler = new HTTP1_FixedLengthHandler(); HttpHandler h1_chunkHandler = new HTTP1_ChunkedHandler(); diff --git a/test/jdk/java/net/httpclient/DependentActionsTest.java b/test/jdk/java/net/httpclient/DependentActionsTest.java index 7d903157de8..9a77d377497 100644 --- a/test/jdk/java/net/httpclient/DependentActionsTest.java +++ b/test/jdk/java/net/httpclient/DependentActionsTest.java @@ -94,7 +94,7 @@ import static org.testng.Assert.assertTrue; public class DependentActionsTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -643,10 +643,6 @@ public class DependentActionsTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler(); HttpTestHandler h1_chunkHandler = new HTTP_ChunkedHandler(); diff --git a/test/jdk/java/net/httpclient/DependentPromiseActionsTest.java b/test/jdk/java/net/httpclient/DependentPromiseActionsTest.java index 12903294315..f1b07f7abce 100644 --- a/test/jdk/java/net/httpclient/DependentPromiseActionsTest.java +++ b/test/jdk/java/net/httpclient/DependentPromiseActionsTest.java @@ -98,7 +98,7 @@ import static org.testng.Assert.assertTrue; public class DependentPromiseActionsTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer http2TestServer; // HTTP/2 ( h2c ) HttpTestServer https2TestServer; // HTTP/2 ( h2 ) HttpTestServer http3TestServer; // HTTP/3 ( h3 ) @@ -701,10 +701,6 @@ public class DependentPromiseActionsTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/2 HttpTestHandler fixedLengthHandler = new HTTP_FixedLengthHandler(); HttpTestHandler chunkedHandler = new HTTP_ChunkedHandler(); diff --git a/test/jdk/java/net/httpclient/DigestEchoClient.java b/test/jdk/java/net/httpclient/DigestEchoClient.java index 10add19cb94..6df4ccac9fb 100644 --- a/test/jdk/java/net/httpclient/DigestEchoClient.java +++ b/test/jdk/java/net/httpclient/DigestEchoClient.java @@ -165,14 +165,9 @@ public class DigestEchoClient { static final AtomicInteger NC = new AtomicInteger(); static final Random random = new Random(); - static final SSLContext context; + private static final SSLContext context = SimpleSSLContext.findSSLContext(); static { - try { - context = new SimpleSSLContext().get(); - SSLContext.setDefault(context); - } catch (Exception x) { - throw new ExceptionInInitializerError(x); - } + SSLContext.setDefault(context); } static final List BOOLEANS = List.of(true, false); diff --git a/test/jdk/java/net/httpclient/DurationOverflowTest.java b/test/jdk/java/net/httpclient/DurationOverflowTest.java index bc836a7c5dd..1beb31f74e5 100644 --- a/test/jdk/java/net/httpclient/DurationOverflowTest.java +++ b/test/jdk/java/net/httpclient/DurationOverflowTest.java @@ -102,15 +102,7 @@ public class DurationOverflowTest { private static final Logger LOGGER = Utils.getDebugLogger(CLASS_NAME::toString, Utils.DEBUG); - private static final SSLContext SSL_CONTEXT = createSslContext(); - - private static SSLContext createSslContext() { - try { - return new SimpleSSLContext().get(); - } catch (IOException exception) { - throw new UncheckedIOException(exception); - } - } + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); private static final List INFRAS = loadInfras(); diff --git a/test/jdk/java/net/httpclient/EmptyAuthenticate.java b/test/jdk/java/net/httpclient/EmptyAuthenticate.java index e445a974ad0..81bbbf3ca5b 100644 --- a/test/jdk/java/net/httpclient/EmptyAuthenticate.java +++ b/test/jdk/java/net/httpclient/EmptyAuthenticate.java @@ -56,18 +56,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class EmptyAuthenticate { - private static final SSLContext SSL_CONTEXT = createSslContext(); + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); private static final String WWW_AUTH_HEADER_NAME = "WWW-Authenticate"; - private static SSLContext createSslContext() { - try { - return new SimpleSSLContext().get(); - } catch (IOException exception) { - throw new RuntimeException(exception); - } - } - @ParameterizedTest @MethodSource("args") void test(Version version, boolean secure) throws Exception { diff --git a/test/jdk/java/net/httpclient/EncodedCharsInURI.java b/test/jdk/java/net/httpclient/EncodedCharsInURI.java index 91bace42699..eab9a29b172 100644 --- a/test/jdk/java/net/httpclient/EncodedCharsInURI.java +++ b/test/jdk/java/net/httpclient/EncodedCharsInURI.java @@ -88,7 +88,7 @@ import static org.testng.Assert.assertTrue; public class EncodedCharsInURI implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -311,10 +311,6 @@ public class EncodedCharsInURI implements HttpServerAdapters { public void setup() throws Exception { out.println(now() + "begin setup"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler(); HttpTestHandler h1_chunkHandler = new HTTP_ChunkedHandler(); diff --git a/test/jdk/java/net/httpclient/EscapedOctetsInURI.java b/test/jdk/java/net/httpclient/EscapedOctetsInURI.java index d9d8ba1ddd7..abb0d7d8541 100644 --- a/test/jdk/java/net/httpclient/EscapedOctetsInURI.java +++ b/test/jdk/java/net/httpclient/EscapedOctetsInURI.java @@ -69,7 +69,7 @@ import static org.testng.Assert.assertEquals; public class EscapedOctetsInURI implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -267,10 +267,6 @@ public class EscapedOctetsInURI implements HttpServerAdapters { public void setup() throws Exception { out.println(now() + "begin setup"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new HttpASCIIUriStringHandler(), "/http1/get"); diff --git a/test/jdk/java/net/httpclient/ExecutorShutdown.java b/test/jdk/java/net/httpclient/ExecutorShutdown.java index 7d4cbec6d92..a7cfd56b282 100644 --- a/test/jdk/java/net/httpclient/ExecutorShutdown.java +++ b/test/jdk/java/net/httpclient/ExecutorShutdown.java @@ -88,7 +88,7 @@ public class ExecutorShutdown implements HttpServerAdapters { } static final Random RANDOM = RandomFactory.getRandom(); - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 6 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -311,10 +311,6 @@ public class ExecutorShutdown implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { out.println("\n**** Setup ****\n"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new ServerRequestHandler(), "/http1/exec/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/exec/retry"; diff --git a/test/jdk/java/net/httpclient/ExpectContinue.java b/test/jdk/java/net/httpclient/ExpectContinue.java index 43c65781413..a2d928e6f41 100644 --- a/test/jdk/java/net/httpclient/ExpectContinue.java +++ b/test/jdk/java/net/httpclient/ExpectContinue.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -60,7 +60,7 @@ import static org.testng.Assert.assertEquals; public class ExpectContinue { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpServer httpTestServer; // HTTP/1.1 [ 2 servers ] HttpsServer httpsTestServer; // HTTPS/1.1 String httpURI; @@ -139,10 +139,6 @@ public class ExpectContinue { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); httpTestServer = HttpServer.create(sa, 0); httpTestServer.createContext("/http1/ec", new Http1ExpectContinueHandler()); diff --git a/test/jdk/java/net/httpclient/FileChannelPublisherTest.java b/test/jdk/java/net/httpclient/FileChannelPublisherTest.java index 4bc3c3ae315..c9c78791da3 100644 --- a/test/jdk/java/net/httpclient/FileChannelPublisherTest.java +++ b/test/jdk/java/net/httpclient/FileChannelPublisherTest.java @@ -90,7 +90,7 @@ class FileChannelPublisherTest { private static final int DEFAULT_BUFFER_SIZE = Utils.getBuffer().capacity(); - private static final SSLContext SSL_CONTEXT = createSslContext(); + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); private static final HttpClient CLIENT = HttpClient.newBuilder().sslContext(SSL_CONTEXT).proxy(NO_PROXY).build(); @@ -102,14 +102,6 @@ class FileChannelPublisherTest { HTTP2 = ServerRequestPair.of(Version.HTTP_2, false), HTTPS2 = ServerRequestPair.of(Version.HTTP_2, true); - private static SSLContext createSslContext() { - try { - return new SimpleSSLContext().get(); - } catch (IOException exception) { - throw new UncheckedIOException(exception); - } - } - private record ServerRequestPair( String serverName, HttpTestServer server, diff --git a/test/jdk/java/net/httpclient/FilePublisherTest.java b/test/jdk/java/net/httpclient/FilePublisherTest.java index 5ab9e6f8e7a..9501e8054cc 100644 --- a/test/jdk/java/net/httpclient/FilePublisherTest.java +++ b/test/jdk/java/net/httpclient/FilePublisherTest.java @@ -61,7 +61,7 @@ import static java.net.http.HttpClient.Version.HTTP_2; import static org.testng.Assert.assertEquals; public class FilePublisherTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpServerAdapters.HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpServerAdapters.HttpTestServer httpsTestServer; // HTTPS/1.1 HttpServerAdapters.HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -183,10 +183,6 @@ public class FilePublisherTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - defaultFsPath = defaultFsFile(); zipFs = newZipFs(); zipFsPath = zipFsFile(zipFs); diff --git a/test/jdk/java/net/httpclient/FlowAdapterPublisherTest.java b/test/jdk/java/net/httpclient/FlowAdapterPublisherTest.java index de511d6bd75..ef9dc7b3077 100644 --- a/test/jdk/java/net/httpclient/FlowAdapterPublisherTest.java +++ b/test/jdk/java/net/httpclient/FlowAdapterPublisherTest.java @@ -67,7 +67,7 @@ import static org.testng.Assert.fail; public class FlowAdapterPublisherTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -358,10 +358,6 @@ public class FlowAdapterPublisherTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(Version.HTTP_1_1); httpTestServer.addHandler(new HttpEchoHandler(), "/http1/echo"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/echo"; diff --git a/test/jdk/java/net/httpclient/FlowAdapterSubscriberTest.java b/test/jdk/java/net/httpclient/FlowAdapterSubscriberTest.java index 5de943278eb..0e175cf0f52 100644 --- a/test/jdk/java/net/httpclient/FlowAdapterSubscriberTest.java +++ b/test/jdk/java/net/httpclient/FlowAdapterSubscriberTest.java @@ -77,7 +77,7 @@ import static org.testng.Assert.assertTrue; public class FlowAdapterSubscriberTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -633,10 +633,6 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(Version.HTTP_1_1); httpTestServer.addHandler(new HttpEchoHandler(), "/http1/echo"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/echo"; diff --git a/test/jdk/java/net/httpclient/ForbiddenHeadTest.java b/test/jdk/java/net/httpclient/ForbiddenHeadTest.java index 2a50d03b365..57fd627b2b0 100644 --- a/test/jdk/java/net/httpclient/ForbiddenHeadTest.java +++ b/test/jdk/java/net/httpclient/ForbiddenHeadTest.java @@ -82,11 +82,10 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY; import static java.net.http.HttpOption.H3_DISCOVERY; import static java.nio.charset.StandardCharsets.UTF_8; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; public class ForbiddenHeadTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -336,10 +335,6 @@ public class ForbiddenHeadTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new UnauthorizedHandler(), "/http1/"); httpTestServer.addHandler(new UnauthorizedHandler(), "/http2/proxy/"); diff --git a/test/jdk/java/net/httpclient/GZIPInputStreamTest.java b/test/jdk/java/net/httpclient/GZIPInputStreamTest.java index a8ce8fb2de5..948ecd4d7cc 100644 --- a/test/jdk/java/net/httpclient/GZIPInputStreamTest.java +++ b/test/jdk/java/net/httpclient/GZIPInputStreamTest.java @@ -72,7 +72,7 @@ import static org.testng.Assert.assertEquals; public class GZIPInputStreamTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -489,10 +489,6 @@ public class GZIPInputStreamTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - HttpTestHandler plainHandler = new LoremIpsumPlainHandler(); HttpTestHandler gzipHandler = new LoremIpsumGZIPHandler(); diff --git a/test/jdk/java/net/httpclient/HeadTest.java b/test/jdk/java/net/httpclient/HeadTest.java index e14339a1121..3e05442faf5 100644 --- a/test/jdk/java/net/httpclient/HeadTest.java +++ b/test/jdk/java/net/httpclient/HeadTest.java @@ -59,7 +59,7 @@ import static org.testng.Assert.assertEquals; public class HeadTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -147,10 +147,6 @@ public class HeadTest implements HttpServerAdapters { // TODO: See if test performs better with Vthreads, see H3SimplePost and H3SimpleGet @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new HeadHandler(), "/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/"; diff --git a/test/jdk/java/net/httpclient/HeadersLowerCaseTest.java b/test/jdk/java/net/httpclient/HeadersLowerCaseTest.java index 26c791eaca8..b1e4e569010 100644 --- a/test/jdk/java/net/httpclient/HeadersLowerCaseTest.java +++ b/test/jdk/java/net/httpclient/HeadersLowerCaseTest.java @@ -72,14 +72,10 @@ public class HeadersLowerCaseTest implements HttpServerAdapters { private HttpTestServer h3server; private String h2ReqURIBase; private String h3ReqURIBase; - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); @BeforeAll public void beforeAll() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } h2server = HttpTestServer.create(HTTP_2, sslContext); h2server.start(); h2ReqURIBase = "https://" + h2server.serverAuthority(); diff --git a/test/jdk/java/net/httpclient/HttpClientAuthRetryLimitTest.java b/test/jdk/java/net/httpclient/HttpClientAuthRetryLimitTest.java index 818fd8c7a01..4cfee56e855 100644 --- a/test/jdk/java/net/httpclient/HttpClientAuthRetryLimitTest.java +++ b/test/jdk/java/net/httpclient/HttpClientAuthRetryLimitTest.java @@ -56,15 +56,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class HttpClientAuthRetryLimitTest implements HttpServerAdapters { - private static final SSLContext SSL_CONTEXT = createSslContext(); - - private static SSLContext createSslContext() { - try { - return new SimpleSSLContext().get(); - } catch (IOException exception) { - throw new RuntimeException(exception); - } - } + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); // This is the system default value for jdk.httpclient.auth.retrylimit private static final int DEFAULT_RETRY_LIMIT = 3; diff --git a/test/jdk/java/net/httpclient/HttpClientBuilderTest.java b/test/jdk/java/net/httpclient/HttpClientBuilderTest.java index 596320d49e6..9f7d2ade62f 100644 --- a/test/jdk/java/net/httpclient/HttpClientBuilderTest.java +++ b/test/jdk/java/net/httpclient/HttpClientBuilderTest.java @@ -318,18 +318,18 @@ public class HttpClientBuilderTest { @Test public void testSSLContext() throws Exception { HttpClient.Builder builder = HttpClient.newBuilder(); - SSLContext a = (new SimpleSSLContext()).get(); + SSLContext a = SimpleSSLContext.findSSLContext(); builder.sslContext(a); try (var closer = closeable(builder)) { assertTrue(closer.build().sslContext() == a); } - SSLContext b = (new SimpleSSLContext()).get(); + SSLContext b = SimpleSSLContext.findSSLContext(); builder.sslContext(b); try (var closer = closeable(builder)) { assertTrue(closer.build().sslContext() == b); } assertThrows(NPE, () -> builder.sslContext(null)); - SSLContext c = (new SimpleSSLContext()).get(); + SSLContext c = SimpleSSLContext.findSSLContext(); builder.sslContext(c); try (var closer = closeable(builder)) { assertTrue(closer.build().sslContext() == c); diff --git a/test/jdk/java/net/httpclient/HttpClientClose.java b/test/jdk/java/net/httpclient/HttpClientClose.java index f761396487c..e71faa8fe4e 100644 --- a/test/jdk/java/net/httpclient/HttpClientClose.java +++ b/test/jdk/java/net/httpclient/HttpClientClose.java @@ -97,7 +97,7 @@ public class HttpClientClose implements HttpServerAdapters { static final Random RANDOM = RandomFactory.getRandom(); ExecutorService readerService; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -343,9 +343,6 @@ public class HttpClientClose implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { out.println("\n**** Setup ****\n"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); readerService = Executors.newCachedThreadPool(); httpTestServer = HttpTestServer.create(HTTP_1_1); diff --git a/test/jdk/java/net/httpclient/HttpClientLocalAddrTest.java b/test/jdk/java/net/httpclient/HttpClientLocalAddrTest.java index e9d5fe6bffe..10cca697231 100644 --- a/test/jdk/java/net/httpclient/HttpClientLocalAddrTest.java +++ b/test/jdk/java/net/httpclient/HttpClientLocalAddrTest.java @@ -69,7 +69,7 @@ import static java.net.http.HttpClient.Version.HTTP_2; */ public class HttpClientLocalAddrTest implements HttpServerAdapters { - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private static HttpServerAdapters.HttpTestServer http1_1_Server; private static URI httpURI; private static HttpServerAdapters.HttpTestServer https_1_1_Server; @@ -83,9 +83,6 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters { // start various HTTP/HTTPS servers that will be invoked against in the tests @BeforeClass public static void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - Assert.assertNotNull(sslContext, "Unexpected null sslContext"); - HttpServerAdapters.HttpTestHandler handler = (exchange) -> { // the handler receives a request and sends back a 200 response with the // response body containing the raw IP address (in byte[] form) of the client from whom diff --git a/test/jdk/java/net/httpclient/HttpClientSNITest.java b/test/jdk/java/net/httpclient/HttpClientSNITest.java index 095508fd849..1f7377f745d 100644 --- a/test/jdk/java/net/httpclient/HttpClientSNITest.java +++ b/test/jdk/java/net/httpclient/HttpClientSNITest.java @@ -95,8 +95,7 @@ public class HttpClientSNITest { @ParameterizedTest @ValueSource(booleans = {false, true}) void testRequestToIPLiteralHost(final boolean sniConfiguredOnClient) throws Exception { - final SSLContext sslContext = new SimpleSSLContext().get(); - assertNotNull(sslContext, "could not create a SSLContext"); + final SSLContext sslContext = SimpleSSLContext.findSSLContext(); final String expectedSNI = "non-dns-resolvable.foo.bar.localhost"; final ServerNameMatcher matcher = new ServerNameMatcher(expectedSNI); final HttpTestServer server = createServer(matcher, sslContext); @@ -149,8 +148,7 @@ public class HttpClientSNITest { @ParameterizedTest @ValueSource(booleans = {false, true}) void testRequestResolvedHostName(final boolean sniConfiguredOnClient) throws Exception { - final SSLContext sslContext = new SimpleSSLContext().get(); - assertNotNull(sslContext, "could not create a SSLContext"); + final SSLContext sslContext = SimpleSSLContext.findSSLContext(); final String resolvedHostName = InetAddress.getLoopbackAddress().getHostName(); final String expectedSNI = resolvedHostName; final ServerNameMatcher matcher = new ServerNameMatcher(expectedSNI); diff --git a/test/jdk/java/net/httpclient/HttpClientShutdown.java b/test/jdk/java/net/httpclient/HttpClientShutdown.java index 192abcba39d..4a5583782cb 100644 --- a/test/jdk/java/net/httpclient/HttpClientShutdown.java +++ b/test/jdk/java/net/httpclient/HttpClientShutdown.java @@ -101,7 +101,7 @@ public class HttpClientShutdown implements HttpServerAdapters { static final Random RANDOM = RandomFactory.getRandom(); ExecutorService readerService; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -464,9 +464,6 @@ public class HttpClientShutdown implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { out.println("\n**** Setup ****\n"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); readerService = Executors.newCachedThreadPool(); httpTestServer = HttpTestServer.create(HTTP_1_1); diff --git a/test/jdk/java/net/httpclient/HttpGetInCancelledFuture.java b/test/jdk/java/net/httpclient/HttpGetInCancelledFuture.java index 4ddc0bdfdc2..80e49f20705 100644 --- a/test/jdk/java/net/httpclient/HttpGetInCancelledFuture.java +++ b/test/jdk/java/net/httpclient/HttpGetInCancelledFuture.java @@ -98,11 +98,7 @@ public class HttpGetInCancelledFuture { ? HttpServerAdapters.createClientBuilderForH3() : HttpClient.newBuilder(); if (uri.getScheme().equalsIgnoreCase("https")) { - try { - builder.sslContext(new SimpleSSLContext().get()); - } catch (IOException io) { - throw new UncheckedIOException(io); - } + builder.sslContext(SimpleSSLContext.findSSLContext()); } return builder.connectTimeout(Duration.ofSeconds(1)) .executor(executor) diff --git a/test/jdk/java/net/httpclient/HttpRedirectTest.java b/test/jdk/java/net/httpclient/HttpRedirectTest.java index 358b908a03c..e03a12a049c 100644 --- a/test/jdk/java/net/httpclient/HttpRedirectTest.java +++ b/test/jdk/java/net/httpclient/HttpRedirectTest.java @@ -80,14 +80,9 @@ import jdk.httpclient.test.lib.common.HttpServerAdapters; public class HttpRedirectTest implements HttpServerAdapters { static final String GET_RESPONSE_BODY = "Lorem ipsum dolor sit amet"; static final String REQUEST_BODY = "Here it goes"; - static final SSLContext context; + private static final SSLContext context = SimpleSSLContext.findSSLContext(); static { - try { - context = new SimpleSSLContext().get(); - SSLContext.setDefault(context); - } catch (Exception x) { - throw new ExceptionInInitializerError(x); - } + SSLContext.setDefault(context); } final AtomicLong requestCounter = new AtomicLong(); diff --git a/test/jdk/java/net/httpclient/HttpResponseConnectionLabelTest.java b/test/jdk/java/net/httpclient/HttpResponseConnectionLabelTest.java index d1dc8b0a5f5..29c4bcc8072 100644 --- a/test/jdk/java/net/httpclient/HttpResponseConnectionLabelTest.java +++ b/test/jdk/java/net/httpclient/HttpResponseConnectionLabelTest.java @@ -87,7 +87,7 @@ class HttpResponseConnectionLabelTest { private static final String SERVER_ID_HEADER_NAME = "X-Server-Id"; - private static final SSLContext SSL_CONTEXT = createSslContext(); + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); // For each test instance, start with a fresh client having no connections in the pool private final HttpClient client = HttpServerAdapters @@ -120,14 +120,6 @@ class HttpResponseConnectionLabelTest { private static final ServerRequestPair SEC_HTTP3 = ServerRequestPair.of(Version.HTTP_3, true); - private static SSLContext createSslContext() { - try { - return new SimpleSSLContext().get(); - } catch (IOException exception) { - throw new UncheckedIOException(exception); - } - } - private record ServerRequestPair( HttpTestServer server, ExecutorService executor, diff --git a/test/jdk/java/net/httpclient/HttpResponseLimitingTest.java b/test/jdk/java/net/httpclient/HttpResponseLimitingTest.java index e0bda0b0071..450fce35f54 100644 --- a/test/jdk/java/net/httpclient/HttpResponseLimitingTest.java +++ b/test/jdk/java/net/httpclient/HttpResponseLimitingTest.java @@ -107,15 +107,7 @@ class HttpResponseLimitingTest { private record ServerClientPair(HttpTestServer server, HttpClient client, HttpRequest request, boolean secure) { - private static final SSLContext SSL_CONTEXT = createSslContext(); - - private static SSLContext createSslContext() { - try { - return new SimpleSSLContext().get(); - } catch (IOException exception) { - throw new UncheckedIOException(exception); - } - } + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); private ServerClientPair { try { diff --git a/test/jdk/java/net/httpclient/HttpSlowServerTest.java b/test/jdk/java/net/httpclient/HttpSlowServerTest.java index ca841cd8ae9..f62f6fa4978 100644 --- a/test/jdk/java/net/httpclient/HttpSlowServerTest.java +++ b/test/jdk/java/net/httpclient/HttpSlowServerTest.java @@ -85,14 +85,9 @@ public class HttpSlowServerTest implements HttpServerAdapters { "Excepteur sint occaecat cupidatat non proident." ); - static final SSLContext context; + private static final SSLContext context = SimpleSSLContext.findSSLContext(); static { - try { - context = new SimpleSSLContext().get(); - SSLContext.setDefault(context); - } catch (Exception x) { - throw new ExceptionInInitializerError(x); - } + SSLContext.setDefault(context); } final AtomicLong requestCounter = new AtomicLong(); diff --git a/test/jdk/java/net/httpclient/HttpVersionsTest.java b/test/jdk/java/net/httpclient/HttpVersionsTest.java index 00b0db1af4e..a55c2727a00 100644 --- a/test/jdk/java/net/httpclient/HttpVersionsTest.java +++ b/test/jdk/java/net/httpclient/HttpVersionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -61,7 +61,7 @@ import static org.testng.Assert.assertTrue; public class HttpVersionsTest { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); Http2TestServer http2TestServer; Http2TestServer https2TestServer; String http2URI; @@ -205,10 +205,6 @@ public class HttpVersionsTest { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - http2TestServer = new Http2TestServer("localhost", false, 0, executor, 50, null, null, true); http2TestServer.addHandler(new Http2VerEchoHandler(), "/http2/vts"); http2URI = "http://" + http2TestServer.serverAuthority() + "/http2/vts"; diff --git a/test/jdk/java/net/httpclient/HttpsTunnelAuthTest.java b/test/jdk/java/net/httpclient/HttpsTunnelAuthTest.java index c6b2c323693..c83abd9cf62 100644 --- a/test/jdk/java/net/httpclient/HttpsTunnelAuthTest.java +++ b/test/jdk/java/net/httpclient/HttpsTunnelAuthTest.java @@ -74,14 +74,9 @@ public class HttpsTunnelAuthTest implements HttpServerAdapters, AutoCloseable { "Excepteur sint occaecat cupidatat non proident." }; - static final SSLContext context; + private static final SSLContext context = SimpleSSLContext.findSSLContext(); static { - try { - context = new SimpleSSLContext().get(); - SSLContext.setDefault(context); - } catch (Exception x) { - throw new ExceptionInInitializerError(x); - } + SSLContext.setDefault(context); } final String realm = "earth"; diff --git a/test/jdk/java/net/httpclient/HttpsTunnelTest.java b/test/jdk/java/net/httpclient/HttpsTunnelTest.java index 86666539942..bb0afacaacb 100644 --- a/test/jdk/java/net/httpclient/HttpsTunnelTest.java +++ b/test/jdk/java/net/httpclient/HttpsTunnelTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -82,14 +82,9 @@ public class HttpsTunnelTest implements HttpServerAdapters { "Excepteur sint occaecat cupidatat non proident." }; - static final SSLContext context; + private static final SSLContext context = SimpleSSLContext.findSSLContext(); static { - try { - context = new SimpleSSLContext().get(); - SSLContext.setDefault(context); - } catch (Exception x) { - throw new ExceptionInInitializerError(x); - } + SSLContext.setDefault(context); } HttpsTunnelTest() { diff --git a/test/jdk/java/net/httpclient/ISO_8859_1_Test.java b/test/jdk/java/net/httpclient/ISO_8859_1_Test.java index a5465ad5103..d629a6f3105 100644 --- a/test/jdk/java/net/httpclient/ISO_8859_1_Test.java +++ b/test/jdk/java/net/httpclient/ISO_8859_1_Test.java @@ -88,7 +88,7 @@ import static org.testng.Assert.assertTrue; public class ISO_8859_1_Test implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); DummyServer http1DummyServer; HttpTestServer http1TestServer; // HTTP/1.1 ( http ) HttpTestServer https1TestServer; // HTTPS/1.1 ( https ) @@ -412,10 +412,6 @@ public class ISO_8859_1_Test implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - HttpServerAdapters.HttpTestHandler handler = new ISO88591Handler(); InetSocketAddress loopback = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); diff --git a/test/jdk/java/net/httpclient/IdleConnectionTimeoutTest.java b/test/jdk/java/net/httpclient/IdleConnectionTimeoutTest.java index 07bb0be455c..78984964895 100644 --- a/test/jdk/java/net/httpclient/IdleConnectionTimeoutTest.java +++ b/test/jdk/java/net/httpclient/IdleConnectionTimeoutTest.java @@ -94,7 +94,7 @@ import static org.testng.Assert.assertEquals; public class IdleConnectionTimeoutTest { URI timeoutUriH2, noTimeoutUriH2, timeoutUriH3, noTimeoutUriH3, getH3; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static volatile QuicServerConnection latestServerConn; final String KEEP_ALIVE_PROPERTY = "jdk.httpclient.keepalive.timeout"; final String IDLE_CONN_PROPERTY_H2 = "jdk.httpclient.keepalive.timeout.h2"; @@ -112,7 +112,6 @@ public class IdleConnectionTimeoutTest { http2TestServer.addHandler(new ServerNoTimeoutHandlerH2(), NO_TIMEOUT_PATH); http2TestServer.setExchangeSupplier(TestExchange::new); - sslContext = new SimpleSSLContext().get(); http3TestServer = new Http3TestServer(sslContext) { @Override public boolean acceptIncoming(SocketAddress source, QuicServerConnection quicConn) { diff --git a/test/jdk/java/net/httpclient/ImmutableFlowItems.java b/test/jdk/java/net/httpclient/ImmutableFlowItems.java index 186d3bbd9f8..3ee4eb28768 100644 --- a/test/jdk/java/net/httpclient/ImmutableFlowItems.java +++ b/test/jdk/java/net/httpclient/ImmutableFlowItems.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -68,7 +68,7 @@ import static org.testng.Assert.*; public class ImmutableFlowItems { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpsServer httpsTestServer; // HTTPS/1.1 Http2TestServer http2TestServer; // HTTP/2 ( h2c ) @@ -175,10 +175,6 @@ public class ImmutableFlowItems { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpHandler h1_fixedLengthHandler = new HTTP1_FixedLengthHandler(); HttpHandler h1_chunkHandler = new HTTP1_ChunkedHandler(); diff --git a/test/jdk/java/net/httpclient/ImmutableSSLSessionTest.java b/test/jdk/java/net/httpclient/ImmutableSSLSessionTest.java index 179900479bc..9b5c7961c2f 100644 --- a/test/jdk/java/net/httpclient/ImmutableSSLSessionTest.java +++ b/test/jdk/java/net/httpclient/ImmutableSSLSessionTest.java @@ -90,15 +90,11 @@ public class ImmutableSSLSessionTest implements HttpServerAdapters { private String h1ReqURIBase; private String h2ReqURIBase; private String h3ReqURIBase; - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private final AtomicInteger counter = new AtomicInteger(); @BeforeAll public void beforeAll() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } h1server = HttpTestServer.create(HTTP_1_1, sslContext); h1server.start(); h1ReqURIBase = "https://" + h1server.serverAuthority() + "/h1ImmutableSSLSessionTest/"; diff --git a/test/jdk/java/net/httpclient/InvalidInputStreamSubscriptionRequest.java b/test/jdk/java/net/httpclient/InvalidInputStreamSubscriptionRequest.java index d1e3cc026d3..10df564bd41 100644 --- a/test/jdk/java/net/httpclient/InvalidInputStreamSubscriptionRequest.java +++ b/test/jdk/java/net/httpclient/InvalidInputStreamSubscriptionRequest.java @@ -100,7 +100,7 @@ import static org.testng.Assert.assertEquals; public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -565,10 +565,6 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler(); HttpTestHandler h1_chunkHandler = new HTTP_VariableLengthHandler(); diff --git a/test/jdk/java/net/httpclient/InvalidSSLContextTest.java b/test/jdk/java/net/httpclient/InvalidSSLContextTest.java index ca2ebbfb038..be4d3297dd7 100644 --- a/test/jdk/java/net/httpclient/InvalidSSLContextTest.java +++ b/test/jdk/java/net/httpclient/InvalidSSLContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -62,7 +62,7 @@ import static java.net.http.HttpClient.Version.HTTP_2; public class InvalidSSLContextTest { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); volatile SSLServerSocket sslServerSocket; volatile String uri; @@ -147,10 +147,6 @@ public class InvalidSSLContextTest { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // server-side uses a different context to that of the client-side sslServerSocket = (SSLServerSocket)sslContext .getServerSocketFactory() diff --git a/test/jdk/java/net/httpclient/InvalidSubscriptionRequest.java b/test/jdk/java/net/httpclient/InvalidSubscriptionRequest.java index 327dc57d6df..c16c9f1747c 100644 --- a/test/jdk/java/net/httpclient/InvalidSubscriptionRequest.java +++ b/test/jdk/java/net/httpclient/InvalidSubscriptionRequest.java @@ -78,7 +78,7 @@ import static org.testng.Assert.assertEquals; public class InvalidSubscriptionRequest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -461,10 +461,6 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler(); HttpTestHandler h1_chunkHandler = new HTTP_VariableLengthHandler(); diff --git a/test/jdk/java/net/httpclient/LargeResponseTest.java b/test/jdk/java/net/httpclient/LargeResponseTest.java index 02cf5ddcc8d..727cc1768df 100644 --- a/test/jdk/java/net/httpclient/LargeResponseTest.java +++ b/test/jdk/java/net/httpclient/LargeResponseTest.java @@ -82,14 +82,9 @@ public class LargeResponseTest implements HttpServerAdapters { } } - static final SSLContext context; + private static final SSLContext context = SimpleSSLContext.findSSLContext(); static { - try { - context = new SimpleSSLContext().get(); - SSLContext.setDefault(context); - } catch (Exception x) { - throw new ExceptionInInitializerError(x); - } + SSLContext.setDefault(context); } final AtomicLong requestCounter = new AtomicLong(); diff --git a/test/jdk/java/net/httpclient/LightWeightHttpServer.java b/test/jdk/java/net/httpclient/LightWeightHttpServer.java index c226b845527..496aa2c5778 100644 --- a/test/jdk/java/net/httpclient/LightWeightHttpServer.java +++ b/test/jdk/java/net/httpclient/LightWeightHttpServer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -55,7 +55,7 @@ import jdk.test.lib.net.SimpleSSLContext; public class LightWeightHttpServer { - static SSLContext ctx; + static final SSLContext ctx = SimpleSSLContext.findSSLContext(); static HttpServer httpServer; static HttpsServer httpsServer; static ExecutorService executor; @@ -111,7 +111,6 @@ public class LightWeightHttpServer { executor = Executors.newCachedThreadPool(); httpServer.setExecutor(executor); httpsServer.setExecutor(executor); - ctx = new SimpleSSLContext().get(); httpsServer.setHttpsConfigurator(new TestServerConfigurator(addr.getAddress(), ctx)); httpServer.start(); httpsServer.start(); diff --git a/test/jdk/java/net/httpclient/LineBodyHandlerTest.java b/test/jdk/java/net/httpclient/LineBodyHandlerTest.java index 62afcab9ee2..45df8d13f7e 100644 --- a/test/jdk/java/net/httpclient/LineBodyHandlerTest.java +++ b/test/jdk/java/net/httpclient/LineBodyHandlerTest.java @@ -86,7 +86,7 @@ import static org.testng.Assert.assertTrue; public class LineBodyHandlerTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -677,10 +677,6 @@ public class LineBodyHandlerTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1, null, executorFor("HTTP/1.1 Server Thread")); httpTestServer.addHandler(new HttpTestEchoHandler(), "/http1/echo"); diff --git a/test/jdk/java/net/httpclient/ManyRequests.java b/test/jdk/java/net/httpclient/ManyRequests.java index 190205a9ef5..ee79ac80b68 100644 --- a/test/jdk/java/net/httpclient/ManyRequests.java +++ b/test/jdk/java/net/httpclient/ManyRequests.java @@ -104,7 +104,7 @@ public class ManyRequests { + " requests; delay=" + INSERT_DELAY + ", chunks=" + CHUNK_SIZE + ", XFixed=" + XFIXED); - SSLContext ctx = new SimpleSSLContext().get(); + SSLContext ctx = SimpleSSLContext.findSSLContext(); InetSocketAddress addr = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); HttpsServer server = HttpsServer.create(addr, 0); diff --git a/test/jdk/java/net/httpclient/ManyRequestsLegacy.java b/test/jdk/java/net/httpclient/ManyRequestsLegacy.java index 1d8091d3085..2e58ee50bff 100644 --- a/test/jdk/java/net/httpclient/ManyRequestsLegacy.java +++ b/test/jdk/java/net/httpclient/ManyRequestsLegacy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -105,7 +105,7 @@ public class ManyRequestsLegacy { + " requests; delay=" + INSERT_DELAY + ", chunks=" + CHUNK_SIZE + ", XFixed=" + XFIXED); - SSLContext ctx = new SimpleSSLContext().get(); + SSLContext ctx = SimpleSSLContext.findSSLContext(); SSLContext.setDefault(ctx); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { diff --git a/test/jdk/java/net/httpclient/MappingResponseSubscriber.java b/test/jdk/java/net/httpclient/MappingResponseSubscriber.java index 5e5497cf0e5..445b4a59e24 100644 --- a/test/jdk/java/net/httpclient/MappingResponseSubscriber.java +++ b/test/jdk/java/net/httpclient/MappingResponseSubscriber.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -75,7 +75,7 @@ import static org.testng.Assert.assertTrue; public class MappingResponseSubscriber { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpsServer httpsTestServer; // HTTPS/1.1 Http2TestServer http2TestServer; // HTTP/2 ( h2c ) @@ -215,10 +215,6 @@ public class MappingResponseSubscriber { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpHandler h1_fixedLengthHandler = new HTTP1_FixedLengthHandler(); HttpHandler h1_chunkHandler = new HTTP1_ChunkedHandler(); diff --git a/test/jdk/java/net/httpclient/MaxStreams.java b/test/jdk/java/net/httpclient/MaxStreams.java index 25ec39ac472..b25f931be9d 100644 --- a/test/jdk/java/net/httpclient/MaxStreams.java +++ b/test/jdk/java/net/httpclient/MaxStreams.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -67,7 +67,7 @@ public class MaxStreams { Http2TestServer http2TestServer; // HTTP/2 ( h2c ) Http2TestServer https2TestServer; // HTTP/2 ( h2 ) final Http2FixedHandler handler = new Http2FixedHandler(); - SSLContext ctx; + private static final SSLContext ctx = SimpleSSLContext.findSSLContext(); String http2FixedURI; String https2FixedURI; ExecutorService exec; @@ -163,7 +163,6 @@ public class MaxStreams { @BeforeTest public void setup() throws Exception { - ctx = (new SimpleSSLContext()).get(); exec = Executors.newCachedThreadPool(); InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); diff --git a/test/jdk/java/net/httpclient/NonAsciiCharsInURI.java b/test/jdk/java/net/httpclient/NonAsciiCharsInURI.java index ba93645aef4..0a0da6366ad 100644 --- a/test/jdk/java/net/httpclient/NonAsciiCharsInURI.java +++ b/test/jdk/java/net/httpclient/NonAsciiCharsInURI.java @@ -67,7 +67,7 @@ import static org.testng.Assert.assertEquals; public class NonAsciiCharsInURI implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -280,10 +280,6 @@ public class NonAsciiCharsInURI implements HttpServerAdapters { public void setup() throws Exception { out.println(now() + "begin setup"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - HttpTestHandler handler = new HttpUriStringHandler(); httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(handler, "/http1/get"); diff --git a/test/jdk/java/net/httpclient/PathSubscriber/BodyHandlerOfFileDownloadTest.java b/test/jdk/java/net/httpclient/PathSubscriber/BodyHandlerOfFileDownloadTest.java index b5ea5da13e4..eb397d37b7a 100644 --- a/test/jdk/java/net/httpclient/PathSubscriber/BodyHandlerOfFileDownloadTest.java +++ b/test/jdk/java/net/httpclient/PathSubscriber/BodyHandlerOfFileDownloadTest.java @@ -80,7 +80,7 @@ public class BodyHandlerOfFileDownloadTest implements HttpServerAdapters { static final String MSG = "msg"; static final String contentDispositionValue = "attachment; filename=example.html"; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -208,10 +208,6 @@ public class BodyHandlerOfFileDownloadTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - defaultFsPath = defaultFsDir(); zipFs = newZipFs(); zipFsPath = zipFsDir(zipFs); diff --git a/test/jdk/java/net/httpclient/PathSubscriber/BodyHandlerOfFileTest.java b/test/jdk/java/net/httpclient/PathSubscriber/BodyHandlerOfFileTest.java index 42d5c2596c7..13871933eac 100644 --- a/test/jdk/java/net/httpclient/PathSubscriber/BodyHandlerOfFileTest.java +++ b/test/jdk/java/net/httpclient/PathSubscriber/BodyHandlerOfFileTest.java @@ -71,7 +71,7 @@ import static org.testng.Assert.assertEquals; public class BodyHandlerOfFileTest implements HttpServerAdapters { static final String MSG = "msg"; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -216,10 +216,6 @@ public class BodyHandlerOfFileTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - defaultFsPath = defaultFsFile(); zipFs = newZipFs(); zipFsPath = zipFsFile(zipFs); diff --git a/test/jdk/java/net/httpclient/PathSubscriber/BodySubscriberOfFileTest.java b/test/jdk/java/net/httpclient/PathSubscriber/BodySubscriberOfFileTest.java index 2a7ba90c7b2..d7c9a3af4f1 100644 --- a/test/jdk/java/net/httpclient/PathSubscriber/BodySubscriberOfFileTest.java +++ b/test/jdk/java/net/httpclient/PathSubscriber/BodySubscriberOfFileTest.java @@ -75,7 +75,7 @@ import static org.testng.Assert.assertEquals; public class BodySubscriberOfFileTest implements HttpServerAdapters { static final String MSG = "msg"; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -246,10 +246,6 @@ public class BodySubscriberOfFileTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - defaultFsPath = defaultFsFile(); zipFs = newZipFs(); zipFsPath = zipFsFile(zipFs); diff --git a/test/jdk/java/net/httpclient/PlainConnectionLockTest.java b/test/jdk/java/net/httpclient/PlainConnectionLockTest.java index 3205f87111a..745f5951dd9 100644 --- a/test/jdk/java/net/httpclient/PlainConnectionLockTest.java +++ b/test/jdk/java/net/httpclient/PlainConnectionLockTest.java @@ -101,7 +101,7 @@ import static java.net.http.HttpClient.Version.HTTP_1_1; // -Djava.security.debug=all class PlainConnectionLockTest implements HttpServerAdapters { - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private HttpTestServer http1Server; private HttpTestServer https1Server; private String http1URI; @@ -133,10 +133,6 @@ class PlainConnectionLockTest implements HttpServerAdapters { requestSemaphore = new Semaphore(0); responseSemaphore = new Semaphore(0); successfulCompletion = false; - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } serverExecutor = Executors.newThreadPerTaskExecutor( Thread.ofVirtual().name("Http1Server", 0).factory()); diff --git a/test/jdk/java/net/httpclient/ProxySelectorTest.java b/test/jdk/java/net/httpclient/ProxySelectorTest.java index a5407801bcd..bf63e5a77b5 100644 --- a/test/jdk/java/net/httpclient/ProxySelectorTest.java +++ b/test/jdk/java/net/httpclient/ProxySelectorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -86,7 +86,7 @@ import static org.testng.Assert.assertEquals; public class ProxySelectorTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 HttpTestServer proxyHttpTestServer; // HTTP/1.1 HttpTestServer authProxyHttpTestServer; // HTTP/1.1 @@ -320,10 +320,6 @@ public class ProxySelectorTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new PlainServerHandler("plain-server"), "/http1/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1"; diff --git a/test/jdk/java/net/httpclient/ProxyTest.java b/test/jdk/java/net/httpclient/ProxyTest.java index 45c21e7ef4a..d8abea188bd 100644 --- a/test/jdk/java/net/httpclient/ProxyTest.java +++ b/test/jdk/java/net/httpclient/ProxyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -80,16 +80,12 @@ import static java.net.Proxy.NO_PROXY; public class ProxyTest { static { - try { - HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { - public boolean verify(String hostname, SSLSession session) { - return true; - } - }); - SSLContext.setDefault(new SimpleSSLContext().get()); - } catch (IOException ex) { - throw new ExceptionInInitializerError(ex); - } + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }); + SSLContext.setDefault(SimpleSSLContext.findSSLContext()); } static final String RESPONSE = "

    Hello World!"; diff --git a/test/jdk/java/net/httpclient/RedirectMethodChange.java b/test/jdk/java/net/httpclient/RedirectMethodChange.java index f713c0dc5d1..b0b130921f5 100644 --- a/test/jdk/java/net/httpclient/RedirectMethodChange.java +++ b/test/jdk/java/net/httpclient/RedirectMethodChange.java @@ -55,7 +55,7 @@ import static org.testng.Assert.assertEquals; public class RedirectMethodChange implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpClient client; HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] @@ -203,10 +203,6 @@ public class RedirectMethodChange implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - client = newClientBuilderForH3() .followRedirects(HttpClient.Redirect.NORMAL) .sslContext(sslContext) diff --git a/test/jdk/java/net/httpclient/RedirectTimeoutTest.java b/test/jdk/java/net/httpclient/RedirectTimeoutTest.java index 3e921879fe3..e51f394f845 100644 --- a/test/jdk/java/net/httpclient/RedirectTimeoutTest.java +++ b/test/jdk/java/net/httpclient/RedirectTimeoutTest.java @@ -66,7 +66,7 @@ import static jdk.test.lib.Utils.adjustTimeout; public class RedirectTimeoutTest implements HttpServerAdapters { - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static HttpTestServer h1TestServer, h2TestServer, h3TestServer; static URI h1Uri, h1RedirectUri, h2Uri, h2RedirectUri, h3Uri, h3RedirectUri, h2WarmupUri, h3WarmupUri, testRedirectURI; @@ -77,10 +77,6 @@ public class RedirectTimeoutTest implements HttpServerAdapters { @BeforeTest public void setup() throws IOException { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - h1TestServer = HttpTestServer.create(HTTP_1_1); h2TestServer = HttpTestServer.create(HTTP_2); h3TestServer = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext); diff --git a/test/jdk/java/net/httpclient/RedirectWithCookie.java b/test/jdk/java/net/httpclient/RedirectWithCookie.java index afc8618835b..b4a4df38721 100644 --- a/test/jdk/java/net/httpclient/RedirectWithCookie.java +++ b/test/jdk/java/net/httpclient/RedirectWithCookie.java @@ -61,7 +61,7 @@ import static org.testng.Assert.assertTrue; public class RedirectWithCookie implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -160,10 +160,6 @@ public class RedirectWithCookie implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new CookieRedirectHandler(), "/http1/cookie/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/cookie/redirect"; diff --git a/test/jdk/java/net/httpclient/Response1xxTest.java b/test/jdk/java/net/httpclient/Response1xxTest.java index d0148f0d684..5cff7a69259 100644 --- a/test/jdk/java/net/httpclient/Response1xxTest.java +++ b/test/jdk/java/net/httpclient/Response1xxTest.java @@ -76,7 +76,7 @@ public class Response1xxTest implements HttpServerAdapters { private String http2RequestURIBase; - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private HttpTestServer https2Server; // h2 private String https2RequestURIBase; @@ -107,10 +107,6 @@ public class Response1xxTest implements HttpServerAdapters { http2Server.start(); System.out.println("Started HTTP2 server at " + http2Server.getAddress()); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } https2Server = HttpTestServer.create(HTTP_2, sslContext); https2Server.addHandler(new Http2Handler(), "/http2/101"); https2RequestURIBase = URIBuilder.newBuilder().scheme("https").loopback() diff --git a/test/jdk/java/net/httpclient/Response204V2Test.java b/test/jdk/java/net/httpclient/Response204V2Test.java index 9f867d0fb17..c9dbd8eccf9 100644 --- a/test/jdk/java/net/httpclient/Response204V2Test.java +++ b/test/jdk/java/net/httpclient/Response204V2Test.java @@ -76,7 +76,7 @@ import static java.net.http.HttpOption.H3_DISCOVERY; public class Response204V2Test implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer http2TestServer; // HTTP/2 ( h2c ) HttpTestServer https2TestServer; // HTTP/2 ( h2 ) HttpTestServer http3TestServer; // HTTP/3 ( h3 ) @@ -284,10 +284,6 @@ public class Response204V2Test implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/2 HttpTestHandler handler204 = new Handler204(); diff --git a/test/jdk/java/net/httpclient/ResponseBodyBeforeError.java b/test/jdk/java/net/httpclient/ResponseBodyBeforeError.java index 04ce3d531af..123e47e2ac9 100644 --- a/test/jdk/java/net/httpclient/ResponseBodyBeforeError.java +++ b/test/jdk/java/net/httpclient/ResponseBodyBeforeError.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -82,7 +82,7 @@ public class ResponseBodyBeforeError { String httpURIFixLen; String httpsURIFixLen; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static final String EXPECTED_RESPONSE_BODY = "

    Heading

    Some Text

    "; @@ -538,9 +538,6 @@ public class ResponseBodyBeforeError { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); SSLContext.setDefault(sslContext); variableLengthServer = new PlainVariableLengthServer(); diff --git a/test/jdk/java/net/httpclient/ResponsePublisher.java b/test/jdk/java/net/httpclient/ResponsePublisher.java index 5d90e20c626..ce86a0a3cf5 100644 --- a/test/jdk/java/net/httpclient/ResponsePublisher.java +++ b/test/jdk/java/net/httpclient/ResponsePublisher.java @@ -79,7 +79,7 @@ import static org.testng.Assert.assertTrue; public class ResponsePublisher implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -456,10 +456,6 @@ public class ResponsePublisher implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler(); HttpTestHandler h1_chunkHandler = new HTTP_VariableLengthHandler(); diff --git a/test/jdk/java/net/httpclient/RetryWithCookie.java b/test/jdk/java/net/httpclient/RetryWithCookie.java index dc046031bd3..782d8a0b956 100644 --- a/test/jdk/java/net/httpclient/RetryWithCookie.java +++ b/test/jdk/java/net/httpclient/RetryWithCookie.java @@ -72,7 +72,7 @@ import static org.testng.Assert.assertTrue; public class RetryWithCookie implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -158,10 +158,6 @@ public class RetryWithCookie implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new CookieRetryHandler(), "/http1/cookie/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/cookie/retry"; diff --git a/test/jdk/java/net/httpclient/ServerCloseTest.java b/test/jdk/java/net/httpclient/ServerCloseTest.java index 10fb8ca94d1..65eb6cfc589 100644 --- a/test/jdk/java/net/httpclient/ServerCloseTest.java +++ b/test/jdk/java/net/httpclient/ServerCloseTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -77,7 +77,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; public class ServerCloseTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); DummyServer httpDummyServer; // HTTP/1.1 [ 2 servers ] DummyServer httpsDummyServer; // HTTPS/1.1 String httpDummy; @@ -226,10 +226,6 @@ public class ServerCloseTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); // DummyServer diff --git a/test/jdk/java/net/httpclient/ShortResponseBody.java b/test/jdk/java/net/httpclient/ShortResponseBody.java index 88d1cde6761..b4fd83585ee 100644 --- a/test/jdk/java/net/httpclient/ShortResponseBody.java +++ b/test/jdk/java/net/httpclient/ShortResponseBody.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -82,7 +82,7 @@ public abstract class ShortResponseBody { String httpsURIVarLen; String httpURIFixLen; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); SSLParameters sslParameters; HttpClient client; int numberOfRequests; @@ -657,9 +657,6 @@ public abstract class ShortResponseBody { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); SSLContext.setDefault(sslContext); sslParameters = new SSLParameters(); diff --git a/test/jdk/java/net/httpclient/ShutdownNow.java b/test/jdk/java/net/httpclient/ShutdownNow.java index a5850b4af61..4f9eabbeb4d 100644 --- a/test/jdk/java/net/httpclient/ShutdownNow.java +++ b/test/jdk/java/net/httpclient/ShutdownNow.java @@ -91,7 +91,7 @@ public class ShutdownNow implements HttpServerAdapters { } static final Random RANDOM = RandomFactory.getRandom(); - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -321,10 +321,6 @@ public class ShutdownNow implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { out.println("\n**** Setup ****\n"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new ServerRequestHandler(), "/http1/exec/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/exec/retry"; diff --git a/test/jdk/java/net/httpclient/SmokeTest.java b/test/jdk/java/net/httpclient/SmokeTest.java index a10afef562f..42c082a5e0f 100644 --- a/test/jdk/java/net/httpclient/SmokeTest.java +++ b/test/jdk/java/net/httpclient/SmokeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -121,7 +121,7 @@ import java.util.logging.Logger; * in docs directory. */ public class SmokeTest { - static SSLContext ctx; + private static final SSLContext ctx = SimpleSSLContext.findSSLContext(); static SSLParameters sslparams; static HttpServer s1 ; static HttpsServer s2; @@ -808,7 +808,6 @@ public class SmokeTest { executor = Executors.newCachedThreadPool(); s1.setExecutor(executor); s2.setExecutor(executor); - ctx = new SimpleSSLContext().get(); sslparams = ctx.getDefaultSSLParameters(); //sslparams.setProtocols(new String[]{"TLSv1.2"}); s2.setHttpsConfigurator(new Configurator(addr.getAddress(), ctx)); diff --git a/test/jdk/java/net/httpclient/SpecialHeadersTest.java b/test/jdk/java/net/httpclient/SpecialHeadersTest.java index 9ad3114da2a..d33135dd4ce 100644 --- a/test/jdk/java/net/httpclient/SpecialHeadersTest.java +++ b/test/jdk/java/net/httpclient/SpecialHeadersTest.java @@ -100,7 +100,7 @@ import static org.testng.Assert.assertTrue; public class SpecialHeadersTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -555,9 +555,6 @@ public class SpecialHeadersTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { out.println("--- Starting setup " + now()); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); HttpTestHandler handler = new HttpUriStringHandler(); httpTestServer = HttpTestServer.create(HTTP_1_1); diff --git a/test/jdk/java/net/httpclient/SplitResponse.java b/test/jdk/java/net/httpclient/SplitResponse.java index 9213901df4b..abc972fd591 100644 --- a/test/jdk/java/net/httpclient/SplitResponse.java +++ b/test/jdk/java/net/httpclient/SplitResponse.java @@ -94,11 +94,10 @@ public class SplitResponse { }; final ServerSocketFactory factory; - final SSLContext context; + private static final SSLContext context = SimpleSSLContext.findSSLContext(); final boolean useSSL; - SplitResponse(boolean useSSL) throws IOException { + SplitResponse(boolean useSSL) { this.useSSL = useSSL; - context = new SimpleSSLContext().get(); SSLContext.setDefault(context); factory = useSSL ? SSLServerSocketFactory.getDefault() : ServerSocketFactory.getDefault(); diff --git a/test/jdk/java/net/httpclient/StreamingBody.java b/test/jdk/java/net/httpclient/StreamingBody.java index bff6a2b39c4..c2ad19cf7b7 100644 --- a/test/jdk/java/net/httpclient/StreamingBody.java +++ b/test/jdk/java/net/httpclient/StreamingBody.java @@ -59,7 +59,7 @@ import static org.testng.Assert.assertEquals; public class StreamingBody implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -126,10 +126,6 @@ public class StreamingBody implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new MessageHandler(), "/http1/streamingbody/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/streamingbody/w"; diff --git a/test/jdk/java/net/httpclient/TimeoutBasic.java b/test/jdk/java/net/httpclient/TimeoutBasic.java index 6ecd2564f54..cae1cda7ade 100644 --- a/test/jdk/java/net/httpclient/TimeoutBasic.java +++ b/test/jdk/java/net/httpclient/TimeoutBasic.java @@ -83,11 +83,7 @@ public class TimeoutBasic { static final List SCHEMES = List.of("https", "http"); static { - try { - SSLContext.setDefault(new SimpleSSLContext().get()); - } catch (IOException x) { - throw new ExceptionInInitializerError(x); - } + SSLContext.setDefault(SimpleSSLContext.findSSLContext()); } public static void main(String[] args) throws Exception { diff --git a/test/jdk/java/net/httpclient/TimeoutResponseTestSupport.java b/test/jdk/java/net/httpclient/TimeoutResponseTestSupport.java index 4da63a2dff9..67b993eef0b 100644 --- a/test/jdk/java/net/httpclient/TimeoutResponseTestSupport.java +++ b/test/jdk/java/net/httpclient/TimeoutResponseTestSupport.java @@ -72,7 +72,7 @@ public class TimeoutResponseTestSupport { private static final Logger LOGGER = Utils.getDebugLogger(CLASS_NAME::toString, Utils.DEBUG); - private static final SSLContext SSL_CONTEXT = createSslContext(); + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); protected static final Duration REQUEST_TIMEOUT = Duration.ofMillis(Long.parseLong(System.getProperty("test.requestTimeoutMillis"))); @@ -126,14 +126,6 @@ public class TimeoutResponseTestSupport { HTTPS2 = ServerRequestPair.of(Version.HTTP_2, true), HTTP3 = ServerRequestPair.of(Version.HTTP_3, true); - private static SSLContext createSslContext() { - try { - return new SimpleSSLContext().get(); - } catch (IOException exception) { - throw new UncheckedIOException(exception); - } - } - protected record ServerRequestPair(HttpTestServer server, HttpRequest request, boolean secure) { private static final ExecutorService EXECUTOR = Executors.newVirtualThreadPerTaskExecutor(); diff --git a/test/jdk/java/net/httpclient/TlsContextTest.java b/test/jdk/java/net/httpclient/TlsContextTest.java index 86b067f66f8..8a5cc99aad3 100644 --- a/test/jdk/java/net/httpclient/TlsContextTest.java +++ b/test/jdk/java/net/httpclient/TlsContextTest.java @@ -75,7 +75,7 @@ public class TlsContextTest implements HttpServerAdapters { // Re-enable TLSv1 and TLSv1.1 since test depends on them SecurityUtils.removeFromDisabledTlsAlgs("TLSv1", "TLSv1.1"); - server = SimpleSSLContext.getContext("TLS"); + server = SimpleSSLContext.findSSLContext("TLS"); final ExecutorService executor = Executors.newCachedThreadPool(); https2Server = HttpTestServer.of( new Http2TestServer("localhost", true, 0, executor, 50, null, server, true) @@ -89,13 +89,13 @@ public class TlsContextTest implements HttpServerAdapters { @DataProvider(name = "scenarios") public Object[][] scenarios() throws Exception { return new Object[][]{ - { SimpleSSLContext.getContext("TLS"), HTTP_2, "TLSv1.3" }, - { SimpleSSLContext.getContext("TLSv1.2"), HTTP_2, "TLSv1.2" }, - { SimpleSSLContext.getContext("TLSv1.1"), HTTP_1_1, "TLSv1.1" }, - { SimpleSSLContext.getContext("TLSv1.1"), HTTP_2, "TLSv1.1" }, - { SimpleSSLContext.getContext("TLSv1.3"), HTTP_3, "TLSv1.3" }, - { SimpleSSLContext.getContext("TLSv1.2"), HTTP_3, "TLSv1.2" }, - { SimpleSSLContext.getContext("TLSv1.1"), HTTP_3, "TLSv1.1" }, + { SimpleSSLContext.findSSLContext("TLS"), HTTP_2, "TLSv1.3" }, + { SimpleSSLContext.findSSLContext("TLSv1.2"), HTTP_2, "TLSv1.2" }, + { SimpleSSLContext.findSSLContext("TLSv1.1"), HTTP_1_1, "TLSv1.1" }, + { SimpleSSLContext.findSSLContext("TLSv1.1"), HTTP_2, "TLSv1.1" }, + { SimpleSSLContext.findSSLContext("TLSv1.3"), HTTP_3, "TLSv1.3" }, + { SimpleSSLContext.findSSLContext("TLSv1.2"), HTTP_3, "TLSv1.2" }, + { SimpleSSLContext.findSSLContext("TLSv1.1"), HTTP_3, "TLSv1.1" }, }; } diff --git a/test/jdk/java/net/httpclient/UnauthorizedTest.java b/test/jdk/java/net/httpclient/UnauthorizedTest.java index 0c8c2b1d2cd..628130f9ffc 100644 --- a/test/jdk/java/net/httpclient/UnauthorizedTest.java +++ b/test/jdk/java/net/httpclient/UnauthorizedTest.java @@ -70,7 +70,7 @@ import static org.testng.Assert.assertTrue; public class UnauthorizedTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -207,10 +207,6 @@ public class UnauthorizedTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new UnauthorizedHandler(), "/http1/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1"; diff --git a/test/jdk/java/net/httpclient/UnknownBodyLengthTest.java b/test/jdk/java/net/httpclient/UnknownBodyLengthTest.java index cb3d083669b..6c7fabb7f00 100644 --- a/test/jdk/java/net/httpclient/UnknownBodyLengthTest.java +++ b/test/jdk/java/net/httpclient/UnknownBodyLengthTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -59,7 +59,7 @@ import jdk.test.lib.net.SimpleSSLContext; public class UnknownBodyLengthTest { static final byte[] BUF = new byte[32 * 10234 + 2]; - volatile SSLContext ctx; + private static final SSLContext ctx = SimpleSSLContext.findSSLContext(); volatile ServerSocketFactory factory; volatile String clientURL; volatile int port; @@ -67,7 +67,6 @@ public class UnknownBodyLengthTest { final List acceptedList = new CopyOnWriteArrayList<>(); UnknownBodyLengthTest(boolean useSSL) throws Exception { - ctx = new SimpleSSLContext().get(); SSLContext.setDefault(ctx); factory = useSSL ? SSLServerSocketFactory.getDefault() : ServerSocketFactory.getDefault(); diff --git a/test/jdk/java/net/httpclient/UserAuthWithAuthenticator.java b/test/jdk/java/net/httpclient/UserAuthWithAuthenticator.java index ee28980c035..90df367a619 100644 --- a/test/jdk/java/net/httpclient/UserAuthWithAuthenticator.java +++ b/test/jdk/java/net/httpclient/UserAuthWithAuthenticator.java @@ -88,7 +88,7 @@ class UserAuthWithAuthenticator { } private static void h2Test(final boolean useHeader, boolean rightPassword) throws Exception { - SSLContext sslContext = new SimpleSSLContext().get(); + SSLContext sslContext = SimpleSSLContext.findSSLContext(); try (ExecutorService executor = Executors.newCachedThreadPool(); HttpTestServer server = HttpTestServer.of(new Http2TestServer( InetAddress.getLoopbackAddress(), @@ -117,7 +117,7 @@ class UserAuthWithAuthenticator { } private static void h3Test(final boolean useHeader, boolean rightPassword) throws Exception { - SSLContext sslContext = new SimpleSSLContext().get(); + SSLContext sslContext = SimpleSSLContext.findSSLContext(); try (ExecutorService executor = Executors.newCachedThreadPool(); HttpTestServer server = HttpTestServer.create(Http3DiscoveryMode.HTTP_3_URI_ONLY, sslContext, executor); HttpClient client = HttpServerAdapters.createClientBuilderForH3() diff --git a/test/jdk/java/net/httpclient/UserCookieTest.java b/test/jdk/java/net/httpclient/UserCookieTest.java index 50a13e48322..3d202914050 100644 --- a/test/jdk/java/net/httpclient/UserCookieTest.java +++ b/test/jdk/java/net/httpclient/UserCookieTest.java @@ -84,7 +84,7 @@ import static org.testng.Assert.assertEquals; public class UserCookieTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer httpTestServer; // HTTP/1.1 [ 7 servers ] HttpTestServer httpsTestServer; // HTTPS/1.1 HttpTestServer http2TestServer; // HTTP/2 ( h2c ) @@ -202,10 +202,6 @@ public class UserCookieTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - httpTestServer = HttpTestServer.create(HTTP_1_1); httpTestServer.addHandler(new CookieValidationHandler(), "/http1/cookie/"); httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/cookie/retry"; diff --git a/test/jdk/java/net/httpclient/http2/BadHeadersTest.java b/test/jdk/java/net/httpclient/http2/BadHeadersTest.java index 4ee95678acb..3bb80031178 100644 --- a/test/jdk/java/net/httpclient/http2/BadHeadersTest.java +++ b/test/jdk/java/net/httpclient/http2/BadHeadersTest.java @@ -87,7 +87,7 @@ public class BadHeadersTest { of(entry("hello", "world!"), entry(":status", "200")) // Pseudo header is not the first one ); - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private static Http2TestServer http2TestServer; // HTTP/2 ( h2c ) private static Http2TestServer https2TestServer; // HTTP/2 ( h2 ) private static String http2URI; @@ -242,10 +242,6 @@ public class BadHeadersTest { @BeforeAll static void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - http2TestServer = new Http2TestServer("localhost", false, 0); http2TestServer.addHandler(new Http2EchoHandler(), "/http2/echo"); int port = http2TestServer.getAddress().getPort(); diff --git a/test/jdk/java/net/httpclient/http2/BasicTest.java b/test/jdk/java/net/httpclient/http2/BasicTest.java index 0c64be84926..58ab191fc6f 100644 --- a/test/jdk/java/net/httpclient/http2/BasicTest.java +++ b/test/jdk/java/net/httpclient/http2/BasicTest.java @@ -70,14 +70,12 @@ public class BasicTest { static HttpClient client = null; static ExecutorService clientExec; static ExecutorService serverExec; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static String pingURIString, httpURIString, httpsURIString; static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); httpServer = new Http2TestServer(false, 0, serverExec, sslContext); httpServer.addHandler(new Http2EchoHandler(), "/"); diff --git a/test/jdk/java/net/httpclient/http2/ConnectionFlowControlTest.java b/test/jdk/java/net/httpclient/http2/ConnectionFlowControlTest.java index 767d31f13e5..1b9396effbb 100644 --- a/test/jdk/java/net/httpclient/http2/ConnectionFlowControlTest.java +++ b/test/jdk/java/net/httpclient/http2/ConnectionFlowControlTest.java @@ -74,7 +74,7 @@ import static org.junit.jupiter.api.Assertions.*; public class ConnectionFlowControlTest { - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private static HttpTestServer http2TestServer; // HTTP/2 ( h2c ) private static HttpTestServer https2TestServer; // HTTP/2 ( h2 ) private static String http2URI; @@ -240,10 +240,6 @@ public class ConnectionFlowControlTest { @BeforeAll static void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - var http2TestServerLocal = new Http2TestServer("localhost", false, 0); http2TestServerLocal.addHandler(new Http2TestHandler(), "/http2/"); http2TestServer = HttpTestServer.of(http2TestServerLocal); diff --git a/test/jdk/java/net/httpclient/http2/ConnectionReuseTest.java b/test/jdk/java/net/httpclient/http2/ConnectionReuseTest.java index 24e7dded842..360eabaee2b 100644 --- a/test/jdk/java/net/httpclient/http2/ConnectionReuseTest.java +++ b/test/jdk/java/net/httpclient/http2/ConnectionReuseTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -68,7 +68,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; */ public class ConnectionReuseTest { - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private static HttpTestServer http2_Server; // h2 server over HTTP private static HttpTestServer https2_Server; // h2 server over HTTPS @@ -80,8 +80,6 @@ public class ConnectionReuseTest { // if IPv6 isn't supported on this host Assumptions.assumeTrue(IPSupport.hasIPv6(), "Skipping tests - IPv6 is not supported"); } - sslContext = new SimpleSSLContext().get(); - assertNotNull(sslContext, "Unexpected null sslContext"); http2_Server = HttpTestServer.create(HTTP_2); http2_Server.addHandler(new Handler(), "/"); diff --git a/test/jdk/java/net/httpclient/http2/ContinuationFrameTest.java b/test/jdk/java/net/httpclient/http2/ContinuationFrameTest.java index f8788da67a4..c72beb04d56 100644 --- a/test/jdk/java/net/httpclient/http2/ContinuationFrameTest.java +++ b/test/jdk/java/net/httpclient/http2/ContinuationFrameTest.java @@ -70,7 +70,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class ContinuationFrameTest { - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private static Http2TestServer http2TestServer; // HTTP/2 ( h2c ) private static Http2TestServer https2TestServer; // HTTP/2 ( h2 ) private static String http2URI; @@ -210,10 +210,6 @@ public class ContinuationFrameTest { @BeforeAll static void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - http2TestServer = new Http2TestServer("localhost", false, 0); http2TestServer.addHandler(new Http2EchoHandler(), "/http2/echo"); http2TestServer.addHandler(new Http2NoBodyHandler(), "/http2/nobody"); diff --git a/test/jdk/java/net/httpclient/http2/ErrorTest.java b/test/jdk/java/net/httpclient/http2/ErrorTest.java index e8613b9efa8..6ecc27441e1 100644 --- a/test/jdk/java/net/httpclient/http2/ErrorTest.java +++ b/test/jdk/java/net/httpclient/http2/ErrorTest.java @@ -82,7 +82,7 @@ public class ErrorTest { //@Test(timeOut=5000) @Test public void test() throws Exception { - SSLContext sslContext = (new SimpleSSLContext()).get(); + SSLContext sslContext = SimpleSSLContext.findSSLContext(); ExecutorService exec = Executors.newCachedThreadPool(); HttpClient client = HttpClient.newBuilder() .executor(exec) @@ -93,7 +93,7 @@ public class ErrorTest { Http2TestServer httpsServer = null; try { - SSLContext serverContext = (new SimpleSSLContext()).get(); + SSLContext serverContext = SimpleSSLContext.findSSLContext(); SSLParameters p = serverContext.getSupportedSSLParameters(); p.setApplicationProtocols(new String[]{"h2"}); httpsServer = new Http2TestServer(true, diff --git a/test/jdk/java/net/httpclient/http2/FixedThreadPoolTest.java b/test/jdk/java/net/httpclient/http2/FixedThreadPoolTest.java index 68cfe826a0e..0f807c33dff 100644 --- a/test/jdk/java/net/httpclient/http2/FixedThreadPoolTest.java +++ b/test/jdk/java/net/httpclient/http2/FixedThreadPoolTest.java @@ -62,14 +62,12 @@ public class FixedThreadPoolTest { static Http2TestServer httpServer, httpsServer; static HttpClient client = null; static ExecutorService exec; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static String httpURIString, httpsURIString; static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); httpServer = new Http2TestServer(false, 0, exec, sslContext); httpServer.addHandler(new Http2EchoHandler(), "/"); diff --git a/test/jdk/java/net/httpclient/http2/H2GoAwayTest.java b/test/jdk/java/net/httpclient/http2/H2GoAwayTest.java index c5db99ce164..08c32171d16 100644 --- a/test/jdk/java/net/httpclient/http2/H2GoAwayTest.java +++ b/test/jdk/java/net/httpclient/http2/H2GoAwayTest.java @@ -69,12 +69,10 @@ public class H2GoAwayTest { private static final String REQ_PATH = "/test"; private static HttpTestServer server; private static String REQ_URI_BASE; - private static SSLContext sslCtx; + private static final SSLContext sslCtx = SimpleSSLContext.findSSLContext(); @BeforeAll static void beforeAll() throws Exception { - sslCtx = new SimpleSSLContext().get(); - assertNotNull(sslCtx, "SSLContext couldn't be created"); server = HttpTestServer.create(HTTP_2, sslCtx); server.addHandler(new Handler(), REQ_PATH); server.start(); diff --git a/test/jdk/java/net/httpclient/http2/H2SelectorVTTest.java b/test/jdk/java/net/httpclient/http2/H2SelectorVTTest.java index b980df99138..85d4012494a 100644 --- a/test/jdk/java/net/httpclient/http2/H2SelectorVTTest.java +++ b/test/jdk/java/net/httpclient/http2/H2SelectorVTTest.java @@ -110,7 +110,7 @@ import static java.net.http.HttpClient.Version.HTTP_2; // -Djava.security.debug=all class H2SelectorVTTest implements HttpServerAdapters { - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private static HttpTestServer h2Server; private static String requestURI; @@ -135,10 +135,6 @@ class H2SelectorVTTest implements HttpServerAdapters { @BeforeAll static void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } // create a h2 server h2Server = HttpTestServer.create(HTTP_2, sslContext); h2Server.addHandler((exchange) -> exchange.sendResponseHeaders(200, 0), "/hello"); diff --git a/test/jdk/java/net/httpclient/http2/NoBodyTest.java b/test/jdk/java/net/httpclient/http2/NoBodyTest.java index 4dcd99e2c87..3d30c54654a 100644 --- a/test/jdk/java/net/httpclient/http2/NoBodyTest.java +++ b/test/jdk/java/net/httpclient/http2/NoBodyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -57,15 +57,13 @@ public class NoBodyTest { static HttpClient client = null; static ExecutorService clientExec; static ExecutorService serverExec; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static String TEST_STRING = "The quick brown fox jumps over the lazy dog "; static String httpURIString, httpsURIString; static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); httpServer = new Http2TestServer(false, 0, serverExec, sslContext); httpServer.addHandler(new Handler(), "/"); diff --git a/test/jdk/java/net/httpclient/http2/ProxyTest2.java b/test/jdk/java/net/httpclient/http2/ProxyTest2.java index 2fdb1b360e1..762a70b95fd 100644 --- a/test/jdk/java/net/httpclient/http2/ProxyTest2.java +++ b/test/jdk/java/net/httpclient/http2/ProxyTest2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -64,11 +64,7 @@ import java.util.concurrent.*; public class ProxyTest2 { static { - try { - SSLContext.setDefault(new SimpleSSLContext().get()); - } catch (IOException ex) { - throw new ExceptionInInitializerError(ex); - } + SSLContext.setDefault(SimpleSSLContext.findSSLContext()); } static final String RESPONSE = "

    Hello World!"; diff --git a/test/jdk/java/net/httpclient/http2/SimpleGet.java b/test/jdk/java/net/httpclient/http2/SimpleGet.java index 8a65292a65d..692a6583b63 100644 --- a/test/jdk/java/net/httpclient/http2/SimpleGet.java +++ b/test/jdk/java/net/httpclient/http2/SimpleGet.java @@ -70,14 +70,12 @@ import static java.net.http.HttpClient.Version.HTTP_2; public class SimpleGet implements HttpServerAdapters { static HttpTestServer httpsServer; static HttpClient client = null; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static String httpsURIString; static ExecutorService serverExec = Executors.newVirtualThreadPerTaskExecutor(); static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); httpsServer = HttpTestServer.create(HTTP_2, sslContext, serverExec); @@ -94,9 +92,6 @@ public class SimpleGet implements HttpServerAdapters { } private static void warmup() throws Exception { - SimpleSSLContext sslct = new SimpleSSLContext(); - var sslContext = sslct.get(); - // warmup server try (var client2 = createClient(sslContext)) { HttpRequest request = HttpRequest.newBuilder(URI.create(httpsURIString)) diff --git a/test/jdk/java/net/httpclient/http2/StreamFlowControlTest.java b/test/jdk/java/net/httpclient/http2/StreamFlowControlTest.java index 32f96c7ed4b..3edf0b71305 100644 --- a/test/jdk/java/net/httpclient/http2/StreamFlowControlTest.java +++ b/test/jdk/java/net/httpclient/http2/StreamFlowControlTest.java @@ -76,7 +76,7 @@ import static org.testng.Assert.fail; public class StreamFlowControlTest { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer http2TestServer; // HTTP/2 ( h2c ) HttpTestServer https2TestServer; // HTTP/2 ( h2 ) String http2URI; @@ -266,10 +266,6 @@ public class StreamFlowControlTest { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - var http2TestServer = new Http2TestServer("localhost", false, 0); http2TestServer.addHandler(new Http2TestHandler(), "/http2/"); this.http2TestServer = HttpTestServer.of(http2TestServer); diff --git a/test/jdk/java/net/httpclient/http2/UserInfoTest.java b/test/jdk/java/net/httpclient/http2/UserInfoTest.java index 69cded67297..3cea2d92570 100644 --- a/test/jdk/java/net/httpclient/http2/UserInfoTest.java +++ b/test/jdk/java/net/httpclient/http2/UserInfoTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2025, 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 @@ -60,11 +60,10 @@ public class UserInfoTest { static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; Http2TestServer server; int port; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); @BeforeAll void before() throws Exception { - sslContext = new SimpleSSLContext().get(); server = createServer(sslContext); port = server.getAddress().getPort(); server.start(); diff --git a/test/jdk/java/net/httpclient/http3/BadCipherSuiteErrorTest.java b/test/jdk/java/net/httpclient/http3/BadCipherSuiteErrorTest.java index abe6889e497..727f2c78352 100644 --- a/test/jdk/java/net/httpclient/http3/BadCipherSuiteErrorTest.java +++ b/test/jdk/java/net/httpclient/http3/BadCipherSuiteErrorTest.java @@ -65,7 +65,7 @@ public class BadCipherSuiteErrorTest implements HttpServerAdapters { //@Test(timeOut=5000) @Test public void test() throws Exception { - SSLContext sslContext = (new SimpleSSLContext()).get(); + SSLContext sslContext = SimpleSSLContext.findSSLContext(); ExecutorService exec = Executors.newCachedThreadPool(); var builder = newClientBuilderForH3() .executor(exec) @@ -80,7 +80,7 @@ public class BadCipherSuiteErrorTest implements HttpServerAdapters { HttpTestServer httpsServer = null; try { - SSLContext serverContext = (new SimpleSSLContext()).get(); + SSLContext serverContext = SimpleSSLContext.findSSLContext(); SSLParameters p = serverContext.getSupportedSSLParameters(); p.setApplicationProtocols(new String[]{"h3"}); httpsServer = HttpTestServer.create(HTTP_3_URI_ONLY, serverContext); diff --git a/test/jdk/java/net/httpclient/http3/GetHTTP3Test.java b/test/jdk/java/net/httpclient/http3/GetHTTP3Test.java index 14842d401fd..17fc33f3aa5 100644 --- a/test/jdk/java/net/httpclient/http3/GetHTTP3Test.java +++ b/test/jdk/java/net/httpclient/http3/GetHTTP3Test.java @@ -91,7 +91,7 @@ public class GetHTTP3Test implements HttpServerAdapters { May the sun shine warm upon your face; """; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer h3TestServer; // HTTP/2 ( h2 + h3) String h3URI; @@ -400,10 +400,6 @@ public class GetHTTP3Test implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - final Http2TestServer h2WithAltService = new Http2TestServer("localhost", true, sslContext).enableH3AltServiceOnSamePort(); h3TestServer = HttpTestServer.of(h2WithAltService); diff --git a/test/jdk/java/net/httpclient/http3/H3BadHeadersTest.java b/test/jdk/java/net/httpclient/http3/H3BadHeadersTest.java index 3bc59a4d67f..fb0e1ef3085 100644 --- a/test/jdk/java/net/httpclient/http3/H3BadHeadersTest.java +++ b/test/jdk/java/net/httpclient/http3/H3BadHeadersTest.java @@ -75,7 +75,7 @@ public class H3BadHeadersTest implements HttpServerAdapters { static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer http3TestServer; // HTTP/3 ( h3 only ) HttpTestServer https2TestServer; // HTTP/2 ( h2 + h3 ) String http3URI; @@ -272,10 +272,6 @@ public class H3BadHeadersTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { System.out.println("creating servers"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - http3TestServer = HttpTestServer.create(Http3DiscoveryMode.HTTP_3_URI_ONLY, sslContext); http3TestServer.addHandler(new BadHeadersHandler(), "/http3/echo"); http3URI = "https://" + http3TestServer.serverAuthority() + "/http3/echo"; diff --git a/test/jdk/java/net/httpclient/http3/H3BasicTest.java b/test/jdk/java/net/httpclient/http3/H3BasicTest.java index b99520ab830..79002d98995 100644 --- a/test/jdk/java/net/httpclient/http3/H3BasicTest.java +++ b/test/jdk/java/net/httpclient/http3/H3BasicTest.java @@ -84,13 +84,11 @@ public class H3BasicTest implements HttpServerAdapters { static HttpClient client = null; static ExecutorService clientExec; static ExecutorService serverExec; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static volatile String http3URIString, pingURIString, https2URIString; static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); // server that only supports HTTP/3 diff --git a/test/jdk/java/net/httpclient/http3/H3ConcurrentPush.java b/test/jdk/java/net/httpclient/http3/H3ConcurrentPush.java index f0a9a947d13..0cdb2f900fd 100644 --- a/test/jdk/java/net/httpclient/http3/H3ConcurrentPush.java +++ b/test/jdk/java/net/httpclient/http3/H3ConcurrentPush.java @@ -112,7 +112,7 @@ public class H3ConcurrentPush implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - server = HttpTestServer.create(ANY, new SimpleSSLContext().get()); + server = HttpTestServer.create(ANY, SimpleSSLContext.findSSLContext()); pushHandler = new ServerPushHandler(MAIN_RESPONSE_BODY, PUSH_PROMISES); server.addHandler(pushHandler, "/push/"); server.addHandler(new HttpHeadOrGetHandler(), "/head/"); @@ -193,7 +193,7 @@ public class H3ConcurrentPush implements HttpServerAdapters { try (HttpClient client = newClientBuilderForH3() .proxy(Builder.NO_PROXY) .version(Version.HTTP_3) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .build()) { sendHeadRequest(client); diff --git a/test/jdk/java/net/httpclient/http3/H3ConnectionPoolTest.java b/test/jdk/java/net/httpclient/http3/H3ConnectionPoolTest.java index 719067a7c3c..0449db3e961 100644 --- a/test/jdk/java/net/httpclient/http3/H3ConnectionPoolTest.java +++ b/test/jdk/java/net/httpclient/http3/H3ConnectionPoolTest.java @@ -76,7 +76,7 @@ public class H3ConnectionPoolTest implements HttpServerAdapters { static Http3TestServer http3OnlyServer; static Http2TestServer https2AltSvcServer; static volatile HttpClient client = null; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static volatile String http3OnlyURIString, https2URIString, http3AltSvcURIString, http3DirectURIString; static void initialize(boolean samePort) throws Exception { @@ -87,8 +87,6 @@ public class H3ConnectionPoolTest implements HttpServerAdapters { System.out.println("\nConfiguring for advertised AltSvc on " + (samePort ? "same port" : "ephemeral port")); try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = null; client = getClient(); diff --git a/test/jdk/java/net/httpclient/http3/H3DataLimitsTest.java b/test/jdk/java/net/httpclient/http3/H3DataLimitsTest.java index 1443c03bf5d..9f509b5440a 100644 --- a/test/jdk/java/net/httpclient/http3/H3DataLimitsTest.java +++ b/test/jdk/java/net/httpclient/http3/H3DataLimitsTest.java @@ -72,7 +72,7 @@ import static org.testng.Assert.assertEquals; */ public class H3DataLimitsTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer h3TestServer; String h3URI; @@ -210,11 +210,6 @@ public class H3DataLimitsTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } - // An HTTP/3 server that only supports HTTP/3 h3TestServer = HttpTestServer.of(new Http3TestServer(sslContext)); final HttpTestHandler h3Handler = new Handler(); diff --git a/test/jdk/java/net/httpclient/http3/H3ErrorHandlingTest.java b/test/jdk/java/net/httpclient/http3/H3ErrorHandlingTest.java index bb5aeacbb0c..44071ea566d 100644 --- a/test/jdk/java/net/httpclient/http3/H3ErrorHandlingTest.java +++ b/test/jdk/java/net/httpclient/http3/H3ErrorHandlingTest.java @@ -88,7 +88,7 @@ import static org.testng.Assert.*; */ public class H3ErrorHandlingTest implements HttpServerAdapters { - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private QuicStandaloneServer server; private String requestURIBase; @@ -231,10 +231,6 @@ public class H3ErrorHandlingTest implements HttpServerAdapters { @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } server = QuicStandaloneServer.newBuilder() .availableVersions(new QuicVersion[]{QuicVersion.QUIC_V1}) .sslContext(sslContext) diff --git a/test/jdk/java/net/httpclient/http3/H3FixedThreadPoolTest.java b/test/jdk/java/net/httpclient/http3/H3FixedThreadPoolTest.java index 9e801ac2ea4..c513cd092c7 100644 --- a/test/jdk/java/net/httpclient/http3/H3FixedThreadPoolTest.java +++ b/test/jdk/java/net/httpclient/http3/H3FixedThreadPoolTest.java @@ -71,14 +71,12 @@ public class H3FixedThreadPoolTest implements HttpServerAdapters { static HttpTestServer http3Server, https2Server; static volatile HttpClient client = null; static ExecutorService exec; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static String http3URIString, https2URIString; static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); exec = Executors.newCachedThreadPool(); http3Server = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext, exec); diff --git a/test/jdk/java/net/httpclient/http3/H3GoAwayTest.java b/test/jdk/java/net/httpclient/http3/H3GoAwayTest.java index fc6166cb66c..b9d50ce2939 100644 --- a/test/jdk/java/net/httpclient/http3/H3GoAwayTest.java +++ b/test/jdk/java/net/httpclient/http3/H3GoAwayTest.java @@ -67,13 +67,11 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; public class H3GoAwayTest { private static String REQ_URI_BASE; - private static SSLContext sslCtx; + private static final SSLContext sslCtx = SimpleSSLContext.findSSLContext(); private static Http3TestServer server; @BeforeAll static void beforeAll() throws Exception { - sslCtx = new SimpleSSLContext().get(); - assertNotNull(sslCtx, "SSLContext couldn't be created"); server = new Http3TestServer(sslCtx); final RequestApprover reqApprover = new RequestApprover(); server.setRequestApprover(reqApprover::allowNewRequest); diff --git a/test/jdk/java/net/httpclient/http3/H3HeaderSizeLimitTest.java b/test/jdk/java/net/httpclient/http3/H3HeaderSizeLimitTest.java index 06e3c2ac521..b48ef9a33f3 100644 --- a/test/jdk/java/net/httpclient/http3/H3HeaderSizeLimitTest.java +++ b/test/jdk/java/net/httpclient/http3/H3HeaderSizeLimitTest.java @@ -64,16 +64,12 @@ import static java.net.http.HttpOption.H3_DISCOVERY; public class H3HeaderSizeLimitTest implements HttpServerAdapters { private static final long HEADER_SIZE_LIMIT_BYTES = 1024; - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private HttpTestServer h3Server; private String requestURIBase; @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } final QuicServer quicServer = Http3TestServer.quicServerBuilder() .sslContext(sslContext) .build(); diff --git a/test/jdk/java/net/httpclient/http3/H3HeadersEncoding.java b/test/jdk/java/net/httpclient/http3/H3HeadersEncoding.java index e63ae88ed32..44ccfac4a6a 100644 --- a/test/jdk/java/net/httpclient/http3/H3HeadersEncoding.java +++ b/test/jdk/java/net/httpclient/http3/H3HeadersEncoding.java @@ -76,7 +76,7 @@ public class H3HeadersEncoding { private static final int REQUESTS_COUNT = 500; private static final int HEADERS_PER_REQUEST = 20; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer http3TestServer; HeadersHandler serverHeadersHandler; String http3URI; @@ -84,10 +84,6 @@ public class H3HeadersEncoding { @BeforeTest public void setup() throws Exception { System.out.println("Creating servers"); - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - http3TestServer = HttpTestServer.create(Http3DiscoveryMode.HTTP_3_URI_ONLY, sslContext); serverHeadersHandler = new HeadersHandler(); http3TestServer.addHandler(serverHeadersHandler, "/http3/headers"); diff --git a/test/jdk/java/net/httpclient/http3/H3IdleExceedsQuicIdleTimeout.java b/test/jdk/java/net/httpclient/http3/H3IdleExceedsQuicIdleTimeout.java index 6b62fcf6043..1028eefe828 100644 --- a/test/jdk/java/net/httpclient/http3/H3IdleExceedsQuicIdleTimeout.java +++ b/test/jdk/java/net/httpclient/http3/H3IdleExceedsQuicIdleTimeout.java @@ -70,12 +70,10 @@ class H3IdleExceedsQuicIdleTimeout { private static final String REQ_PATH = "/8371802"; private static HttpTestServer h3Server; - private static SSLContext sslCtx; + private static final SSLContext sslCtx = SimpleSSLContext.findSSLContext(); @BeforeAll static void beforeAll() throws Exception { - sslCtx = new SimpleSSLContext().get(); - assert sslCtx != null : "SSLContext is null"; h3Server = HttpTestServer.create(HTTP_3_URI_ONLY, sslCtx); h3Server.addHandler(new Handler(), REQ_PATH); h3Server.start(); diff --git a/test/jdk/java/net/httpclient/http3/H3ImplicitPushCancel.java b/test/jdk/java/net/httpclient/http3/H3ImplicitPushCancel.java index 735a68c88cf..130ccd40cd6 100644 --- a/test/jdk/java/net/httpclient/http3/H3ImplicitPushCancel.java +++ b/test/jdk/java/net/httpclient/http3/H3ImplicitPushCancel.java @@ -85,7 +85,7 @@ public class H3ImplicitPushCancel implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - server = HttpTestServer.create(ANY, new SimpleSSLContext().get()); + server = HttpTestServer.create(ANY, SimpleSSLContext.findSSLContext()); HttpTestHandler pushHandler = new ServerPushHandler(MAIN_RESPONSE_BODY, PUSH_PROMISES); server.addHandler(pushHandler, "/push/"); @@ -125,7 +125,7 @@ public class H3ImplicitPushCancel implements HttpServerAdapters { try (HttpClient client = newClientBuilderForH3() .proxy(Builder.NO_PROXY) .version(Version.HTTP_3) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .build()) { sendHeadRequest(client); diff --git a/test/jdk/java/net/httpclient/http3/H3InsertionsLimitTest.java b/test/jdk/java/net/httpclient/http3/H3InsertionsLimitTest.java index 19c19561cf9..ff38cd4fa98 100644 --- a/test/jdk/java/net/httpclient/http3/H3InsertionsLimitTest.java +++ b/test/jdk/java/net/httpclient/http3/H3InsertionsLimitTest.java @@ -74,7 +74,7 @@ public class H3InsertionsLimitTest implements HttpServerAdapters { private static final long HEADER_SIZE_LIMIT_BYTES = 8192; private static final long MAX_SERVER_DT_CAPACITY = 4096; - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private HttpTestServer h3Server; private String requestURIBase; public static final long MAX_LITERALS_WITH_INDEXING = 32L; @@ -122,10 +122,6 @@ public class H3InsertionsLimitTest implements HttpServerAdapters { @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } final QuicServer quicServer = Http3TestServer.quicServerBuilder() .bindAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)) .sslContext(sslContext) diff --git a/test/jdk/java/net/httpclient/http3/H3LogHandshakeErrors.java b/test/jdk/java/net/httpclient/http3/H3LogHandshakeErrors.java index 32872f4fb12..f7a258c069c 100644 --- a/test/jdk/java/net/httpclient/http3/H3LogHandshakeErrors.java +++ b/test/jdk/java/net/httpclient/http3/H3LogHandshakeErrors.java @@ -70,7 +70,7 @@ import static org.testng.Assert.*; // -Djava.security.debug=all public class H3LogHandshakeErrors implements HttpServerAdapters { - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private HttpTestServer h3Server; private ServerSocket tcpServerSocket = null; private Thread tcpServerThread = null; @@ -79,10 +79,6 @@ public class H3LogHandshakeErrors implements HttpServerAdapters { @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } // create an H3 only server h3Server = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext); h3Server.addHandler((exchange) -> exchange.sendResponseHeaders(200, 0), "/hello"); diff --git a/test/jdk/java/net/httpclient/http3/H3MalformedResponseTest.java b/test/jdk/java/net/httpclient/http3/H3MalformedResponseTest.java index ea1efaf4933..5ef45f8b230 100644 --- a/test/jdk/java/net/httpclient/http3/H3MalformedResponseTest.java +++ b/test/jdk/java/net/httpclient/http3/H3MalformedResponseTest.java @@ -51,7 +51,6 @@ import static java.net.http.HttpOption.H3_DISCOVERY; import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; /* @@ -133,7 +132,7 @@ class H3MalformedResponseTest { private static final Logger LOGGER = Utils.getDebugLogger(CLASS_NAME::toString, Utils.DEBUG); - private static SSLContext SSL_CONTEXT; + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); private static QuicStandaloneServer SERVER; @@ -142,10 +141,6 @@ class H3MalformedResponseTest { @BeforeAll static void setUp() throws Exception { - // Obtain an `SSLContext` - SSL_CONTEXT = new SimpleSSLContext().get(); - assertNotNull(SSL_CONTEXT); - // Create and start the server SERVER = QuicStandaloneServer.newBuilder() .availableVersions(new QuicVersion[]{QuicVersion.QUIC_V1}) diff --git a/test/jdk/java/net/httpclient/http3/H3MaxInitialTimeoutTest.java b/test/jdk/java/net/httpclient/http3/H3MaxInitialTimeoutTest.java index 30f48c56454..27eec672bcd 100644 --- a/test/jdk/java/net/httpclient/http3/H3MaxInitialTimeoutTest.java +++ b/test/jdk/java/net/httpclient/http3/H3MaxInitialTimeoutTest.java @@ -83,7 +83,7 @@ import static org.testng.Assert.assertEquals; */ public class H3MaxInitialTimeoutTest implements HttpServerAdapters { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); DatagramChannel receiver; String h3URI; @@ -224,10 +224,6 @@ public class H3MaxInitialTimeoutTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } receiver = DatagramChannel.open(); receiver.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); h3URI = URIBuilder.newBuilder() diff --git a/test/jdk/java/net/httpclient/http3/H3MemoryHandlingTest.java b/test/jdk/java/net/httpclient/http3/H3MemoryHandlingTest.java index f270297d85c..c9474be51c2 100644 --- a/test/jdk/java/net/httpclient/http3/H3MemoryHandlingTest.java +++ b/test/jdk/java/net/httpclient/http3/H3MemoryHandlingTest.java @@ -70,16 +70,12 @@ import static org.testng.Assert.*; */ public class H3MemoryHandlingTest implements HttpServerAdapters { - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private QuicStandaloneServer server; private String requestURIBase; @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } server = QuicStandaloneServer.newBuilder() .availableVersions(new QuicVersion[]{QuicVersion.QUIC_V1}) .sslContext(sslContext) diff --git a/test/jdk/java/net/httpclient/http3/H3MultipleConnectionsToSameHost.java b/test/jdk/java/net/httpclient/http3/H3MultipleConnectionsToSameHost.java index 2e4047cf5ea..14149da7815 100644 --- a/test/jdk/java/net/httpclient/http3/H3MultipleConnectionsToSameHost.java +++ b/test/jdk/java/net/httpclient/http3/H3MultipleConnectionsToSameHost.java @@ -172,7 +172,7 @@ import static jdk.internal.net.http.Http3ClientProperties.MAX_STREAM_LIMIT_WAIT_ public class H3MultipleConnectionsToSameHost implements HttpServerAdapters { static HttpTestServer httpsServer; static HttpClient client = null; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static String httpsURIString; static ExecutorService serverExec = Executors.newThreadPerTaskExecutor(Thread.ofVirtual() @@ -180,8 +180,6 @@ public class H3MultipleConnectionsToSameHost implements HttpServerAdapters { static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); httpsServer = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext, serverExec); @@ -198,9 +196,6 @@ public class H3MultipleConnectionsToSameHost implements HttpServerAdapters { } private static void warmup() throws Exception { - SimpleSSLContext sslct = new SimpleSSLContext(); - var sslContext = sslct.get(); - // warmup server try (var client2 = createClient(sslContext, Executors.newVirtualThreadPerTaskExecutor())) { HttpRequest request = HttpRequest.newBuilder(URI.create(httpsURIString)) diff --git a/test/jdk/java/net/httpclient/http3/H3ProxyTest.java b/test/jdk/java/net/httpclient/http3/H3ProxyTest.java index 4555f259e07..58deeec1982 100644 --- a/test/jdk/java/net/httpclient/http3/H3ProxyTest.java +++ b/test/jdk/java/net/httpclient/http3/H3ProxyTest.java @@ -65,11 +65,7 @@ import static java.net.http.HttpOption.H3_DISCOVERY; public class H3ProxyTest implements HttpServerAdapters { static { - try { - SSLContext.setDefault(new SimpleSSLContext().get()); - } catch (IOException ex) { - throw new ExceptionInInitializerError(ex); - } + SSLContext.setDefault(SimpleSSLContext.findSSLContext()); } static final String RESPONSE = "

    Hello World!"; @@ -157,7 +153,7 @@ public class H3ProxyTest implements HttpServerAdapters { InetSocketAddress.createUnresolved("localhost", proxy.getAddress().getPort())); HttpClient client = HttpServerAdapters.createClientBuilderForH3() .version(Version.HTTP_3) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .proxy(ps) .build(); try (client) { diff --git a/test/jdk/java/net/httpclient/http3/H3PushCancel.java b/test/jdk/java/net/httpclient/http3/H3PushCancel.java index a5293444ade..324942b67d0 100644 --- a/test/jdk/java/net/httpclient/http3/H3PushCancel.java +++ b/test/jdk/java/net/httpclient/http3/H3PushCancel.java @@ -100,7 +100,7 @@ public class H3PushCancel implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - server = HttpTestServer.create(ANY, new SimpleSSLContext().get()); + server = HttpTestServer.create(ANY, SimpleSSLContext.findSSLContext()); pushHandler = new ServerPushHandler(MAIN_RESPONSE_BODY, PUSH_PROMISES); server.addHandler(pushHandler, "/push/"); server.addHandler(new HttpHeadOrGetHandler(), "/head/"); @@ -137,7 +137,7 @@ public class H3PushCancel implements HttpServerAdapters { try (HttpClient client = newClientBuilderForH3() .proxy(Builder.NO_PROXY) .version(Version.HTTP_3) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .build()) { sendHeadRequest(client); @@ -243,7 +243,7 @@ public class H3PushCancel implements HttpServerAdapters { try (HttpClient client = newClientBuilderForH3() .proxy(Builder.NO_PROXY) .version(Version.HTTP_3) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .build()) { sendHeadRequest(client); diff --git a/test/jdk/java/net/httpclient/http3/H3QuicTLSConnection.java b/test/jdk/java/net/httpclient/http3/H3QuicTLSConnection.java index cd699e7774d..6086c26729b 100644 --- a/test/jdk/java/net/httpclient/http3/H3QuicTLSConnection.java +++ b/test/jdk/java/net/httpclient/http3/H3QuicTLSConnection.java @@ -83,7 +83,7 @@ public class H3QuicTLSConnection { public static void main(String[] args) throws Exception { // create and set the default SSLContext - SSLContext context = new SimpleSSLContext().get(); + SSLContext context = SimpleSSLContext.findSSLContext(); SSLContext.setDefault(context); Handler handler = new Handler(); diff --git a/test/jdk/java/net/httpclient/http3/H3QuicVTTest.java b/test/jdk/java/net/httpclient/http3/H3QuicVTTest.java index b00f6b1522d..7ea24d81ded 100644 --- a/test/jdk/java/net/httpclient/http3/H3QuicVTTest.java +++ b/test/jdk/java/net/httpclient/http3/H3QuicVTTest.java @@ -114,7 +114,7 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY; // -Djava.security.debug=all class H3QuicVTTest implements HttpServerAdapters { - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private static HttpTestServer h3Server; private static String requestURI; @@ -139,10 +139,6 @@ class H3QuicVTTest implements HttpServerAdapters { @BeforeAll static void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } // create an H3 only server h3Server = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext); h3Server.addHandler((exchange) -> exchange.sendResponseHeaders(200, 0), "/hello"); diff --git a/test/jdk/java/net/httpclient/http3/H3RedirectTest.java b/test/jdk/java/net/httpclient/http3/H3RedirectTest.java index 4f6fbaeef6f..0a5546bc1c1 100644 --- a/test/jdk/java/net/httpclient/http3/H3RedirectTest.java +++ b/test/jdk/java/net/httpclient/http3/H3RedirectTest.java @@ -57,7 +57,7 @@ import static java.net.http.HttpOption.H3_DISCOVERY; public class H3RedirectTest implements HttpServerAdapters { static int httpPort; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static HttpTestServer http3Server; static HttpClient client; @@ -106,8 +106,6 @@ public class H3RedirectTest implements HttpServerAdapters { static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); http3Server = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext); httpPort = http3Server.getAddress().getPort(); diff --git a/test/jdk/java/net/httpclient/http3/H3RequestRejectedTest.java b/test/jdk/java/net/httpclient/http3/H3RequestRejectedTest.java index 1731ddae833..834011bf4f5 100644 --- a/test/jdk/java/net/httpclient/http3/H3RequestRejectedTest.java +++ b/test/jdk/java/net/httpclient/http3/H3RequestRejectedTest.java @@ -72,12 +72,10 @@ class H3RequestRejectedTest { private static final String HANDLER_PATH = "/foo"; private static HttpTestServer server; - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); @BeforeAll static void beforeAll() throws Exception { - sslContext = new SimpleSSLContext().get(); - assertNotNull(sslContext, "SSLContext could not be constructed"); server = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext); server.addHandler(new Handler(), HANDLER_PATH); server.start(); diff --git a/test/jdk/java/net/httpclient/http3/H3ServerPush.java b/test/jdk/java/net/httpclient/http3/H3ServerPush.java index 4b271320b0d..83f68a15579 100644 --- a/test/jdk/java/net/httpclient/http3/H3ServerPush.java +++ b/test/jdk/java/net/httpclient/http3/H3ServerPush.java @@ -90,7 +90,7 @@ public class H3ServerPush implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { tempFile = createTempFileOfSize(CLASS_NAME, ".dat", FILE_SIZE); - var sslContext = new SimpleSSLContext().get(); + var sslContext = SimpleSSLContext.findSSLContext(); var h2Server = new Http2TestServer(true, sslContext); h2Server.enableH3AltServiceOnSamePort(); h2Server.addHandler(new PushHandler(tempFile, LOOPS), "/foo/"); @@ -133,7 +133,7 @@ public class H3ServerPush implements HttpServerAdapters { }; try (HttpClient client = newClientBuilderForH3().proxy(Builder.NO_PROXY) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .version(Version.HTTP_3).build()) { sendHeadRequest(client); @@ -183,7 +183,7 @@ public class H3ServerPush implements HttpServerAdapters { PushPromiseHandler.of(pushPromise -> BodyHandlers.ofString(UTF_8), resultMap); try (HttpClient client = newClientBuilderForH3().proxy(Builder.NO_PROXY) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .version(Version.HTTP_3).build()) { sendHeadRequest(client); HttpRequest request = HttpRequest.newBuilder(uri).GET().build(); @@ -231,7 +231,7 @@ public class H3ServerPush implements HttpServerAdapters { }; try (HttpClient client = newClientBuilderForH3().proxy(Builder.NO_PROXY) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .version(Version.HTTP_3).build()) { sendHeadRequest(client); @@ -263,7 +263,7 @@ public class H3ServerPush implements HttpServerAdapters { PushPromiseHandler.of(H3ServerPush::requestToPath, resultsMap); try (HttpClient client = newClientBuilderForH3().proxy(Builder.NO_PROXY) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .version(Version.HTTP_3).build()) { sendHeadRequest(client); @@ -316,7 +316,7 @@ public class H3ServerPush implements HttpServerAdapters { = new ConcurrentHashMap<>(); try (HttpClient client = newClientBuilderForH3().proxy(Builder.NO_PROXY) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .version(Version.HTTP_3).build()) { sendHeadRequest(client); @@ -361,7 +361,7 @@ public class H3ServerPush implements HttpServerAdapters { = new ConcurrentHashMap<>(); try (HttpClient client = newClientBuilderForH3().proxy(Builder.NO_PROXY) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .version(Version.HTTP_3).build()) { sendHeadRequest(client); diff --git a/test/jdk/java/net/httpclient/http3/H3ServerPushCancel.java b/test/jdk/java/net/httpclient/http3/H3ServerPushCancel.java index 32ca87e20f5..312b9ac507d 100644 --- a/test/jdk/java/net/httpclient/http3/H3ServerPushCancel.java +++ b/test/jdk/java/net/httpclient/http3/H3ServerPushCancel.java @@ -116,7 +116,7 @@ public class H3ServerPushCancel implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - server = HttpTestServer.create(ANY, new SimpleSSLContext().get()); + server = HttpTestServer.create(ANY, SimpleSSLContext.findSSLContext()); pushHandler = new ServerPushHandler(MAIN_RESPONSE_BODY, PUSH_PROMISES); server.addHandler(pushHandler, "/push/"); server.addHandler(new HttpHeadOrGetHandler(), "/head/"); @@ -222,7 +222,7 @@ public class H3ServerPushCancel implements HttpServerAdapters { try (HttpClient client = newClientBuilderForH3() .proxy(Builder.NO_PROXY) .version(HTTP_3) - .sslContext(new SimpleSSLContext().get()) + .sslContext(SimpleSSLContext.findSSLContext()) .build()) { sendHeadRequest(client); diff --git a/test/jdk/java/net/httpclient/http3/H3ServerPushTest.java b/test/jdk/java/net/httpclient/http3/H3ServerPushTest.java index ed5a14d8576..00fe651c9cf 100644 --- a/test/jdk/java/net/httpclient/http3/H3ServerPushTest.java +++ b/test/jdk/java/net/httpclient/http3/H3ServerPushTest.java @@ -95,15 +95,7 @@ class H3ServerPushTest { private static final HttpHeaders EMPTY_HEADERS = HttpHeaders.of(Map.of(), (_, _) -> false); - private static final SSLContext SSL_CONTEXT = createSslContext(); - - private static SSLContext createSslContext() { - try { - return new SimpleSSLContext().get(); - } catch (IOException exception) { - throw new RuntimeException(exception); - } - } + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); @Test @Order(1) diff --git a/test/jdk/java/net/httpclient/http3/H3ServerPushWithDiffTypes.java b/test/jdk/java/net/httpclient/http3/H3ServerPushWithDiffTypes.java index af22651f0a0..d00012826ef 100644 --- a/test/jdk/java/net/httpclient/http3/H3ServerPushWithDiffTypes.java +++ b/test/jdk/java/net/httpclient/http3/H3ServerPushWithDiffTypes.java @@ -95,7 +95,7 @@ public class H3ServerPushWithDiffTypes implements HttpServerAdapters { @Test public void test() throws Exception { - var sslContext = new SimpleSSLContext().get(); + var sslContext = SimpleSSLContext.findSSLContext(); try (HttpTestServer server = HttpTestServer.create(ANY, sslContext)) { HttpTestHandler pushHandler = new ServerPushHandler("the main response body", diff --git a/test/jdk/java/net/httpclient/http3/H3SimpleGet.java b/test/jdk/java/net/httpclient/http3/H3SimpleGet.java index fe0217e64b6..3745c32afbf 100644 --- a/test/jdk/java/net/httpclient/http3/H3SimpleGet.java +++ b/test/jdk/java/net/httpclient/http3/H3SimpleGet.java @@ -208,7 +208,7 @@ import static java.net.http.HttpOption.H3_DISCOVERY; public class H3SimpleGet implements HttpServerAdapters { static HttpTestServer httpsServer; static HttpClient client = null; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static String httpsURIString; static ExecutorService serverExec = Executors.newThreadPerTaskExecutor(Thread.ofVirtual() @@ -216,8 +216,6 @@ public class H3SimpleGet implements HttpServerAdapters { static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); httpsServer = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext, serverExec); @@ -234,9 +232,6 @@ public class H3SimpleGet implements HttpServerAdapters { } private static void warmup() throws Exception { - SimpleSSLContext sslct = new SimpleSSLContext(); - var sslContext = sslct.get(); - // warmup server try (var client2 = createClient(sslContext, Executors.newThreadPerTaskExecutor( Thread.ofVirtual().name("client-2-vt-worker", 1).factory()))) { diff --git a/test/jdk/java/net/httpclient/http3/H3SimplePost.java b/test/jdk/java/net/httpclient/http3/H3SimplePost.java index dc8848947b3..4cf46988873 100644 --- a/test/jdk/java/net/httpclient/http3/H3SimplePost.java +++ b/test/jdk/java/net/httpclient/http3/H3SimplePost.java @@ -64,7 +64,7 @@ import static java.net.http.HttpOption.H3_DISCOVERY; public class H3SimplePost implements HttpServerAdapters { static HttpTestServer httpsServer; static HttpClient client = null; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static String httpsURIString; static ExecutorService serverExec = Executors.newThreadPerTaskExecutor(Thread.ofVirtual() @@ -72,8 +72,6 @@ public class H3SimplePost implements HttpServerAdapters { static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); httpsServer = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext, serverExec); @@ -90,9 +88,6 @@ public class H3SimplePost implements HttpServerAdapters { } private static void warmup() throws Exception { - SimpleSSLContext sslct = new SimpleSSLContext(); - var sslContext = sslct.get(); - // warmup server try (var client2 = createClient(sslContext, Executors.newVirtualThreadPerTaskExecutor())) { HttpRequest request = HttpRequest.newBuilder(URI.create(httpsURIString)) diff --git a/test/jdk/java/net/httpclient/http3/H3SimpleTest.java b/test/jdk/java/net/httpclient/http3/H3SimpleTest.java index 8531f10bea7..1880d436501 100644 --- a/test/jdk/java/net/httpclient/http3/H3SimpleTest.java +++ b/test/jdk/java/net/httpclient/http3/H3SimpleTest.java @@ -73,16 +73,12 @@ import static java.net.http.HttpOption.H3_DISCOVERY; // -Djava.security.debug=all public class H3SimpleTest implements HttpServerAdapters { - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private HttpTestServer h3Server; private String requestURI; @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } // create an H3 only server h3Server = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext); h3Server.addHandler((exchange) -> exchange.sendResponseHeaders(200, 0), "/hello"); diff --git a/test/jdk/java/net/httpclient/http3/H3StopSendingTest.java b/test/jdk/java/net/httpclient/http3/H3StopSendingTest.java index 1855cdba6ff..5b017c15d9b 100644 --- a/test/jdk/java/net/httpclient/http3/H3StopSendingTest.java +++ b/test/jdk/java/net/httpclient/http3/H3StopSendingTest.java @@ -61,7 +61,7 @@ public class H3StopSendingTest { HttpRequest postRequestNoError, postRequestError; HttpRequest postRequestNoErrorWithData, postRequestErrorWithData; URI h3TestServerUriNoError, h3TestServerUriError; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static final String TEST_ROOT_PATH = "/h3_stop_sending_test"; static final String NO_ERROR_PATH = TEST_ROOT_PATH + "/no_error_path"; @@ -128,7 +128,6 @@ public class H3StopSendingTest { @BeforeTest public void setup() throws IOException { - sslContext = new SimpleSSLContext().get(); h3TestServer = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext); h3TestServer.addHandler(new ServerRequestStopSendingHandler(), TEST_ROOT_PATH); h3TestServerUriError = URI.create("https://" + h3TestServer.serverAuthority() + ERROR_PATH); diff --git a/test/jdk/java/net/httpclient/http3/H3StreamLimitReachedTest.java b/test/jdk/java/net/httpclient/http3/H3StreamLimitReachedTest.java index 0de80c6d587..a4524b9ae5e 100644 --- a/test/jdk/java/net/httpclient/http3/H3StreamLimitReachedTest.java +++ b/test/jdk/java/net/httpclient/http3/H3StreamLimitReachedTest.java @@ -135,7 +135,7 @@ public class H3StreamLimitReachedTest implements HttpServerAdapters { static Http3TestServer http3OnlyServer; static Http2TestServer https2AltSvcServer; static volatile HttpClient client = null; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static volatile String http3OnlyURIString, https2URIString, http3AltSvcURIString, http3DirectURIString; static void initialize(boolean samePort) throws Exception { @@ -149,8 +149,6 @@ public class H3StreamLimitReachedTest implements HttpServerAdapters { System.out.println("\nConfiguring for advertised AltSvc on " + (samePort ? "same port" : "ephemeral port")); try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = null; client = getClient(); diff --git a/test/jdk/java/net/httpclient/http3/H3Timeout.java b/test/jdk/java/net/httpclient/http3/H3Timeout.java index 81a0f87467b..fedb4d46952 100644 --- a/test/jdk/java/net/httpclient/http3/H3Timeout.java +++ b/test/jdk/java/net/httpclient/http3/H3Timeout.java @@ -61,7 +61,7 @@ public class H3Timeout implements HttpServerAdapters { private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; public static void main(String[] args) throws Exception { - SSLContext context = new SimpleSSLContext().get(); + SSLContext context = SimpleSSLContext.findSSLContext(); testConnect(context, false); testConnect(context, true); testTimeout(context, false); diff --git a/test/jdk/java/net/httpclient/http3/H3UserInfoTest.java b/test/jdk/java/net/httpclient/http3/H3UserInfoTest.java index 15e25b865cd..8eaad2ce4de 100644 --- a/test/jdk/java/net/httpclient/http3/H3UserInfoTest.java +++ b/test/jdk/java/net/httpclient/http3/H3UserInfoTest.java @@ -70,11 +70,10 @@ public class H3UserInfoTest implements HttpServerAdapters { static HttpTestServer server3; static String serverURI; static String server3URI; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); @BeforeAll static void before() throws Exception { - sslContext = new SimpleSSLContext().get(); HttpTestHandler handler = new HttpHandler(); server = HttpTestServer.create(ANY, sslContext); diff --git a/test/jdk/java/net/httpclient/http3/HTTP3NoBodyTest.java b/test/jdk/java/net/httpclient/http3/HTTP3NoBodyTest.java index f04588e9362..601e40c7dc6 100644 --- a/test/jdk/java/net/httpclient/http3/HTTP3NoBodyTest.java +++ b/test/jdk/java/net/httpclient/http3/HTTP3NoBodyTest.java @@ -76,15 +76,13 @@ public class HTTP3NoBodyTest { static HttpClient client = null; static ExecutorService clientExec; static ExecutorService serverExec; - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); static final String TEST_STRING = "The quick brown fox jumps over the lazy dog "; static volatile String http3URIString, https2URIString; static void initialize() throws Exception { try { - SimpleSSLContext sslct = new SimpleSSLContext(); - sslContext = sslct.get(); client = getClient(); // server that only supports HTTP/3 diff --git a/test/jdk/java/net/httpclient/http3/Http3ExpectContinueTest.java b/test/jdk/java/net/httpclient/http3/Http3ExpectContinueTest.java index 2052671b697..53ce6a68d38 100644 --- a/test/jdk/java/net/httpclient/http3/Http3ExpectContinueTest.java +++ b/test/jdk/java/net/httpclient/http3/Http3ExpectContinueTest.java @@ -76,7 +76,7 @@ public class Http3ExpectContinueTest implements HttpServerAdapters { static final String CONTINUE_100 = "100 Continue"; static final String RESPONSE_BODY= "Verify response received"; static final String BODY = "Post body"; - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); @DataProvider(name = "uris") public Object[][] urisData() { @@ -151,10 +151,6 @@ public class Http3ExpectContinueTest implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } final QuicServer quicServer = Http3TestServer.quicServerBuilder() .sslContext(sslContext) .build(); diff --git a/test/jdk/java/net/httpclient/http3/PostHTTP3Test.java b/test/jdk/java/net/httpclient/http3/PostHTTP3Test.java index 8bb6515d4ff..90f2c41f4e5 100644 --- a/test/jdk/java/net/httpclient/http3/PostHTTP3Test.java +++ b/test/jdk/java/net/httpclient/http3/PostHTTP3Test.java @@ -96,7 +96,7 @@ public class PostHTTP3Test implements HttpServerAdapters { May the sun shine warm upon your face; """; - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpTestServer h3TestServer; // HTTP/2 ( h2 + h3) String h3URI; @@ -443,9 +443,6 @@ public class PostHTTP3Test implements HttpServerAdapters { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); final Http2TestServer h2WithAltService = new Http2TestServer("localhost", true, sslContext) .enableH3AltServiceOnSamePort(); h3TestServer = HttpTestServer.of(h2WithAltService); diff --git a/test/jdk/java/net/httpclient/http3/StopSendingTest.java b/test/jdk/java/net/httpclient/http3/StopSendingTest.java index 2a029e176a2..ff1b8db7bc8 100644 --- a/test/jdk/java/net/httpclient/http3/StopSendingTest.java +++ b/test/jdk/java/net/httpclient/http3/StopSendingTest.java @@ -64,16 +64,12 @@ import static java.net.http.HttpOption.H3_DISCOVERY; */ public class StopSendingTest implements HttpServerAdapters { - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private HttpTestServer h3Server; private String requestURIBase; @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } h3Server = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext); h3Server.addHandler(new Handler(), "/hello"); h3Server.start(); diff --git a/test/jdk/java/net/httpclient/http3/StreamLimitTest.java b/test/jdk/java/net/httpclient/http3/StreamLimitTest.java index 105417950a1..e0610cf89b8 100644 --- a/test/jdk/java/net/httpclient/http3/StreamLimitTest.java +++ b/test/jdk/java/net/httpclient/http3/StreamLimitTest.java @@ -68,7 +68,7 @@ import static java.net.http.HttpOption.H3_DISCOVERY; */ public class StreamLimitTest { - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private HttpTestServer server; private QuicServer quicServer; private URI requestURI; @@ -99,10 +99,6 @@ public class StreamLimitTest { @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } quicServer = Http3TestServer.quicServerBuilder().sslContext(sslContext).build(); final Http3TestServer h3Server = new Http3TestServer(quicServer) { @Override diff --git a/test/jdk/java/net/httpclient/quic/KeyUpdateTest.java b/test/jdk/java/net/httpclient/quic/KeyUpdateTest.java index 631a054b2f9..d6d287be9e0 100644 --- a/test/jdk/java/net/httpclient/quic/KeyUpdateTest.java +++ b/test/jdk/java/net/httpclient/quic/KeyUpdateTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -86,7 +86,7 @@ import static org.testng.Assert.assertTrue; public class KeyUpdateTest { private QuicStandaloneServer server; - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private ExecutorService executor; private static final byte[] HELLO_MSG = "Hello Quic".getBytes(StandardCharsets.UTF_8); @@ -94,10 +94,6 @@ public class KeyUpdateTest { @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } executor = Executors.newCachedThreadPool(); server = QuicStandaloneServer.newBuilder() .availableVersions(new QuicVersion[]{QuicVersion.QUIC_V1}) diff --git a/test/jdk/java/net/httpclient/quic/PacketLossTest.java b/test/jdk/java/net/httpclient/quic/PacketLossTest.java index 1298e0977de..1f75e1feb95 100644 --- a/test/jdk/java/net/httpclient/quic/PacketLossTest.java +++ b/test/jdk/java/net/httpclient/quic/PacketLossTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -67,17 +67,13 @@ import org.junit.jupiter.api.Test; */ public class PacketLossTest { - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private static ExecutorService executor; private static final byte[] HELLO_MSG = "Hello Quic".getBytes(StandardCharsets.UTF_8); @BeforeAll public static void beforeAll() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } executor = Executors.newCachedThreadPool(); } diff --git a/test/jdk/java/net/httpclient/quic/QuicRequestResponseTest.java b/test/jdk/java/net/httpclient/quic/QuicRequestResponseTest.java index 2c5844dc4c4..9d5c35f5414 100644 --- a/test/jdk/java/net/httpclient/quic/QuicRequestResponseTest.java +++ b/test/jdk/java/net/httpclient/quic/QuicRequestResponseTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -59,17 +59,13 @@ import org.testng.annotations.Test; public class QuicRequestResponseTest { private QuicStandaloneServer server; - private SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private ExecutorService executor; private static final byte[] HELLO_MSG = "Hello Quic".getBytes(StandardCharsets.UTF_8); @BeforeClass public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } executor = Executors.newCachedThreadPool(); server = QuicStandaloneServer.newBuilder() .availableVersions(new QuicVersion[]{QuicVersion.QUIC_V1}) diff --git a/test/jdk/java/net/httpclient/quic/StatelessResetReceiptTest.java b/test/jdk/java/net/httpclient/quic/StatelessResetReceiptTest.java index bee56824381..a20494095bd 100644 --- a/test/jdk/java/net/httpclient/quic/StatelessResetReceiptTest.java +++ b/test/jdk/java/net/httpclient/quic/StatelessResetReceiptTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, 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 @@ -76,15 +76,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class StatelessResetReceiptTest { private static QuicStandaloneServer server; - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private static ExecutorService executor; @BeforeAll static void beforeAll() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } executor = Executors.newCachedThreadPool(); server = QuicStandaloneServer.newBuilder() .availableVersions(new QuicVersion[]{QuicVersion.QUIC_V1}) diff --git a/test/jdk/java/net/httpclient/quic/VersionNegotiationTest.java b/test/jdk/java/net/httpclient/quic/VersionNegotiationTest.java index d0de5ce9a60..973477a63dc 100644 --- a/test/jdk/java/net/httpclient/quic/VersionNegotiationTest.java +++ b/test/jdk/java/net/httpclient/quic/VersionNegotiationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -61,15 +61,11 @@ import static org.testng.Assert.expectThrows; */ public class VersionNegotiationTest { - private static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private static ExecutorService executor; @BeforeClass public static void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); - } executor = Executors.newCachedThreadPool(); } diff --git a/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineBadParametersTest.java b/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineBadParametersTest.java index e6a99caebad..0b7e6875b96 100644 --- a/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineBadParametersTest.java +++ b/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineBadParametersTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -50,7 +50,7 @@ public class QuicTLSEngineBadParametersTest { @Test void testServerConsumerExceptionPropagated() throws IOException { - SSLContext ctx = SimpleSSLContext.getContext("TLSv1.3"); + SSLContext ctx = SimpleSSLContext.findSSLContext("TLSv1.3"); QuicTLSContext qctx = new QuicTLSContext(ctx); QuicTLSEngine clientEngine = createClientEngine(qctx); QuicTLSEngine serverEngine = createServerEngine(qctx); @@ -68,7 +68,7 @@ public class QuicTLSEngineBadParametersTest { @Test void testClientConsumerExceptionPropagated() throws IOException, QuicTransportException { - SSLContext ctx = SimpleSSLContext.getContext("TLSv1.3"); + SSLContext ctx = SimpleSSLContext.findSSLContext("TLSv1.3"); QuicTLSContext qctx = new QuicTLSContext(ctx); QuicTLSEngine clientEngine = createClientEngine(qctx); QuicTLSEngine serverEngine = createServerEngine(qctx); diff --git a/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineFailedALPNTest.java b/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineFailedALPNTest.java index fa7df3bc5c3..5767d81cc83 100644 --- a/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineFailedALPNTest.java +++ b/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineFailedALPNTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -48,7 +48,7 @@ public class QuicTLSEngineFailedALPNTest { @Test void testServerRequiresALPN() throws IOException { - SSLContext ctx = SimpleSSLContext.getContext("TLSv1.3"); + SSLContext ctx = SimpleSSLContext.findSSLContext("TLSv1.3"); QuicTLSContext qctx = new QuicTLSContext(ctx); QuicTLSEngine clientEngine = createClientEngine(qctx); QuicTLSEngine serverEngine = createServerEngine(qctx); @@ -63,7 +63,7 @@ public class QuicTLSEngineFailedALPNTest { @Test void testClientRequiresALPN() throws IOException, QuicTransportException { - SSLContext ctx = SimpleSSLContext.getContext("TLSv1.3"); + SSLContext ctx = SimpleSSLContext.findSSLContext("TLSv1.3"); QuicTLSContext qctx = new QuicTLSContext(ctx); QuicTLSEngine clientEngine = createClientEngine(qctx); QuicTLSEngine serverEngine = createServerEngine(qctx); diff --git a/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineMissingParametersTest.java b/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineMissingParametersTest.java index da9f06785a2..933d258f912 100644 --- a/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineMissingParametersTest.java +++ b/test/jdk/java/net/httpclient/quic/tls/QuicTLSEngineMissingParametersTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -48,7 +48,7 @@ public class QuicTLSEngineMissingParametersTest { @Test void testServerRequiresTransportParameters() throws IOException { - SSLContext ctx = SimpleSSLContext.getContext("TLSv1.3"); + SSLContext ctx = SimpleSSLContext.findSSLContext("TLSv1.3"); QuicTLSContext qctx = new QuicTLSContext(ctx); QuicTLSEngine clientEngine = createClientEngine(qctx); QuicTLSEngine serverEngine = createServerEngine(qctx); @@ -63,7 +63,7 @@ public class QuicTLSEngineMissingParametersTest { @Test void testClientRequiresTransportParameters() throws IOException, QuicTransportException { - SSLContext ctx = SimpleSSLContext.getContext("TLSv1.3"); + SSLContext ctx = SimpleSSLContext.findSSLContext("TLSv1.3"); QuicTLSContext qctx = new QuicTLSContext(ctx); QuicTLSEngine clientEngine = createClientEngine(qctx); QuicTLSEngine serverEngine = createServerEngine(qctx); diff --git a/test/jdk/java/net/httpclient/websocket/HandshakeUrlEncodingTest.java b/test/jdk/java/net/httpclient/websocket/HandshakeUrlEncodingTest.java index 6d242a596e7..25a6893ff13 100644 --- a/test/jdk/java/net/httpclient/websocket/HandshakeUrlEncodingTest.java +++ b/test/jdk/java/net/httpclient/websocket/HandshakeUrlEncodingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -67,7 +67,7 @@ import static java.lang.System.out; public class HandshakeUrlEncodingTest { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpServer httpTestServer; HttpsServer httpsTestServer; String httpURI; @@ -135,11 +135,6 @@ public class HandshakeUrlEncodingTest { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - - InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); queryPart = "?&raw=abc+def/ghi=xyz&encoded=abc%2Bdef%2Fghi%3Dxyz"; httpTestServer = HttpServer.create(sa, 10); diff --git a/test/jdk/java/net/httpclient/websocket/WSHandshakeExceptionTest.java b/test/jdk/java/net/httpclient/websocket/WSHandshakeExceptionTest.java index 6a02b774929..90db79dc8ef 100644 --- a/test/jdk/java/net/httpclient/websocket/WSHandshakeExceptionTest.java +++ b/test/jdk/java/net/httpclient/websocket/WSHandshakeExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -70,7 +70,7 @@ import static java.lang.System.out; public class WSHandshakeExceptionTest { - SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); HttpServer httpTestServer; // HTTP/1.1 [ 2 servers ] HttpsServer httpsTestServer; // HTTPS/1.1 String httpURI; @@ -161,10 +161,6 @@ public class WSHandshakeExceptionTest { @BeforeTest public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - // HTTP/1.1 InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); httpTestServer = HttpServer.create(sa, 0); diff --git a/test/jdk/java/net/httpclient/websocket/WebSocketProxyTest.java b/test/jdk/java/net/httpclient/websocket/WebSocketProxyTest.java index 405edd270a4..46758b2fe6e 100644 --- a/test/jdk/java/net/httpclient/websocket/WebSocketProxyTest.java +++ b/test/jdk/java/net/httpclient/websocket/WebSocketProxyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -79,11 +79,7 @@ public class WebSocketProxyTest { private static final String PASSWORD = "xyz987"; static { - try { - SSLContext.setDefault(new SimpleSSLContext().get()); - } catch (IOException ex) { - throw new ExceptionInInitializerError(ex); - } + SSLContext.setDefault(SimpleSSLContext.findSSLContext()); } static class WSAuthenticator extends Authenticator { diff --git a/test/jdk/java/net/httpclient/whitebox/AltSvcFrameTest.java b/test/jdk/java/net/httpclient/whitebox/AltSvcFrameTest.java index 949c950fd76..589e5409044 100644 --- a/test/jdk/java/net/httpclient/whitebox/AltSvcFrameTest.java +++ b/test/jdk/java/net/httpclient/whitebox/AltSvcFrameTest.java @@ -107,11 +107,10 @@ public class AltSvcFrameTest { static Http2TestServer https2Server; static String https2URI; static HttpClient client; - static SSLContext server; + private static final SSLContext server = SimpleSSLContext.findSSLContext(); @BeforeTest public void setUp() throws Exception { - server = SimpleSSLContext.getContext("TLS"); getRegistry(); https2Server = new Http2TestServer("localhost", true, server); https2Server.addHandler(new AltSvcFrameTestHandler(), "/"); diff --git a/test/jdk/java/net/httpclient/whitebox/AltSvcRegistryTest.java b/test/jdk/java/net/httpclient/whitebox/AltSvcRegistryTest.java index 47e69338715..b853f715415 100644 --- a/test/jdk/java/net/httpclient/whitebox/AltSvcRegistryTest.java +++ b/test/jdk/java/net/httpclient/whitebox/AltSvcRegistryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -87,11 +87,10 @@ public class AltSvcRegistryTest implements HttpServerAdapters { static HttpTestServer https2Server; static String https2URI; static HttpClient client; - static SSLContext server; + private static final SSLContext server = SimpleSSLContext.findSSLContext(); @BeforeTest public void setUp() throws Exception { - server = SimpleSSLContext.getContext("TLS"); getRegistry(); final ExecutorService executor = Executors.newCachedThreadPool(); https2Server = HttpServerAdapters.HttpTestServer.of( diff --git a/test/jdk/java/net/httpclient/whitebox/FlowTestDriver.java b/test/jdk/java/net/httpclient/whitebox/FlowTestDriver.java index a0130de5a67..c24a733db3b 100644 --- a/test/jdk/java/net/httpclient/whitebox/FlowTestDriver.java +++ b/test/jdk/java/net/httpclient/whitebox/FlowTestDriver.java @@ -23,6 +23,7 @@ /* * @test + * @compile/module=java.net.http ../../../../../../lib/jdk/test/lib/net/SimpleSSLContext.java * @modules java.net.http/jdk.internal.net.http * @run testng/timeout=480 java.net.http/jdk.internal.net.http.FlowTest */ diff --git a/test/jdk/java/net/httpclient/whitebox/SSLEchoTubeTestDriver.java b/test/jdk/java/net/httpclient/whitebox/SSLEchoTubeTestDriver.java index 2ae82454cff..d641513b298 100644 --- a/test/jdk/java/net/httpclient/whitebox/SSLEchoTubeTestDriver.java +++ b/test/jdk/java/net/httpclient/whitebox/SSLEchoTubeTestDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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,6 +23,7 @@ /* * @test + * @compile/module=java.net.http ../../../../../../lib/jdk/test/lib/net/SimpleSSLContext.java * @modules java.net.http/jdk.internal.net.http * @run testng/othervm * -Djdk.internal.httpclient.debug=true diff --git a/test/jdk/java/net/httpclient/whitebox/SSLFlowDelegateTestDriver.java b/test/jdk/java/net/httpclient/whitebox/SSLFlowDelegateTestDriver.java index 083a291751f..a49f53a844a 100644 --- a/test/jdk/java/net/httpclient/whitebox/SSLFlowDelegateTestDriver.java +++ b/test/jdk/java/net/httpclient/whitebox/SSLFlowDelegateTestDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 8308144 * @summary tests that the SSLFlowDelegate doesn't accumulate application data when the * downReader doesn't request any + * @compile/module=java.net.http ../../../../../../lib/jdk/test/lib/net/SimpleSSLContext.java * @modules java.net.http/jdk.internal.net.http * @run testng/othervm -Djdk.internal.httpclient.debug=true * -Djavax.net.debug=ssl:handshake diff --git a/test/jdk/java/net/httpclient/whitebox/SSLTubeTestDriver.java b/test/jdk/java/net/httpclient/whitebox/SSLTubeTestDriver.java index e4809b60355..b1994777b14 100644 --- a/test/jdk/java/net/httpclient/whitebox/SSLTubeTestDriver.java +++ b/test/jdk/java/net/httpclient/whitebox/SSLTubeTestDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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,6 +23,7 @@ /* * @test + * @compile/module=java.net.http ../../../../../../lib/jdk/test/lib/net/SimpleSSLContext.java * @modules java.net.http/jdk.internal.net.http * @run testng/othervm * -Djdk.internal.httpclient.debug=true diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/AbstractSSLTubeTest.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/AbstractSSLTubeTest.java index f1e54b47730..944f8ae0872 100644 --- a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/AbstractSSLTubeTest.java +++ b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/AbstractSSLTubeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -286,8 +286,8 @@ public class AbstractSSLTubeTest extends AbstractRandomTest { } } - protected static SSLEngine createSSLEngine(boolean client) throws IOException { - SSLContext context = (new SimpleSSLContext()).get(); + protected static SSLEngine createSSLEngine(boolean client) { + SSLContext context = SimpleSSLContextWhiteboxAdapter.findSSLContext(); SSLEngine engine = context.createSSLEngine(); SSLParameters params = context.getSupportedSSLParameters(); if (client) { diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/FlowTest.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/FlowTest.java index 7fa717639db..3e9e967c061 100644 --- a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/FlowTest.java +++ b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/FlowTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -76,7 +76,7 @@ public class FlowTest extends AbstractRandomTest { executor = Executors.newCachedThreadPool(); srcPublisher = new SubmissionPublisher<>(executor, 20, this::handlePublisherException); - SSLContext ctx = (new SimpleSSLContext()).get(); + SSLContext ctx = SimpleSSLContextWhiteboxAdapter.findSSLContext(); SSLEngine engineClient = ctx.createSSLEngine(); SSLParameters params = ctx.getSupportedSSLParameters(); params.setApplicationProtocols(new String[]{"proto1", "proto2"}); // server will choose proto2 diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SSLFlowDelegateTest.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SSLFlowDelegateTest.java index 45af27a96a8..6b031bdfa58 100644 --- a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SSLFlowDelegateTest.java +++ b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SSLFlowDelegateTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -71,7 +71,6 @@ public class SSLFlowDelegateTest { private static final byte DATA_BYTE = (byte) random.nextInt(); private ExecutorService executor; - private SSLContext sslContext; private SSLParameters sslParams; private SSLServerSocket sslServerSocket; private SSLEngine clientEngine; @@ -80,18 +79,18 @@ public class SSLFlowDelegateTest { @BeforeTest public void beforeTest() throws Exception { this.executor = Executors.newCachedThreadPool(); - this.sslContext = new jdk.internal.net.http.SimpleSSLContext().get(); this.testCompletion = new CompletableFuture<>(); final SSLParameters sp = new SSLParameters(); sp.setApplicationProtocols(new String[]{ALPN}); this.sslParams = sp; - this.sslServerSocket = startServer(this.sslContext); + var sslContext = SimpleSSLContextWhiteboxAdapter.findSSLContext(); + this.sslServerSocket = startServer(sslContext); println(debugTag, "Server started at " + this.sslServerSocket.getInetAddress() + ":" + this.sslServerSocket.getLocalPort()); - this.clientEngine = createClientEngine(this.sslContext); + this.clientEngine = createClientEngine(sslContext); } @AfterTest diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SSLTubeTest.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SSLTubeTest.java index 114110344a4..ac6a235b8e2 100644 --- a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SSLTubeTest.java +++ b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SSLTubeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -61,7 +61,7 @@ public class SSLTubeTest extends AbstractSSLTubeTest { /* Start of wiring */ /* Emulates an echo server */ SSLLoopbackSubscriber server = - new SSLLoopbackSubscriber((new SimpleSSLContext()).get(), + new SSLLoopbackSubscriber(SimpleSSLContextWhiteboxAdapter.findSSLContext(), sslExecutor, allBytesReceived); server.start(); diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContext.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContext.java deleted file mode 100644 index 00b261292fa..00000000000 --- a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContext.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2018, 2024, 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. - */ - -package jdk.internal.net.http; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.util.StringTokenizer; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; - -/** - * Creates a simple usable SSLContext for SSLSocketFactory - * or a HttpsServer using a default keystore in the test tree. - */ -public class SimpleSSLContext { - - private final SSLContext ssl; - - /** - * Loads default keystore from SimpleSSLContext source directory - */ - public SimpleSSLContext() throws IOException { - String paths = System.getProperty("test.src.path"); - StringTokenizer st = new StringTokenizer(paths, File.pathSeparator); - SSLContext sslContext = null; - while (st.hasMoreTokens()) { - String path = st.nextToken(); - File f = new File(path, "../../../../../lib/jdk/test/lib/net/testkeys"); - if (f.exists()) { - try (FileInputStream fis = new FileInputStream(f)) { - sslContext = init(fis); - break; - } - } - } - ssl = sslContext; - } - - private SSLContext init(InputStream i) throws IOException { - try { - char[] passphrase = "passphrase".toCharArray(); - KeyStore ks = KeyStore.getInstance("PKCS12"); - ks.load(i, passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); - tmf.init(ks); - - SSLContext ssl = SSLContext.getInstance("TLS"); - ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - return ssl; - } catch (KeyManagementException | KeyStoreException | - UnrecoverableKeyException | CertificateException | - NoSuchAlgorithmException e) { - throw new RuntimeException(e.getMessage()); - } - } - - public SSLContext get() { - return ssl; - } -} diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContextWhiteboxAdapter.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContextWhiteboxAdapter.java new file mode 100644 index 00000000000..8b22de543d3 --- /dev/null +++ b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContextWhiteboxAdapter.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2018, 2025, 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. + */ + +package jdk.internal.net.http; + +import jdk.test.lib.net.SimpleSSLContext; + +import javax.net.ssl.SSLContext; + +/** + * Adapter for {@link SimpleSSLContext} for whitebox tests. + */ +public final class SimpleSSLContextWhiteboxAdapter { + + private SimpleSSLContextWhiteboxAdapter() {} + + /** + * {@return a new {@link SSLContext} instance by searching for a key store + * file path, and loading the first found one} + * + * @throws RuntimeException if no key store file can be found or the found + * one cannot be loaded + */ + public static SSLContext findSSLContext() { + return SimpleSSLContext.findSSLContext("../../../../../lib/jdk/test/lib/net/testkeys", "TLS"); + } + +} diff --git a/test/jdk/java/security/Security/ConfigFileTest.java b/test/jdk/java/security/Security/SecurityPropFile/ExtraFileAndIncludes.java similarity index 88% rename from test/jdk/java/security/Security/ConfigFileTest.java rename to test/jdk/java/security/Security/SecurityPropFile/ExtraFileAndIncludes.java index caf657005e1..4cf723f856a 100644 --- a/test/jdk/java/security/Security/ConfigFileTest.java +++ b/test/jdk/java/security/Security/SecurityPropFile/ExtraFileAndIncludes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, 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 @@ -62,13 +62,13 @@ import java.util.stream.Stream; * @test * @summary Tests security properties passed through java.security, * java.security.properties or included from other properties files. - * @bug 8155246 8292297 8292177 8281658 8319332 + * @bug 4303068 8155246 8292297 8292177 8281658 8319332 * @modules java.base/sun.net.www * @library /test/lib - * @run main ConfigFileTest + * @run main ExtraFileAndIncludes */ -public class ConfigFileTest { +public class ExtraFileAndIncludes { static final String SEPARATOR_THIN = "----------------------------"; private static void printTestHeader(String testName) { @@ -91,7 +91,8 @@ public class ConfigFileTest { } else { // Executed by the test JVM. try (FilesManager filesMgr = new FilesManager()) { - for (Method m : ConfigFileTest.class.getDeclaredMethods()) { + for (Method m : + ExtraFileAndIncludes.class.getDeclaredMethods()) { if (m.getName().startsWith("test")) { printTestHeader(m.getName()); Executor.run(m, filesMgr); @@ -120,7 +121,7 @@ public class ConfigFileTest { static void testIncludeBasic(Executor ex, FilesManager filesMgr) throws Exception { PropsFile masterFile = filesMgr.newMasterFile(); - ExtraPropsFile extraFile = filesMgr.newExtraFile(); + ExtraPropsFile extraFile = filesMgr.newExtraFile(ExtraMode.FILE_URI); PropsFile file0 = filesMgr.newFile("file0.properties"); PropsFile file1 = filesMgr.newFile("dir1/file1.properties"); PropsFile file2 = filesMgr.newFile("dir1/dir2/file2.properties"); @@ -130,7 +131,7 @@ public class ConfigFileTest { file2.addAbsoluteInclude(file1); ex.setMasterFile(masterFile); - ex.setExtraFile(extraFile, Executor.ExtraMode.FILE_URI, false); + ex.setExtraFile(extraFile, false); ex.assertSuccess(); } @@ -152,7 +153,7 @@ public class ConfigFileTest { static void testIncludeWithOverrideAll(Executor ex, FilesManager filesMgr) throws Exception { PropsFile masterFile = filesMgr.newMasterFile(); - ExtraPropsFile extraFile = filesMgr.newExtraFile(); + ExtraPropsFile extraFile = filesMgr.newExtraFile(ExtraMode.HTTP_SERVED); PropsFile file0 = filesMgr.newFile("file0.properties"); PropsFile file1 = filesMgr.newFile("dir1/file1.properties"); @@ -160,40 +161,40 @@ public class ConfigFileTest { extraFile.addAbsoluteInclude(file1); ex.setMasterFile(masterFile); - ex.setExtraFile(extraFile, Executor.ExtraMode.HTTP_SERVED, true); + ex.setExtraFile(extraFile, true); ex.assertSuccess(); } static void extraPropertiesByHelper(Executor ex, FilesManager filesMgr, - Executor.ExtraMode mode) throws Exception { - ExtraPropsFile extraFile = filesMgr.newExtraFile(); + ExtraMode mode) throws Exception { + ExtraPropsFile extraFile = filesMgr.newExtraFile(mode); PropsFile file0 = filesMgr.newFile("file0.properties"); extraFile.addRelativeInclude(file0); ex.setMasterFile(filesMgr.newMasterFile()); - ex.setExtraFile(extraFile, mode, true); + ex.setExtraFile(extraFile, true); ex.assertSuccess(); } static void testExtraPropertiesByPathAbsolute(Executor ex, FilesManager filesMgr) throws Exception { - extraPropertiesByHelper(ex, filesMgr, Executor.ExtraMode.PATH_ABS); + extraPropertiesByHelper(ex, filesMgr, ExtraMode.PATH_ABS); } static void testExtraPropertiesByPathRelative(Executor ex, FilesManager filesMgr) throws Exception { - extraPropertiesByHelper(ex, filesMgr, Executor.ExtraMode.PATH_REL); + extraPropertiesByHelper(ex, filesMgr, ExtraMode.PATH_REL); } static void specialCharsIncludes(Executor ex, FilesManager filesMgr, - char specialChar, Executor.ExtraMode extraMode, - boolean useRelativeIncludes) throws Exception { + char specialChar, ExtraMode extraMode, boolean useRelativeIncludes) + throws Exception { String suffix = specialChar + ".properties"; ExtraPropsFile extraFile; PropsFile file0, file1; try { - extraFile = filesMgr.newExtraFile("extra" + suffix); + extraFile = filesMgr.newExtraFile("extra" + suffix, extraMode); file0 = filesMgr.newFile("file0" + suffix); file1 = filesMgr.newFile("file1" + suffix); } catch (InvalidPathException ipe) { @@ -210,20 +211,18 @@ public class ConfigFileTest { extraFile.addAbsoluteInclude(file1); ex.setMasterFile(filesMgr.newMasterFile()); - ex.setExtraFile(extraFile, extraMode, false); + ex.setExtraFile(extraFile, false); ex.assertSuccess(); } static void testUnicodeIncludes1(Executor ex, FilesManager filesMgr) throws Exception { - specialCharsIncludes(ex, filesMgr, '\u2022', - Executor.ExtraMode.PATH_ABS, true); + specialCharsIncludes(ex, filesMgr, '\u2022', ExtraMode.PATH_ABS, true); } static void testUnicodeIncludes2(Executor ex, FilesManager filesMgr) throws Exception { - specialCharsIncludes(ex, filesMgr, '\u2022', - Executor.ExtraMode.FILE_URI, true); + specialCharsIncludes(ex, filesMgr, '\u2022', ExtraMode.FILE_URI, true); } static void testUnicodeIncludes3(Executor ex, FilesManager filesMgr) @@ -232,7 +231,7 @@ public class ConfigFileTest { // file:/tmp/extra•.properties are supported for the extra file. // However, relative includes are not allowed in these cases. specialCharsIncludes(ex, filesMgr, '\u2022', - Executor.ExtraMode.RAW_FILE_URI1, false); + ExtraMode.RAW_FILE_URI1, false); } static void testUnicodeIncludes4(Executor ex, FilesManager filesMgr) @@ -241,19 +240,17 @@ public class ConfigFileTest { // file:///tmp/extra•.properties are supported for the extra file. // However, relative includes are not allowed in these cases. specialCharsIncludes(ex, filesMgr, '\u2022', - Executor.ExtraMode.RAW_FILE_URI2, false); + ExtraMode.RAW_FILE_URI2, false); } static void testSpaceIncludes1(Executor ex, FilesManager filesMgr) throws Exception { - specialCharsIncludes(ex, filesMgr, ' ', - Executor.ExtraMode.PATH_ABS, true); + specialCharsIncludes(ex, filesMgr, ' ', ExtraMode.PATH_ABS, true); } static void testSpaceIncludes2(Executor ex, FilesManager filesMgr) throws Exception { - specialCharsIncludes(ex, filesMgr, ' ', - Executor.ExtraMode.FILE_URI, true); + specialCharsIncludes(ex, filesMgr, ' ', ExtraMode.FILE_URI, true); } static void testSpaceIncludes3(Executor ex, FilesManager filesMgr) @@ -261,8 +258,7 @@ public class ConfigFileTest { // Backward compatibility check. Malformed URLs such as // file:/tmp/extra .properties are supported for the extra file. // However, relative includes are not allowed in these cases. - specialCharsIncludes(ex, filesMgr, ' ', - Executor.ExtraMode.RAW_FILE_URI1, false); + specialCharsIncludes(ex, filesMgr, ' ', ExtraMode.RAW_FILE_URI1, false); } static void testSpaceIncludes4(Executor ex, FilesManager filesMgr) @@ -270,8 +266,7 @@ public class ConfigFileTest { // Backward compatibility check. Malformed URLs such as // file:///tmp/extra .properties are supported for the extra file. // However, relative includes are not allowed in these cases. - specialCharsIncludes(ex, filesMgr, ' ', - Executor.ExtraMode.RAW_FILE_URI2, false); + specialCharsIncludes(ex, filesMgr, ' ', ExtraMode.RAW_FILE_URI2, false); } static void notOverrideOnFailureHelper(Executor ex, FilesManager filesMgr, @@ -370,13 +365,13 @@ public class ConfigFileTest { static void testCannotResolveRelativeFromHTTPServed(Executor ex, FilesManager filesMgr) throws Exception { - ExtraPropsFile extraFile = filesMgr.newExtraFile(); + ExtraPropsFile extraFile = filesMgr.newExtraFile(ExtraMode.HTTP_SERVED); PropsFile file0 = filesMgr.newFile("file0.properties"); extraFile.addRelativeInclude(file0); ex.setMasterFile(filesMgr.newMasterFile()); - ex.setExtraFile(extraFile, Executor.ExtraMode.HTTP_SERVED, true); + ex.setExtraFile(extraFile, true); ex.assertError("InternalError: Cannot resolve '" + file0.fileName + "' relative path when included from a non-regular " + "properties file (e.g. HTTP served file)"); @@ -394,14 +389,15 @@ public class ConfigFileTest { masterFile.addRelativeInclude(file0); ex.setMasterFile(masterFile); - ex.assertError( - "InternalError: Cyclic include of '" + masterFile.path + "'"); + ex.assertError("Cyclic include"); + ex.getOutputAnalyzer().stderrShouldMatch("\\QInternalError: Cyclic " + + "include of '\\E[^']+\\Q" + masterFile.fileName + "'\\E"); } static void testCannotIncludeURL(Executor ex, FilesManager filesMgr) throws Exception { PropsFile masterFile = filesMgr.newMasterFile(); - ExtraPropsFile extraFile = filesMgr.newExtraFile(); + ExtraPropsFile extraFile = filesMgr.newExtraFile(ExtraMode.HTTP_SERVED); masterFile.addRawProperty("include", extraFile.url.toString()); @@ -432,8 +428,7 @@ public class ConfigFileTest { // Launch a JDK without a master java.security file present, but with an // extra file passed. Since the "security.overridePropertiesFile=true" // security property is missing, it should fail anyway. - ex.setExtraFile( - filesMgr.newExtraFile(), Executor.ExtraMode.FILE_URI, true); + ex.setExtraFile(filesMgr.newExtraFile(ExtraMode.FILE_URI), true); ex.assertError("InternalError: Error loading java.security file"); } } @@ -455,17 +450,24 @@ sealed class PropsFile permits ExtraPropsFile { static Include of(PropsFile propsFile, String value) { return new Include(propsFile, value); } + + void assertProcessed(OutputAnalyzer oa) { + oa.shouldContain("processing include: '" + value + "'"); + oa.shouldContain("finished processing " + propsFile.displayPath); + } } protected final List includes = new ArrayList<>(); protected final PrintWriter writer; protected boolean includedFromExtra = false; + protected Path displayPath; final String fileName; final Path path; PropsFile(String fileName, Path path) throws IOException { this.fileName = fileName; this.path = path; + this.displayPath = path; this.writer = new PrintWriter(Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND), true); } @@ -513,8 +515,9 @@ sealed class PropsFile permits ExtraPropsFile { } void addRelativeInclude(PropsFile propsFile) { - addIncludeDefinition(Include.of(propsFile, - path.getParent().relativize(propsFile.path).toString())); + Path rel = path.getParent().relativize(propsFile.path); + addIncludeDefinition(Include.of(propsFile, rel.toString())); + propsFile.displayPath = displayPath.getParent().resolve(rel); } void assertApplied(OutputAnalyzer oa) { @@ -522,8 +525,7 @@ sealed class PropsFile permits ExtraPropsFile { FilesManager.APPLIED_PROP_VALUE); for (Include include : includes) { include.propsFile.assertApplied(oa); - oa.shouldContain("processing include: '" + include.value + "'"); - oa.shouldContain("finished processing " + include.propsFile.path); + include.assertProcessed(oa); } } @@ -534,8 +536,7 @@ sealed class PropsFile permits ExtraPropsFile { if (!include.propsFile.includedFromExtra) { include.propsFile.assertWasOverwritten(oa); } - oa.shouldContain("processing include: '" + include.value + "'"); - oa.shouldContain("finished processing " + include.propsFile.path); + include.assertProcessed(oa); } } @@ -556,13 +557,24 @@ sealed class PropsFile permits ExtraPropsFile { } } +enum ExtraMode { + HTTP_SERVED, FILE_URI, RAW_FILE_URI1, RAW_FILE_URI2, PATH_ABS, PATH_REL +} + final class ExtraPropsFile extends PropsFile { + private static final Path CWD = Path.of(".").toAbsolutePath(); private final Map systemProps = new LinkedHashMap<>(); + private final ExtraMode mode; final URI url; - ExtraPropsFile(String fileName, URI url, Path path) throws IOException { + ExtraPropsFile(String fileName, URI url, Path path, ExtraMode mode) + throws IOException { super(fileName, path); this.url = url; + this.mode = mode; + if (mode == ExtraMode.PATH_REL) { + this.displayPath = CWD.relativize(path); + } } @Override @@ -578,14 +590,25 @@ final class ExtraPropsFile extends PropsFile { super.addIncludeDefinition(include); } + String getSysPropValue() { + return switch (mode) { + case HTTP_SERVED -> url.toString(); + case FILE_URI -> path.toUri().toString(); + case RAW_FILE_URI1 -> "file:" + path; + case RAW_FILE_URI2 -> + "file://" + (path.startsWith("/") ? "" : "/") + path; + case PATH_ABS, PATH_REL -> displayPath.toString(); + }; + } + Map getSystemProperties() { return Collections.unmodifiableMap(systemProps); } } final class FilesManager implements Closeable { - private static final Path ROOT_DIR = - Path.of(ConfigFileTest.class.getSimpleName()).toAbsolutePath(); + private static final Path ROOT_DIR = Path.of( + ExtraFileAndIncludes.class.getSimpleName()).toAbsolutePath(); private static final Path PROPS_DIR = ROOT_DIR.resolve("properties"); private static final Path JDK_DIR = ROOT_DIR.resolve("jdk"); private static final Path MASTER_FILE = @@ -684,11 +707,11 @@ final class FilesManager implements Closeable { propsFile.addComment("Property to determine if this properties file " + "was parsed and not overwritten:"); propsFile.addRawProperty(fileName, APPLIED_PROP_VALUE); - propsFile.addComment(ConfigFileTest.SEPARATOR_THIN); + propsFile.addComment(ExtraFileAndIncludes.SEPARATOR_THIN); propsFile.addComment("Property to be overwritten by every properties " + "file (master, extra or included):"); propsFile.addRawProperty(LAST_FILE_PROP_NAME, fileName); - propsFile.addComment(ConfigFileTest.SEPARATOR_THIN); + propsFile.addComment(ExtraFileAndIncludes.SEPARATOR_THIN); createdFiles.add(propsFile); return propsFile; } @@ -702,16 +725,17 @@ final class FilesManager implements Closeable { return newFile(MASTER_FILE, PropsFile::new); } - ExtraPropsFile newExtraFile() throws IOException { - return newExtraFile("extra.properties"); + ExtraPropsFile newExtraFile(ExtraMode mode) throws IOException { + return newExtraFile("extra.properties", mode); } - ExtraPropsFile newExtraFile(String extraFileName) throws IOException { + ExtraPropsFile newExtraFile(String extraFileName, ExtraMode mode) + throws IOException { return (ExtraPropsFile) newFile(PROPS_DIR.resolve(extraFileName), (fileName, path) -> { URI uri = serverUri.resolve(ParseUtil.encodePath( ROOT_DIR.relativize(path).toString())); - return new ExtraPropsFile(fileName, uri, path); + return new ExtraPropsFile(fileName, uri, path, mode); }); } @@ -719,7 +743,7 @@ final class FilesManager implements Closeable { for (PropsFile propsFile : createdFiles) { System.err.println(); System.err.println(propsFile.path.toString()); - System.err.println(ConfigFileTest.SEPARATOR_THIN.repeat(3)); + System.err.println(ExtraFileAndIncludes.SEPARATOR_THIN.repeat(3)); try (Stream lines = Files.lines(propsFile.path)) { long lineNumber = 1L; Iterator it = lines.iterator(); @@ -757,9 +781,6 @@ final class FilesManager implements Closeable { } final class Executor { - enum ExtraMode { - HTTP_SERVED, FILE_URI, RAW_FILE_URI1, RAW_FILE_URI2, PATH_ABS, PATH_REL - } static final String RUNNER_ARG = "runner"; static final String INITIAL_PROP_LOG_MSG = "Initial security property: "; private static final String OVERRIDING_LOG_MSG = @@ -769,7 +790,6 @@ final class Executor { INITIAL_PROP_LOG_MSG + "postInitTest=shouldNotRecord", INITIAL_PROP_LOG_MSG + "include=", }; - private static final Path CWD = Path.of(".").toAbsolutePath(); private static final String JAVA_SEC_PROPS = "java.security.properties"; private static final String CLASS_PATH = Objects.requireNonNull( System.getProperty("test.classes"), "unspecified test.classes"); @@ -812,20 +832,10 @@ final class Executor { this.masterPropsFile = masterPropsFile; } - void setExtraFile(ExtraPropsFile extraPropsFile, ExtraMode mode, - boolean overrideAll) { + void setExtraFile(ExtraPropsFile extraPropsFile, boolean overrideAll) { this.extraPropsFile = extraPropsFile; expectedOverrideAll = overrideAll; - setRawExtraFile(switch (mode) { - case HTTP_SERVED -> extraPropsFile.url.toString(); - case FILE_URI -> extraPropsFile.path.toUri().toString(); - case RAW_FILE_URI1 -> "file:" + extraPropsFile.path; - case RAW_FILE_URI2 -> "file://" + - (extraPropsFile.path.startsWith("/") ? "" : "/") + - extraPropsFile.path; - case PATH_ABS -> extraPropsFile.path.toString(); - case PATH_REL -> CWD.relativize(extraPropsFile.path).toString(); - }, overrideAll); + setRawExtraFile(extraPropsFile.getSysPropValue(), overrideAll); } void setIgnoredExtraFile(String extraPropsFile, boolean overrideAll) { @@ -841,7 +851,7 @@ final class Executor { List command = new ArrayList<>(jvmArgs); Collections.addAll(command, Utils.getTestJavaOpts()); addSystemPropertiesAsJvmArgs(command); - command.add(ConfigFileTest.class.getSimpleName()); + command.add(ExtraFileAndIncludes.class.getSimpleName()); command.add(RUNNER_ARG); oa = ProcessTools.executeProcess(new ProcessBuilder(command)); oa.shouldHaveExitValue(successExpected ? 0 : 1); diff --git a/test/jdk/java/security/Security/SecurityPropFile/LinuxAnonymousFiles.java b/test/jdk/java/security/Security/SecurityPropFile/LinuxAnonymousFiles.java new file mode 100644 index 00000000000..7ca2a7c0f8b --- /dev/null +++ b/test/jdk/java/security/Security/SecurityPropFile/LinuxAnonymousFiles.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2026, Red Hat, Inc. + * + * 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 jdk.test.lib.process.ProcessTools; + +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; + +/* + * @test + * @summary Ensures the java executable is able to load extra security + * properties files from anonymous files and pipes. + * @bug 8352728 + * @requires os.family == "linux" + * @modules java.base/java.io:+open + * @library /test/lib + * @run main LinuxAnonymousFiles + */ + +public class LinuxAnonymousFiles { + private static final String TEST_PROP = "property.name=PROPERTY_VALUE"; + + private static final class AnonymousFile implements AutoCloseable { + public final Path fdPath; + private final FileInputStream fis; + + private AnonymousFile(CharSequence content) throws Exception { + Path tmp = Files.createTempFile("anonymous-file-", ""); + Files.writeString(tmp, content + System.lineSeparator()); + fis = new FileInputStream(tmp.toFile()); + Files.delete(tmp); + // Now the file is regular but anonymous, and will be unlinked + // when we close the last file descriptor referring to it. The + // fis instance ensures we keep it alive until close() is invoked. + Field field = FileDescriptor.class.getDeclaredField("fd"); + field.setAccessible(true); + int fd = field.getInt(fis.getFD()); + fdPath = Path.of("/proc/self").toRealPath().resolve("fd/" + fd); + } + + @Override + public void close() throws IOException { + fis.close(); + } + } + + public static void main(String[] args) throws Exception { + Path java = Path.of(System.getProperty("test.jdk"), "bin", "java"); + try (AnonymousFile af = new AnonymousFile("include /dev/stdin")) { + ProcessTools.executeProcess(new ProcessBuilder(java.toString(), + "-Djava.security.debug=properties", + "-Djava.security.properties=" + af.fdPath, + "-XshowSettings:security:properties", "-version"), + TEST_PROP).shouldHaveExitValue(0).shouldContain(TEST_PROP); + } + System.out.println("TEST PASS - OK"); + } +} diff --git a/test/jdk/java/security/Security/SecurityPropFile/SecurityPropFile.file b/test/jdk/java/security/Security/SecurityPropFile/SecurityPropFile.file deleted file mode 100644 index 2b4c08c6903..00000000000 --- a/test/jdk/java/security/Security/SecurityPropFile/SecurityPropFile.file +++ /dev/null @@ -1 +0,0 @@ -policy.url.2=file:${test.src}/SecurityPropFile.policy diff --git a/test/jdk/java/security/Security/SecurityPropFile/WindowsParentDirPermissions.java b/test/jdk/java/security/Security/SecurityPropFile/WindowsParentDirPermissions.java new file mode 100644 index 00000000000..a41fd2f3535 --- /dev/null +++ b/test/jdk/java/security/Security/SecurityPropFile/WindowsParentDirPermissions.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2026, Red Hat, Inc. + * + * 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 jdk.test.lib.process.ProcessTools; +import jdk.test.lib.util.FileUtils; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.AclEntry; +import java.nio.file.attribute.AclEntryType; +import java.nio.file.attribute.AclFileAttributeView; +import java.util.List; + +/* + * @test + * @summary Ensures java.security is loadable in Windows, even when the user + * does not have permissions on one of the parent directories. + * @bug 8352728 + * @requires os.family == "windows" + * @library /test/lib + * @run main WindowsParentDirPermissions + */ + +public class WindowsParentDirPermissions { + private static AutoCloseable restrictedAcl(Path path) throws IOException { + AclFileAttributeView view = + Files.getFileAttributeView(path, AclFileAttributeView.class); + List originalAcl = List.copyOf(view.getAcl()); + view.setAcl(List.of(AclEntry.newBuilder().setType(AclEntryType.DENY) + .setPrincipal(Files.getOwner(path)).build())); + return () -> view.setAcl(originalAcl); + } + + public static void main(String[] args) throws Exception { + Path temp = Files.createTempDirectory("JDK-8352728-tmp-"); + try (AutoCloseable a1 = () -> FileUtils.deleteFileTreeUnchecked(temp)) { + // Copy the jdk to a different directory + Path originalJdk = Path.of(System.getProperty("test.jdk")); + Path jdk = temp.resolve("jdk-parent-dir", "jdk"); + Files.createDirectories(jdk); + FileUtils.copyDirectory(originalJdk, jdk); + + // Remove current user permissions from jdk-parent-dir + try (AutoCloseable a2 = restrictedAcl(jdk.getParent())) { + // Make sure the permissions are affecting the current user + try { + jdk.toRealPath(); + throw new jtreg.SkippedException("Must run non-elevated!"); + } catch (IOException expected) { } + + // Execute the copied jdk, ensuring java.security.Security is + // loaded (i.e. use -XshowSettings:security:properties) + ProcessTools.executeProcess(new ProcessBuilder( + List.of(jdk.resolve("bin", "java.exe").toString(), + "-Djava.security.debug=properties", + "-XshowSettings:security:properties", + "-version"))).shouldHaveExitValue(0); + } + } + System.out.println("TEST PASS - OK"); + } +} diff --git a/test/jdk/java/time/nontestng/java/time/chrono/HijrahConfigCheck.java b/test/jdk/java/time/nonjunit/java/time/chrono/HijrahConfigCheck.java similarity index 100% rename from test/jdk/java/time/nontestng/java/time/chrono/HijrahConfigCheck.java rename to test/jdk/java/time/nonjunit/java/time/chrono/HijrahConfigCheck.java diff --git a/test/jdk/java/time/nontestng/java/time/chrono/HijrahConfigTest.java b/test/jdk/java/time/nonjunit/java/time/chrono/HijrahConfigTest.java similarity index 100% rename from test/jdk/java/time/nontestng/java/time/chrono/HijrahConfigTest.java rename to test/jdk/java/time/nonjunit/java/time/chrono/HijrahConfigTest.java diff --git a/test/jdk/java/time/nontestng/java/time/chrono/hijrah-config-Hijrah-test_islamic-test.properties b/test/jdk/java/time/nonjunit/java/time/chrono/hijrah-config-Hijrah-test_islamic-test.properties similarity index 100% rename from test/jdk/java/time/nontestng/java/time/chrono/hijrah-config-Hijrah-test_islamic-test.properties rename to test/jdk/java/time/nonjunit/java/time/chrono/hijrah-config-Hijrah-test_islamic-test.properties diff --git a/test/jdk/java/time/nontestng/java/time/zone/CustomZoneNameTest.java b/test/jdk/java/time/nonjunit/java/time/zone/CustomZoneNameTest.java similarity index 100% rename from test/jdk/java/time/nontestng/java/time/zone/CustomZoneNameTest.java rename to test/jdk/java/time/nonjunit/java/time/zone/CustomZoneNameTest.java diff --git a/test/jdk/java/time/nontestng/java/time/zone/zoneProvider/META-INF/services/java.time.zone.ZoneRulesProvider b/test/jdk/java/time/nonjunit/java/time/zone/zoneProvider/META-INF/services/java.time.zone.ZoneRulesProvider similarity index 100% rename from test/jdk/java/time/nontestng/java/time/zone/zoneProvider/META-INF/services/java.time.zone.ZoneRulesProvider rename to test/jdk/java/time/nonjunit/java/time/zone/zoneProvider/META-INF/services/java.time.zone.ZoneRulesProvider diff --git a/test/jdk/java/time/nontestng/java/time/zone/zoneProvider/META-INF/services/java.util.spi.TimeZoneNameProvider b/test/jdk/java/time/nonjunit/java/time/zone/zoneProvider/META-INF/services/java.util.spi.TimeZoneNameProvider similarity index 100% rename from test/jdk/java/time/nontestng/java/time/zone/zoneProvider/META-INF/services/java.util.spi.TimeZoneNameProvider rename to test/jdk/java/time/nonjunit/java/time/zone/zoneProvider/META-INF/services/java.util.spi.TimeZoneNameProvider diff --git a/test/jdk/java/time/nontestng/java/time/zone/zoneProvider/custom/CustomTimeZoneNameProvider.java b/test/jdk/java/time/nonjunit/java/time/zone/zoneProvider/custom/CustomTimeZoneNameProvider.java similarity index 100% rename from test/jdk/java/time/nontestng/java/time/zone/zoneProvider/custom/CustomTimeZoneNameProvider.java rename to test/jdk/java/time/nonjunit/java/time/zone/zoneProvider/custom/CustomTimeZoneNameProvider.java diff --git a/test/jdk/java/time/nontestng/java/time/zone/zoneProvider/custom/CustomZoneRulesProvider.java b/test/jdk/java/time/nonjunit/java/time/zone/zoneProvider/custom/CustomZoneRulesProvider.java similarity index 100% rename from test/jdk/java/time/nontestng/java/time/zone/zoneProvider/custom/CustomZoneRulesProvider.java rename to test/jdk/java/time/nonjunit/java/time/zone/zoneProvider/custom/CustomZoneRulesProvider.java diff --git a/test/jdk/java/time/tck/TEST.properties b/test/jdk/java/time/tck/TEST.properties index 056694122b0..70c91dbfcb5 100644 --- a/test/jdk/java/time/tck/TEST.properties +++ b/test/jdk/java/time/tck/TEST.properties @@ -1,5 +1,5 @@ -# java.time tests use TestNG -TestNG.dirs = .. +# java.time tests use JUnit +JUnit.dirs = .. othervm.dirs = java/time/chrono lib.dirs = /test/lib /test/jdk/tools/lib lib.build = jdk.test.lib.RandomFactory diff --git a/test/jdk/java/time/tck/java/time/AbstractDateTimeTest.java b/test/jdk/java/time/tck/java/time/AbstractDateTimeTest.java index e7c6db6ef9d..cf138419c83 100644 --- a/test/jdk/java/time/tck/java/time/AbstractDateTimeTest.java +++ b/test/jdk/java/time/tck/java/time/AbstractDateTimeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -59,8 +59,11 @@ */ package tck.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.DateTimeException; import java.time.temporal.TemporalAccessor; @@ -68,7 +71,9 @@ import java.time.temporal.TemporalField; import java.time.temporal.TemporalQuery; import java.util.List; -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.temporal.MockFieldNoValue; /** @@ -97,179 +102,137 @@ public abstract class AbstractDateTimeTest extends AbstractTCKTest { //----------------------------------------------------------------------- // isSupported(TemporalField) //----------------------------------------------------------------------- - @Test() - public void basicTest_isSupported_TemporalField_supported() { - for (TemporalAccessor sample : samples()) { - for (TemporalField field : validFields()) { - assertEquals(sample.isSupported(field), true, "Failed on " + sample + " " + field); - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_isSupported_TemporalField_supported(TemporalAccessor sample) { + for (TemporalField field : validFields()) { + assertTrue(sample.isSupported(field), "Failed on " + sample + " " + field); } } - @Test() - public void basicTest_isSupported_TemporalField_unsupported() { - for (TemporalAccessor sample : samples()) { - for (TemporalField field : invalidFields()) { - assertEquals(sample.isSupported(field), false, "Failed on " + sample + " " + field); - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_isSupported_TemporalField_unsupported(TemporalAccessor sample) { + for (TemporalField field : invalidFields()) { + assertFalse(sample.isSupported(field), "Failed on " + sample + " " + field); } } - @Test() - public void basicTest_isSupported_TemporalField_null() { - for (TemporalAccessor sample : samples()) { - assertEquals(sample.isSupported(null), false, "Failed on " + sample); - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_isSupported_TemporalField_null(TemporalAccessor sample) { + assertFalse(sample.isSupported(null), "Failed on " + sample); } //----------------------------------------------------------------------- // range(TemporalField) //----------------------------------------------------------------------- - @Test() - public void basicTest_range_TemporalField_supported() { - for (TemporalAccessor sample : samples()) { - for (TemporalField field : validFields()) { - sample.range(field); // no exception - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_range_TemporalField_supported(TemporalAccessor sample) { + for (TemporalField field : validFields()) { + assertDoesNotThrow(() -> sample.range(field)); } } - @Test() - public void basicTest_range_TemporalField_unsupported() { - for (TemporalAccessor sample : samples()) { - for (TemporalField field : invalidFields()) { - try { - sample.range(field); - fail("Failed on " + sample + " " + field); - } catch (DateTimeException ex) { - // expected - } - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_range_TemporalField_unsupported(TemporalAccessor sample) { + for (TemporalField field : invalidFields()) { + assertThrows(DateTimeException.class, + () -> sample.range(field), "Failed on " + sample + " " + field); } } - @Test() - public void basicTest_range_TemporalField_null() { - for (TemporalAccessor sample : samples()) { - try { - sample.range(null); - fail("Failed on " + sample); - } catch (NullPointerException ex) { - // expected - } - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_range_TemporalField_null(TemporalAccessor sample) { + assertThrows(NullPointerException.class, + () -> sample.range(null), "Failed on " + sample); } //----------------------------------------------------------------------- // get(TemporalField) //----------------------------------------------------------------------- - @Test() - public void basicTest_get_TemporalField_supported() { - for (TemporalAccessor sample : samples()) { - for (TemporalField field : validFields()) { - if (sample.range(field).isIntValue()) { - sample.get(field); // no exception - } else { - try { - sample.get(field); - fail("Failed on " + sample + " " + field); - } catch (DateTimeException ex) { - // expected - } - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_get_TemporalField_supported(TemporalAccessor sample) { + for (TemporalField field : validFields()) { + if (sample.range(field).isIntValue()) { + assertDoesNotThrow(() -> sample.get(field)); + } else { + assertThrows(DateTimeException.class, + () -> sample.get(field), "Failed on " + sample + " " + field); } } } - @Test() - public void basicTest_get_TemporalField_unsupported() { - for (TemporalAccessor sample : samples()) { - for (TemporalField field : invalidFields()) { - try { - sample.get(field); - fail("Failed on " + sample + " " + field); - } catch (DateTimeException ex) { - // expected - } - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_get_TemporalField_unsupported(TemporalAccessor sample) { + for (TemporalField field : invalidFields()) { + assertThrows(DateTimeException.class, + () -> sample.get(field), "Failed on " + sample + " " + field); } } - @Test(expectedExceptions=DateTimeException.class) - public void test_get_TemporalField_invalidField() { - for (TemporalAccessor sample : samples()) { - sample.get(MockFieldNoValue.INSTANCE); - } + @ParameterizedTest + @MethodSource("samples") + public void test_get_TemporalField_invalidField(TemporalAccessor sample) { + assertThrows(DateTimeException.class, + () -> sample.get(MockFieldNoValue.INSTANCE)); } - @Test() - public void basicTest_get_TemporalField_null() { - for (TemporalAccessor sample : samples()) { - try { - sample.get(null); - fail("Failed on " + sample); - } catch (NullPointerException ex) { - // expected - } - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_get_TemporalField_null(TemporalAccessor sample) { + assertThrows(NullPointerException.class, + () -> sample.get(null), "Failed on " + sample); } //----------------------------------------------------------------------- // getLong(TemporalField) //----------------------------------------------------------------------- - @Test() - public void basicTest_getLong_TemporalField_supported() { - for (TemporalAccessor sample : samples()) { - for (TemporalField field : validFields()) { - sample.getLong(field); // no exception - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_getLong_TemporalField_supported(TemporalAccessor sample) { + for (TemporalField field : validFields()) { + sample.getLong(field); } } - @Test() - public void basicTest_getLong_TemporalField_unsupported() { - for (TemporalAccessor sample : samples()) { - for (TemporalField field : invalidFields()) { - try { - sample.getLong(field); - fail("Failed on " + sample + " " + field); - } catch (DateTimeException ex) { - // expected - } - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_getLong_TemporalField_unsupported(TemporalAccessor sample) { + for (TemporalField field : invalidFields()) { + assertThrows(DateTimeException.class, + () -> sample.getLong(field), "Failed on " + sample + " " + field); } } - @Test(expectedExceptions=DateTimeException.class) - public void test_getLong_TemporalField_invalidField() { - for (TemporalAccessor sample : samples()) { - sample.getLong(MockFieldNoValue.INSTANCE); - } + @ParameterizedTest + @MethodSource("samples") + public void test_getLong_TemporalField_invalidField(TemporalAccessor sample) { + assertThrows(DateTimeException.class, + () -> sample.getLong(MockFieldNoValue.INSTANCE)); } - @Test() - public void basicTest_getLong_TemporalField_null() { - for (TemporalAccessor sample : samples()) { - try { - sample.getLong(null); - fail("Failed on " + sample); - } catch (NullPointerException ex) { - // expected - } - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_getLong_TemporalField_null(TemporalAccessor sample) { + assertThrows(NullPointerException.class, + () -> sample.getLong(null), "Failed on " + sample); } //----------------------------------------------------------------------- - @Test - public void basicTest_query() { - for (TemporalAccessor sample : samples()) { - assertEquals(sample.query(new TemporalQuery() { - @Override - public String queryFrom(TemporalAccessor temporal) { - return "foo"; - } - }), "foo"); - } + @ParameterizedTest + @MethodSource("samples") + public void basicTest_query(TemporalAccessor sample) { + assertEquals("foo", sample.query(new TemporalQuery() { + @Override + public String queryFrom(TemporalAccessor temporal) { + return "foo"; + } + })); } - } diff --git a/test/jdk/java/time/tck/java/time/AbstractTCKTest.java b/test/jdk/java/time/tck/java/time/AbstractTCKTest.java index 0db507e400a..d8d53f931df 100644 --- a/test/jdk/java/time/tck/java/time/AbstractTCKTest.java +++ b/test/jdk/java/time/tck/java/time/AbstractTCKTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,9 +54,9 @@ */ package tck.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -70,6 +70,8 @@ import java.io.Serializable; import java.util.Formatter; import java.util.Map; +import org.junit.jupiter.api.Assertions; + /** * Base test class. */ @@ -107,13 +109,13 @@ public abstract class AbstractTCKTest { } protected static void assertSerializable(Object object) throws IOException, ClassNotFoundException { - assertEquals(object instanceof Serializable, true); + assertEquals(true, object instanceof Serializable); Object deserializedObject = writeThenRead(object); - assertEquals(deserializedObject, object); + assertEquals(object, deserializedObject); } protected static void assertSerializableSame(Object object) throws IOException, ClassNotFoundException { - assertEquals(object instanceof Serializable, true); + assertEquals(true, object instanceof Serializable); Object deserializedObject = writeThenRead(object); assertSame(deserializedObject, object); } @@ -139,26 +141,26 @@ public abstract class AbstractTCKTest { byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); try (DataInputStream dis = new DataInputStream(bais)) { - assertEquals(dis.readShort(), ObjectStreamConstants.STREAM_MAGIC); - assertEquals(dis.readShort(), ObjectStreamConstants.STREAM_VERSION); - assertEquals(dis.readByte(), ObjectStreamConstants.TC_OBJECT); - assertEquals(dis.readByte(), ObjectStreamConstants.TC_CLASSDESC); - assertEquals(dis.readUTF(), serClass); - assertEquals(dis.readLong(), serVer); - assertEquals(dis.readByte(), ObjectStreamConstants.SC_EXTERNALIZABLE | ObjectStreamConstants.SC_BLOCK_DATA); - assertEquals(dis.readShort(), 0); // number of fields - assertEquals(dis.readByte(), ObjectStreamConstants.TC_ENDBLOCKDATA); // end of classdesc - assertEquals(dis.readByte(), ObjectStreamConstants.TC_NULL); // no superclasses + assertEquals(ObjectStreamConstants.STREAM_MAGIC, dis.readShort()); + assertEquals(ObjectStreamConstants.STREAM_VERSION, dis.readShort()); + assertEquals(ObjectStreamConstants.TC_OBJECT, dis.readByte()); + assertEquals(ObjectStreamConstants.TC_CLASSDESC, dis.readByte()); + assertEquals(serClass, dis.readUTF()); + assertEquals(serVer, dis.readLong()); + assertEquals(ObjectStreamConstants.SC_EXTERNALIZABLE | ObjectStreamConstants.SC_BLOCK_DATA, dis.readByte()); + assertEquals(0, dis.readShort()); // number of fields + assertEquals(ObjectStreamConstants.TC_ENDBLOCKDATA, dis.readByte()); // end of classdesc + assertEquals(ObjectStreamConstants.TC_NULL, dis.readByte()); // no superclasses if (expectedBytes.length < 256) { - assertEquals(dis.readByte(), ObjectStreamConstants.TC_BLOCKDATA); - assertEquals(dis.readUnsignedByte(), expectedBytes.length, "blockdata length incorrect"); + assertEquals(ObjectStreamConstants.TC_BLOCKDATA, dis.readByte()); + assertEquals(expectedBytes.length, dis.readUnsignedByte(), "blockdata length incorrect"); } else { - assertEquals(dis.readByte(), ObjectStreamConstants.TC_BLOCKDATALONG); - assertEquals(dis.readInt(), expectedBytes.length, "blockdatalong length incorrect"); + assertEquals(ObjectStreamConstants.TC_BLOCKDATALONG, dis.readByte()); + assertEquals(expectedBytes.length, dis.readInt(), "blockdatalong length incorrect"); } byte[] input = new byte[expectedBytes.length]; dis.readFully(input); - assertEquals(input, expectedBytes); + Assertions.assertArrayEquals(expectedBytes, input); if (matches.length > 0) { for (byte[] match : matches) { boolean matched = false; @@ -167,7 +169,7 @@ public abstract class AbstractTCKTest { dis.mark(1000); byte[] possible = new byte[match.length]; dis.readFully(possible); - assertEquals(possible, match); + Assertions.assertArrayEquals(match, possible); matched = true; } catch (AssertionError ex) { dis.reset(); @@ -176,8 +178,8 @@ public abstract class AbstractTCKTest { } } } else { - assertEquals(dis.readByte(), ObjectStreamConstants.TC_ENDBLOCKDATA); // end of blockdata - assertEquals(dis.read(), -1); + assertEquals(ObjectStreamConstants.TC_ENDBLOCKDATA, dis.readByte()); // end of blockdata + assertEquals(-1, dis.read()); } } } diff --git a/test/jdk/java/time/tck/java/time/TCKClock.java b/test/jdk/java/time/tck/java/time/TCKClock.java index 843992e0d79..9e98756109b 100644 --- a/test/jdk/java/time/tck/java/time/TCKClock.java +++ b/test/jdk/java/time/tck/java/time/TCKClock.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,18 +59,17 @@ */ package tck.java.time; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test Clock. */ -@Test public class TCKClock { static class MockInstantClock extends Clock { @@ -117,18 +116,18 @@ public class TCKClock { //----------------------------------------------------------------------- @Test public void test_mockInstantClock_get() { - assertEquals(MOCK_INSTANT.instant(), INSTANT); - assertEquals(MOCK_INSTANT.millis(), INSTANT.toEpochMilli()); - assertEquals(MOCK_INSTANT.getZone(), ZONE); + assertEquals(INSTANT, MOCK_INSTANT.instant()); + assertEquals(INSTANT.toEpochMilli(), MOCK_INSTANT.millis()); + assertEquals(ZONE, MOCK_INSTANT.getZone()); } @Test public void test_mockInstantClock_withZone() { ZoneId london = ZoneId.of("Europe/London"); Clock changed = MOCK_INSTANT.withZone(london); - assertEquals(MOCK_INSTANT.instant(), INSTANT); - assertEquals(MOCK_INSTANT.millis(), INSTANT.toEpochMilli()); - assertEquals(changed.getZone(), london); + assertEquals(INSTANT, MOCK_INSTANT.instant()); + assertEquals(INSTANT.toEpochMilli(), MOCK_INSTANT.millis()); + assertEquals(london, changed.getZone()); } } diff --git a/test/jdk/java/time/tck/java/time/TCKClock_Fixed.java b/test/jdk/java/time/tck/java/time/TCKClock_Fixed.java index 3dc567d0ec1..0c95af5ea08 100644 --- a/test/jdk/java/time/tck/java/time/TCKClock_Fixed.java +++ b/test/jdk/java/time/tck/java/time/TCKClock_Fixed.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,7 +59,7 @@ */ package tck.java.time; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.time.Clock; @@ -68,12 +68,12 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Test fixed clock. */ -@Test public class TCKClock_Fixed extends AbstractTCKTest { private static final ZoneId MOSCOW = ZoneId.of("Europe/Moscow"); @@ -81,72 +81,77 @@ public class TCKClock_Fixed extends AbstractTCKTest { private static final Instant INSTANT = LocalDateTime.of(2008, 6, 30, 11, 30, 10, 500).atZone(ZoneOffset.ofHours(2)).toInstant(); //------------------------------------------------------------------------- + @Test public void test_fixed_InstantZoneId() { Clock test = Clock.fixed(INSTANT, PARIS); - assertEquals(test.instant(), INSTANT); - assertEquals(test.getZone(), PARIS); - assertEquals(test.instant().getEpochSecond()*1000, test.millis()); + assertEquals(INSTANT, test.instant()); + assertEquals(PARIS, test.getZone()); + assertEquals(test.millis(), test.instant().getEpochSecond()*1000); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_fixed_InstantZoneId_nullInstant() { - Clock.fixed(null, PARIS); + Assertions.assertThrows(NullPointerException.class, () -> Clock.fixed(null, PARIS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_fixed_InstantZoneId_nullZoneId() { - Clock.fixed(INSTANT, null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.fixed(INSTANT, null)); } //------------------------------------------------------------------------- + @Test public void test_withZone() { Clock test = Clock.fixed(INSTANT, PARIS); Clock changed = test.withZone(MOSCOW); - assertEquals(test.getZone(), PARIS); - assertEquals(changed.getZone(), MOSCOW); + assertEquals(PARIS, test.getZone()); + assertEquals(MOSCOW, changed.getZone()); } + @Test public void test_withZone_equal() { Clock test = Clock.fixed(INSTANT, PARIS); Clock changed = test.withZone(PARIS); - assertEquals(changed.getZone(), PARIS); + assertEquals(PARIS, changed.getZone()); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_withZone_null() { - Clock.fixed(INSTANT, PARIS).withZone(null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.fixed(INSTANT, PARIS).withZone(null)); } //----------------------------------------------------------------------- + @Test public void test_equals() { Clock a = Clock.fixed(INSTANT, ZoneOffset.UTC); Clock b = Clock.fixed(INSTANT, ZoneOffset.UTC); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), true); - assertEquals(b.equals(a), true); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(true, a.equals(b)); + assertEquals(true, b.equals(a)); + assertEquals(true, b.equals(b)); Clock c = Clock.fixed(INSTANT, PARIS); - assertEquals(a.equals(c), false); + assertEquals(false, a.equals(c)); Clock d = Clock.fixed(INSTANT.minusNanos(1), ZoneOffset.UTC); - assertEquals(a.equals(d), false); + assertEquals(false, a.equals(d)); - assertEquals(a.equals(null), false); - assertEquals(a.equals("other type"), false); - assertEquals(a.equals(Clock.systemUTC()), false); + assertEquals(false, a.equals(null)); + assertEquals(false, a.equals("other type")); + assertEquals(false, a.equals(Clock.systemUTC())); } + @Test public void test_hashCode() { Clock a = Clock.fixed(INSTANT, ZoneOffset.UTC); Clock b = Clock.fixed(INSTANT, ZoneOffset.UTC); assertEquals(a.hashCode(), a.hashCode()); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); Clock c = Clock.fixed(INSTANT, PARIS); - assertEquals(a.hashCode() == c.hashCode(), false); + assertEquals(false, a.hashCode() == c.hashCode()); Clock d = Clock.fixed(INSTANT.minusNanos(1), ZoneOffset.UTC); - assertEquals(a.hashCode() == d.hashCode(), false); + assertEquals(false, a.hashCode() == d.hashCode()); } } diff --git a/test/jdk/java/time/tck/java/time/TCKClock_Offset.java b/test/jdk/java/time/tck/java/time/TCKClock_Offset.java index 644c1a63880..5adb61da589 100644 --- a/test/jdk/java/time/tck/java/time/TCKClock_Offset.java +++ b/test/jdk/java/time/tck/java/time/TCKClock_Offset.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,8 @@ */ package tck.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import java.time.Clock; import java.time.Duration; @@ -69,12 +69,12 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Test offset clock. */ -@Test public class TCKClock_Offset extends AbstractTCKTest { private static final ZoneId MOSCOW = ZoneId.of("Europe/Moscow"); @@ -83,80 +83,86 @@ public class TCKClock_Offset extends AbstractTCKTest { private static final Duration OFFSET = Duration.ofSeconds(2); //----------------------------------------------------------------------- + @Test public void test_offset_ClockDuration() { Clock test = Clock.offset(Clock.fixed(INSTANT, PARIS), OFFSET); //System.out.println(test.instant()); //System.out.println(INSTANT.plus(OFFSET)); - assertEquals(test.instant(), INSTANT.plus(OFFSET)); - assertEquals(test.getZone(), PARIS); + assertEquals(INSTANT.plus(OFFSET), test.instant()); + assertEquals(PARIS, test.getZone()); } + @Test public void test_offset_ClockDuration_zeroDuration() { Clock underlying = Clock.system(PARIS); Clock test = Clock.offset(underlying, Duration.ZERO); assertSame(test, underlying); // spec says same } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_offset_ClockDuration_nullClock() { - Clock.offset(null, Duration.ZERO); + Assertions.assertThrows(NullPointerException.class, () -> Clock.offset(null, Duration.ZERO)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_offset_ClockDuration_nullDuration() { - Clock.offset(Clock.systemUTC(), null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.offset(Clock.systemUTC(), null)); } //------------------------------------------------------------------------- + @Test public void test_withZone() { Clock test = Clock.offset(Clock.system(PARIS), OFFSET); Clock changed = test.withZone(MOSCOW); - assertEquals(test.getZone(), PARIS); - assertEquals(changed.getZone(), MOSCOW); + assertEquals(PARIS, test.getZone()); + assertEquals(MOSCOW, changed.getZone()); } + @Test public void test_withZone_equal() { Clock test = Clock.offset(Clock.system(PARIS), OFFSET); Clock changed = test.withZone(PARIS); - assertEquals(test, changed); + assertEquals(changed, test); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_withZone_null() { - Clock.offset(Clock.system(PARIS), OFFSET).withZone(null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.offset(Clock.system(PARIS), OFFSET).withZone(null)); } //----------------------------------------------------------------------- + @Test public void test_equals() { Clock a = Clock.offset(Clock.system(PARIS), OFFSET); Clock b = Clock.offset(Clock.system(PARIS), OFFSET); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), true); - assertEquals(b.equals(a), true); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(true, a.equals(b)); + assertEquals(true, b.equals(a)); + assertEquals(true, b.equals(b)); Clock c = Clock.offset(Clock.system(MOSCOW), OFFSET); - assertEquals(a.equals(c), false); + assertEquals(false, a.equals(c)); Clock d = Clock.offset(Clock.system(PARIS), OFFSET.minusNanos(1)); - assertEquals(a.equals(d), false); + assertEquals(false, a.equals(d)); - assertEquals(a.equals(null), false); - assertEquals(a.equals("other type"), false); - assertEquals(a.equals(Clock.systemUTC()), false); + assertEquals(false, a.equals(null)); + assertEquals(false, a.equals("other type")); + assertEquals(false, a.equals(Clock.systemUTC())); } + @Test public void test_hashCode() { Clock a = Clock.offset(Clock.system(PARIS), OFFSET); Clock b = Clock.offset(Clock.system(PARIS), OFFSET); assertEquals(a.hashCode(), a.hashCode()); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); Clock c = Clock.offset(Clock.system(MOSCOW), OFFSET); - assertEquals(a.hashCode() == c.hashCode(), false); + assertEquals(false, a.hashCode() == c.hashCode()); Clock d = Clock.offset(Clock.system(PARIS), OFFSET.minusNanos(1)); - assertEquals(a.hashCode() == d.hashCode(), false); + assertEquals(false, a.hashCode() == d.hashCode()); } } diff --git a/test/jdk/java/time/tck/java/time/TCKClock_System.java b/test/jdk/java/time/tck/java/time/TCKClock_System.java index 94f3b57a4aa..5e5fd2a579d 100644 --- a/test/jdk/java/time/tck/java/time/TCKClock_System.java +++ b/test/jdk/java/time/tck/java/time/TCKClock_System.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,29 +59,30 @@ */ package tck.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Test system clock. */ -@Test public class TCKClock_System extends AbstractTCKTest { private static final ZoneId MOSCOW = ZoneId.of("Europe/Moscow"); private static final ZoneId PARIS = ZoneId.of("Europe/Paris"); //----------------------------------------------------------------------- + @Test public void test_instant() { Clock system = Clock.systemUTC(); - assertEquals(system.getZone(), ZoneOffset.UTC); + assertEquals(ZoneOffset.UTC, system.getZone()); for (int i = 0; i < 10000; i++) { // assume can eventually get these within 10 milliseconds Instant instant = system.instant(); @@ -93,9 +94,10 @@ public class TCKClock_System extends AbstractTCKTest { fail(); } + @Test public void test_millis() { Clock system = Clock.systemUTC(); - assertEquals(system.getZone(), ZoneOffset.UTC); + assertEquals(ZoneOffset.UTC, system.getZone()); for (int i = 0; i < 10000; i++) { // assume can eventually get these within 10 milliseconds long instant = system.millis(); @@ -108,85 +110,93 @@ public class TCKClock_System extends AbstractTCKTest { } //------------------------------------------------------------------------- + @Test public void test_systemUTC() { Clock test = Clock.systemUTC(); - assertEquals(test.getZone(), ZoneOffset.UTC); - assertEquals(test, Clock.system(ZoneOffset.UTC)); + assertEquals(ZoneOffset.UTC, test.getZone()); + assertEquals(Clock.system(ZoneOffset.UTC), test); } + @Test public void test_systemDefaultZone() { Clock test = Clock.systemDefaultZone(); - assertEquals(test.getZone(), ZoneId.systemDefault()); - assertEquals(test, Clock.system(ZoneId.systemDefault())); + assertEquals(ZoneId.systemDefault(), test.getZone()); + assertEquals(Clock.system(ZoneId.systemDefault()), test); } + @Test public void test_system_ZoneId() { Clock test = Clock.system(PARIS); - assertEquals(test.getZone(), PARIS); + assertEquals(PARIS, test.getZone()); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_zoneId_nullZoneId() { - Clock.system(null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.system(null)); } //------------------------------------------------------------------------- + @Test public void test_withZone() { Clock test = Clock.system(PARIS); Clock changed = test.withZone(MOSCOW); - assertEquals(test.getZone(), PARIS); - assertEquals(changed.getZone(), MOSCOW); + assertEquals(PARIS, test.getZone()); + assertEquals(MOSCOW, changed.getZone()); } + @Test public void test_withZone_equal() { Clock test = Clock.system(PARIS); Clock changed = test.withZone(PARIS); - assertEquals(changed.getZone(), PARIS); + assertEquals(PARIS, changed.getZone()); } + @Test public void test_withZone_fromUTC() { Clock test = Clock.systemUTC(); Clock changed = test.withZone(PARIS); - assertEquals(changed.getZone(), PARIS); + assertEquals(PARIS, changed.getZone()); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_withZone_null() { - Clock.systemUTC().withZone(null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.systemUTC().withZone(null)); } //----------------------------------------------------------------------- + @Test public void test_equals() { Clock a = Clock.systemUTC(); Clock b = Clock.systemUTC(); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), true); - assertEquals(b.equals(a), true); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(true, a.equals(b)); + assertEquals(true, b.equals(a)); + assertEquals(true, b.equals(b)); Clock c = Clock.system(PARIS); Clock d = Clock.system(PARIS); - assertEquals(c.equals(c), true); - assertEquals(c.equals(d), true); - assertEquals(d.equals(c), true); - assertEquals(d.equals(d), true); + assertEquals(true, c.equals(c)); + assertEquals(true, c.equals(d)); + assertEquals(true, d.equals(c)); + assertEquals(true, d.equals(d)); - assertEquals(a.equals(c), false); - assertEquals(c.equals(a), false); + assertEquals(false, a.equals(c)); + assertEquals(false, c.equals(a)); - assertEquals(a.equals(null), false); - assertEquals(a.equals("other type"), false); - assertEquals(a.equals(Clock.fixed(Instant.now(), ZoneOffset.UTC)), false); + assertEquals(false, a.equals(null)); + assertEquals(false, a.equals("other type")); + assertEquals(false, a.equals(Clock.fixed(Instant.now(), ZoneOffset.UTC))); } + @Test public void test_hashCode() { Clock a = Clock.system(ZoneOffset.UTC); Clock b = Clock.system(ZoneOffset.UTC); assertEquals(a.hashCode(), a.hashCode()); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); Clock c = Clock.system(PARIS); - assertEquals(a.hashCode() == c.hashCode(), false); + assertEquals(false, a.hashCode() == c.hashCode()); } } diff --git a/test/jdk/java/time/tck/java/time/TCKClock_Tick.java b/test/jdk/java/time/tck/java/time/TCKClock_Tick.java index 08b0a524828..d589daede5f 100644 --- a/test/jdk/java/time/tck/java/time/TCKClock_Tick.java +++ b/test/jdk/java/time/tck/java/time/TCKClock_Tick.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,8 @@ */ package tck.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import java.time.Clock; import java.time.Duration; @@ -70,12 +70,12 @@ import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Test tick clock. */ -@Test public class TCKClock_Tick extends AbstractTCKTest { private static final ZoneId MOSCOW = ZoneId.of("Europe/Moscow"); @@ -83,170 +83,182 @@ public class TCKClock_Tick extends AbstractTCKTest { private static final ZonedDateTime ZDT = LocalDateTime.of(2008, 6, 30, 11, 30, 10, 500).atZone(ZoneOffset.ofHours(2)); //----------------------------------------------------------------------- + @Test public void test_tick_ClockDuration_250millis() { for (int i = 0; i < 1000; i++) { Clock test = Clock.tick(Clock.fixed(ZDT.withNano(i * 1000_000).toInstant(), PARIS), Duration.ofMillis(250)); - assertEquals(test.instant(), ZDT.withNano((i / 250) * 250_000_000).toInstant()); - assertEquals(test.getZone(), PARIS); + assertEquals(ZDT.withNano((i / 250) * 250_000_000).toInstant(), test.instant()); + assertEquals(PARIS, test.getZone()); } } + @Test public void test_tick_ClockDuration_250micros() { for (int i = 0; i < 1000; i++) { Clock test = Clock.tick(Clock.fixed(ZDT.withNano(i * 1000).toInstant(), PARIS), Duration.ofNanos(250_000)); - assertEquals(test.instant(), ZDT.withNano((i / 250) * 250_000).toInstant()); - assertEquals(test.getZone(), PARIS); + assertEquals(ZDT.withNano((i / 250) * 250_000).toInstant(), test.instant()); + assertEquals(PARIS, test.getZone()); } } + @Test public void test_tick_ClockDuration_20nanos() { for (int i = 0; i < 1000; i++) { Clock test = Clock.tick(Clock.fixed(ZDT.withNano(i).toInstant(), PARIS), Duration.ofNanos(20)); - assertEquals(test.instant(), ZDT.withNano((i / 20) * 20).toInstant()); - assertEquals(test.getZone(), PARIS); + assertEquals(ZDT.withNano((i / 20) * 20).toInstant(), test.instant()); + assertEquals(PARIS, test.getZone()); } } + @Test public void test_tick_ClockDuration_zeroDuration() { Clock underlying = Clock.system(PARIS); Clock test = Clock.tick(underlying, Duration.ZERO); assertSame(test, underlying); // spec says same } + @Test public void test_tick_ClockDuration_1nsDuration() { Clock underlying = Clock.system(PARIS); Clock test = Clock.tick(underlying, Duration.ofNanos(1)); assertSame(test, underlying); // spec says same } - @Test(expectedExceptions = ArithmeticException.class) + @Test public void test_tick_ClockDuration_maxDuration() { - Clock.tick(Clock.systemUTC(), Duration.ofSeconds(Long.MAX_VALUE)); + Assertions.assertThrows(ArithmeticException.class, () -> Clock.tick(Clock.systemUTC(), Duration.ofSeconds(Long.MAX_VALUE))); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_tick_ClockDuration_subMilliNotDivisible_123ns() { - Clock.tick(Clock.systemUTC(), Duration.ofSeconds(0, 123)); + Assertions.assertThrows(IllegalArgumentException.class, () -> Clock.tick(Clock.systemUTC(), Duration.ofSeconds(0, 123))); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_tick_ClockDuration_subMilliNotDivisible_999ns() { - Clock.tick(Clock.systemUTC(), Duration.ofSeconds(0, 999)); + Assertions.assertThrows(IllegalArgumentException.class, () -> Clock.tick(Clock.systemUTC(), Duration.ofSeconds(0, 999))); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_tick_ClockDuration_subMilliNotDivisible_999_999_999ns() { - Clock.tick(Clock.systemUTC(), Duration.ofSeconds(0, 999_999_999)); + Assertions.assertThrows(IllegalArgumentException.class, () -> Clock.tick(Clock.systemUTC(), Duration.ofSeconds(0, 999_999_999))); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_tick_ClockDuration_negative1ns() { - Clock.tick(Clock.systemUTC(), Duration.ofSeconds(0, -1)); + Assertions.assertThrows(IllegalArgumentException.class, () -> Clock.tick(Clock.systemUTC(), Duration.ofSeconds(0, -1))); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_tick_ClockDuration_negative1s() { - Clock.tick(Clock.systemUTC(), Duration.ofSeconds(-1)); + Assertions.assertThrows(IllegalArgumentException.class, () -> Clock.tick(Clock.systemUTC(), Duration.ofSeconds(-1))); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_tick_ClockDuration_nullClock() { - Clock.tick(null, Duration.ZERO); + Assertions.assertThrows(NullPointerException.class, () -> Clock.tick(null, Duration.ZERO)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_tick_ClockDuration_nullDuration() { - Clock.tick(Clock.systemUTC(), null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.tick(Clock.systemUTC(), null)); } //----------------------------------------------------------------------- + @Test public void test_tickMillis_ZoneId() throws Exception { Clock test = Clock.tickMillis(PARIS); - assertEquals(test.getZone(), PARIS); - assertEquals(test.instant().getNano() % 1000_000, 0); + assertEquals(PARIS, test.getZone()); + assertEquals(0, test.instant().getNano() % 1000_000); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_tickMillis_ZoneId_nullZoneId() { - Clock.tickMillis(null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.tickMillis(null)); } //----------------------------------------------------------------------- + @Test public void test_tickSeconds_ZoneId() throws Exception { Clock test = Clock.tickSeconds(PARIS); - assertEquals(test.getZone(), PARIS); - assertEquals(test.instant().getNano(), 0); + assertEquals(PARIS, test.getZone()); + assertEquals(0, test.instant().getNano()); Thread.sleep(100); - assertEquals(test.instant().getNano(), 0); + assertEquals(0, test.instant().getNano()); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_tickSeconds_ZoneId_nullZoneId() { - Clock.tickSeconds(null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.tickSeconds(null)); } //----------------------------------------------------------------------- + @Test public void test_tickMinutes_ZoneId() { Clock test = Clock.tickMinutes(PARIS); - assertEquals(test.getZone(), PARIS); + assertEquals(PARIS, test.getZone()); Instant instant = test.instant(); - assertEquals(instant.getEpochSecond() % 60, 0); - assertEquals(instant.getNano(), 0); + assertEquals(0, instant.getEpochSecond() % 60); + assertEquals(0, instant.getNano()); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_tickMinutes_ZoneId_nullZoneId() { - Clock.tickMinutes(null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.tickMinutes(null)); } //------------------------------------------------------------------------- + @Test public void test_withZone() { Clock test = Clock.tick(Clock.system(PARIS), Duration.ofMillis(500)); Clock changed = test.withZone(MOSCOW); - assertEquals(test.getZone(), PARIS); - assertEquals(changed.getZone(), MOSCOW); + assertEquals(PARIS, test.getZone()); + assertEquals(MOSCOW, changed.getZone()); } + @Test public void test_withZone_equal() { Clock test = Clock.tick(Clock.system(PARIS), Duration.ofMillis(500)); Clock changed = test.withZone(PARIS); - assertEquals(test, changed); + assertEquals(changed, test); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_withZone_null() { - Clock.tick(Clock.system(PARIS), Duration.ofMillis(500)).withZone(null); + Assertions.assertThrows(NullPointerException.class, () -> Clock.tick(Clock.system(PARIS), Duration.ofMillis(500)).withZone(null)); } //----------------------------------------------------------------------- + @Test public void test__equals() { Clock a = Clock.tick(Clock.system(PARIS), Duration.ofMillis(500)); Clock b = Clock.tick(Clock.system(PARIS), Duration.ofMillis(500)); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), true); - assertEquals(b.equals(a), true); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(true, a.equals(b)); + assertEquals(true, b.equals(a)); + assertEquals(true, b.equals(b)); Clock c = Clock.tick(Clock.system(MOSCOW), Duration.ofMillis(500)); - assertEquals(a.equals(c), false); + assertEquals(false, a.equals(c)); Clock d = Clock.tick(Clock.system(PARIS), Duration.ofMillis(499)); - assertEquals(a.equals(d), false); + assertEquals(false, a.equals(d)); - assertEquals(a.equals(null), false); - assertEquals(a.equals("other type"), false); - assertEquals(a.equals(Clock.systemUTC()), false); + assertEquals(false, a.equals(null)); + assertEquals(false, a.equals("other type")); + assertEquals(false, a.equals(Clock.systemUTC())); } + @Test public void test_hashCode() { Clock a = Clock.tick(Clock.system(PARIS), Duration.ofMillis(500)); Clock b = Clock.tick(Clock.system(PARIS), Duration.ofMillis(500)); assertEquals(a.hashCode(), a.hashCode()); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); Clock c = Clock.tick(Clock.system(MOSCOW), Duration.ofMillis(500)); - assertEquals(a.hashCode() == c.hashCode(), false); + assertEquals(false, a.hashCode() == c.hashCode()); Clock d = Clock.tick(Clock.system(PARIS), Duration.ofMillis(499)); - assertEquals(a.hashCode() == d.hashCode(), false); + assertEquals(false, a.hashCode() == d.hashCode()); } } diff --git a/test/jdk/java/time/tck/java/time/TCKDayOfWeek.java b/test/jdk/java/time/tck/java/time/TCKDayOfWeek.java index e3f0e719ccb..efb6fc7e9ae 100644 --- a/test/jdk/java/time/tck/java/time/TCKDayOfWeek.java +++ b/test/jdk/java/time/tck/java/time/TCKDayOfWeek.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -63,8 +63,9 @@ import static java.time.DayOfWeek.MONDAY; import static java.time.DayOfWeek.SUNDAY; import static java.time.DayOfWeek.WEDNESDAY; import static java.time.temporal.ChronoField.DAY_OF_WEEK; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import java.time.DateTimeException; import java.time.DayOfWeek; @@ -84,17 +85,20 @@ import java.util.Arrays; import java.util.List; import java.util.Locale; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DayOfWeek. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKDayOfWeek extends AbstractDateTimeTest { - @BeforeMethod + @BeforeEach public void setUp() { } @@ -128,35 +132,35 @@ public class TCKDayOfWeek extends AbstractDateTimeTest { public void test_factory_int_singleton() { for (int i = 1; i <= 7; i++) { DayOfWeek test = DayOfWeek.of(i); - assertEquals(test.getValue(), i); + assertEquals(i, test.getValue()); assertSame(DayOfWeek.of(i), test); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_valueTooLow() { - DayOfWeek.of(0); + Assertions.assertThrows(DateTimeException.class, () -> DayOfWeek.of(0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_valueTooHigh() { - DayOfWeek.of(8); + Assertions.assertThrows(DateTimeException.class, () -> DayOfWeek.of(8)); } //----------------------------------------------------------------------- @Test public void test_factory_CalendricalObject() { - assertEquals(DayOfWeek.from(LocalDate.of(2011, 6, 6)), DayOfWeek.MONDAY); + assertEquals(DayOfWeek.MONDAY, DayOfWeek.from(LocalDate.of(2011, 6, 6))); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_CalendricalObject_invalid_noDerive() { - DayOfWeek.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> DayOfWeek.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_CalendricalObject_null() { - DayOfWeek.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> DayOfWeek.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- @@ -164,37 +168,37 @@ public class TCKDayOfWeek extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(DayOfWeek.THURSDAY.isSupported((TemporalField) null), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.NANO_OF_SECOND), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.NANO_OF_DAY), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.MICRO_OF_SECOND), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.MICRO_OF_DAY), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.MILLI_OF_SECOND), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.MILLI_OF_DAY), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.SECOND_OF_MINUTE), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.SECOND_OF_DAY), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.MINUTE_OF_HOUR), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.MINUTE_OF_DAY), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.HOUR_OF_AMPM), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.HOUR_OF_DAY), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.AMPM_OF_DAY), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.DAY_OF_WEEK), true); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.DAY_OF_MONTH), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.DAY_OF_YEAR), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.EPOCH_DAY), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.MONTH_OF_YEAR), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.PROLEPTIC_MONTH), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.YEAR), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.YEAR_OF_ERA), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.ERA), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.INSTANT_SECONDS), false); - assertEquals(DayOfWeek.THURSDAY.isSupported(ChronoField.OFFSET_SECONDS), false); + assertEquals(false, DayOfWeek.THURSDAY.isSupported((TemporalField) null)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(true, DayOfWeek.THURSDAY.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.YEAR)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.ERA)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(false, DayOfWeek.THURSDAY.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -202,18 +206,17 @@ public class TCKDayOfWeek extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_get_TemporalField() { - assertEquals(DayOfWeek.WEDNESDAY.getLong(ChronoField.DAY_OF_WEEK), 3); + assertEquals(3, DayOfWeek.WEDNESDAY.getLong(ChronoField.DAY_OF_WEEK)); } @Test public void test_getLong_TemporalField() { - assertEquals(DayOfWeek.WEDNESDAY.getLong(ChronoField.DAY_OF_WEEK), 3); + assertEquals(3, DayOfWeek.WEDNESDAY.getLong(ChronoField.DAY_OF_WEEK)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {DayOfWeek.FRIDAY, TemporalQueries.chronology(), null}, @@ -226,19 +229,21 @@ public class TCKDayOfWeek extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - DayOfWeek.FRIDAY.query(null); + Assertions.assertThrows(NullPointerException.class, () -> DayOfWeek.FRIDAY.query(null)); } //----------------------------------------------------------------------- @@ -246,23 +251,22 @@ public class TCKDayOfWeek extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_getText() { - assertEquals(DayOfWeek.MONDAY.getDisplayName(TextStyle.SHORT, Locale.US), "Mon"); + assertEquals("Mon", DayOfWeek.MONDAY.getDisplayName(TextStyle.SHORT, Locale.US)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_getText_nullStyle() { - DayOfWeek.MONDAY.getDisplayName(null, Locale.US); + Assertions.assertThrows(NullPointerException.class, () -> DayOfWeek.MONDAY.getDisplayName(null, Locale.US)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_getText_nullLocale() { - DayOfWeek.MONDAY.getDisplayName(TextStyle.FULL, null); + Assertions.assertThrows(NullPointerException.class, () -> DayOfWeek.MONDAY.getDisplayName(TextStyle.FULL, null)); } //----------------------------------------------------------------------- // plus(long), plus(long,unit) //----------------------------------------------------------------------- - @DataProvider(name="plus") Object[][] data_plus() { return new Object[][] { {1, -8, 7}, @@ -301,15 +305,15 @@ public class TCKDayOfWeek extends AbstractDateTimeTest { }; } - @Test(dataProvider="plus") + @ParameterizedTest + @MethodSource("data_plus") public void test_plus_long(int base, long amount, int expected) { - assertEquals(DayOfWeek.of(base).plus(amount), DayOfWeek.of(expected)); + assertEquals(DayOfWeek.of(expected), DayOfWeek.of(base).plus(amount)); } //----------------------------------------------------------------------- // minus(long), minus(long,unit) //----------------------------------------------------------------------- - @DataProvider(name="minus") Object[][] data_minus() { return new Object[][] { {1, -8, 2}, @@ -332,9 +336,10 @@ public class TCKDayOfWeek extends AbstractDateTimeTest { }; } - @Test(dataProvider="minus") + @ParameterizedTest + @MethodSource("data_minus") public void test_minus_long(int base, long amount, int expected) { - assertEquals(DayOfWeek.of(base).minus(amount), DayOfWeek.of(expected)); + assertEquals(DayOfWeek.of(expected), DayOfWeek.of(base).minus(amount)); } //----------------------------------------------------------------------- @@ -342,16 +347,16 @@ public class TCKDayOfWeek extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_adjustInto() { - assertEquals(DayOfWeek.MONDAY.adjustInto(LocalDate.of(2012, 9, 2)), LocalDate.of(2012, 8, 27)); - assertEquals(DayOfWeek.MONDAY.adjustInto(LocalDate.of(2012, 9, 3)), LocalDate.of(2012, 9, 3)); - assertEquals(DayOfWeek.MONDAY.adjustInto(LocalDate.of(2012, 9, 4)), LocalDate.of(2012, 9, 3)); - assertEquals(DayOfWeek.MONDAY.adjustInto(LocalDate.of(2012, 9, 10)), LocalDate.of(2012, 9, 10)); - assertEquals(DayOfWeek.MONDAY.adjustInto(LocalDate.of(2012, 9, 11)), LocalDate.of(2012, 9, 10)); + assertEquals(LocalDate.of(2012, 8, 27), DayOfWeek.MONDAY.adjustInto(LocalDate.of(2012, 9, 2))); + assertEquals(LocalDate.of(2012, 9, 3), DayOfWeek.MONDAY.adjustInto(LocalDate.of(2012, 9, 3))); + assertEquals(LocalDate.of(2012, 9, 3), DayOfWeek.MONDAY.adjustInto(LocalDate.of(2012, 9, 4))); + assertEquals(LocalDate.of(2012, 9, 10), DayOfWeek.MONDAY.adjustInto(LocalDate.of(2012, 9, 10))); + assertEquals(LocalDate.of(2012, 9, 10), DayOfWeek.MONDAY.adjustInto(LocalDate.of(2012, 9, 11))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_adjustInto_null() { - DayOfWeek.MONDAY.adjustInto((Temporal) null); + Assertions.assertThrows(NullPointerException.class, () -> DayOfWeek.MONDAY.adjustInto((Temporal) null)); } //----------------------------------------------------------------------- @@ -359,13 +364,13 @@ public class TCKDayOfWeek extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_toString() { - assertEquals(DayOfWeek.MONDAY.toString(), "MONDAY"); - assertEquals(DayOfWeek.TUESDAY.toString(), "TUESDAY"); - assertEquals(DayOfWeek.WEDNESDAY.toString(), "WEDNESDAY"); - assertEquals(DayOfWeek.THURSDAY.toString(), "THURSDAY"); - assertEquals(DayOfWeek.FRIDAY.toString(), "FRIDAY"); - assertEquals(DayOfWeek.SATURDAY.toString(), "SATURDAY"); - assertEquals(DayOfWeek.SUNDAY.toString(), "SUNDAY"); + assertEquals("MONDAY", DayOfWeek.MONDAY.toString()); + assertEquals("TUESDAY", DayOfWeek.TUESDAY.toString()); + assertEquals("WEDNESDAY", DayOfWeek.WEDNESDAY.toString()); + assertEquals("THURSDAY", DayOfWeek.THURSDAY.toString()); + assertEquals("FRIDAY", DayOfWeek.FRIDAY.toString()); + assertEquals("SATURDAY", DayOfWeek.SATURDAY.toString()); + assertEquals("SUNDAY", DayOfWeek.SUNDAY.toString()); } //----------------------------------------------------------------------- @@ -373,8 +378,8 @@ public class TCKDayOfWeek extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_enum() { - assertEquals(DayOfWeek.valueOf("MONDAY"), DayOfWeek.MONDAY); - assertEquals(DayOfWeek.values()[0], DayOfWeek.MONDAY); + assertEquals(DayOfWeek.MONDAY, DayOfWeek.valueOf("MONDAY")); + assertEquals(DayOfWeek.MONDAY, DayOfWeek.values()[0]); } } diff --git a/test/jdk/java/time/tck/java/time/TCKDuration.java b/test/jdk/java/time/tck/java/time/TCKDuration.java index 2057e8e8939..1c9225e178a 100644 --- a/test/jdk/java/time/tck/java/time/TCKDuration.java +++ b/test/jdk/java/time/tck/java/time/TCKDuration.java @@ -70,11 +70,12 @@ import static java.time.temporal.ChronoUnit.NANOS; import static java.time.temporal.ChronoUnit.SECONDS; import static java.time.temporal.ChronoUnit.WEEKS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; @@ -97,13 +98,16 @@ import java.util.Collections; import java.util.List; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test Duration. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKDuration extends AbstractTCKTest { private static final long CYCLE_SECS = 146097L * 86400L; @@ -113,22 +117,22 @@ public class TCKDuration extends AbstractTCKTest { //----------------------------------------------------------------------- @Test public void test_zero() { - assertEquals(Duration.ZERO.getSeconds(), 0L); - assertEquals(Duration.ZERO.getNano(), 0); + assertEquals(0L, Duration.ZERO.getSeconds()); + assertEquals(0, Duration.ZERO.getNano()); } @Test public void test_min() { - assertEquals(Duration.MIN.getSeconds(), Long.MIN_VALUE); - assertEquals(Duration.MIN.getNano(), 0); + assertEquals(Long.MIN_VALUE, Duration.MIN.getSeconds()); + assertEquals(0, Duration.MIN.getNano()); // no duration minimally less than MIN assertThrows(ArithmeticException.class, () -> Duration.MIN.minusNanos(1)); } @Test public void test_max() { - assertEquals(Duration.MAX.getSeconds(), Long.MAX_VALUE); - assertEquals(Duration.MAX.getNano(), 999_999_999); + assertEquals(Long.MAX_VALUE, Duration.MAX.getSeconds()); + assertEquals(999_999_999, Duration.MAX.getNano()); // no duration minimally greater than MAX assertThrows(ArithmeticException.class, () -> Duration.MAX.plusNanos(1)); } @@ -144,15 +148,15 @@ public class TCKDuration extends AbstractTCKTest { assertTrue(Duration.MIN.compareTo(Duration.ZERO) < 0); assertTrue(Duration.ZERO.compareTo(Duration.MIN) > 0); - assertNotEquals(Duration.ZERO, Duration.MIN); + assertNotEquals(Duration.MIN, Duration.ZERO); assertTrue(Duration.ZERO.compareTo(Duration.MAX) < 0); assertTrue(Duration.MAX.compareTo(Duration.ZERO) > 0); - assertNotEquals(Duration.ZERO, Duration.MAX); + assertNotEquals(Duration.MAX, Duration.ZERO); assertTrue(Duration.MIN.compareTo(Duration.MAX) < 0); assertTrue(Duration.MAX.compareTo(Duration.MIN) > 0); - assertNotEquals(Duration.MIN, Duration.MAX); + assertNotEquals(Duration.MAX, Duration.MIN); } //----------------------------------------------------------------------- @@ -162,8 +166,8 @@ public class TCKDuration extends AbstractTCKTest { public void factory_seconds_long() { for (long i = -2; i <= 2; i++) { Duration t = Duration.ofSeconds(i); - assertEquals(t.getSeconds(), i); - assertEquals(t.getNano(), 0); + assertEquals(i, t.getSeconds()); + assertEquals(0, t.getNano()); } } @@ -175,18 +179,18 @@ public class TCKDuration extends AbstractTCKTest { for (long i = -2; i <= 2; i++) { for (int j = 0; j < 10; j++) { Duration t = Duration.ofSeconds(i, j); - assertEquals(t.getSeconds(), i); - assertEquals(t.getNano(), j); + assertEquals(i, t.getSeconds()); + assertEquals(j, t.getNano()); } for (int j = -10; j < 0; j++) { Duration t = Duration.ofSeconds(i, j); - assertEquals(t.getSeconds(), i - 1); - assertEquals(t.getNano(), j + 1000000000); + assertEquals(i - 1, t.getSeconds()); + assertEquals(j + 1000000000, t.getNano()); } for (int j = 999999990; j < 1000000000; j++) { Duration t = Duration.ofSeconds(i, j); - assertEquals(t.getSeconds(), i); - assertEquals(t.getNano(), j); + assertEquals(i, t.getSeconds()); + assertEquals(j, t.getNano()); } } } @@ -194,19 +198,18 @@ public class TCKDuration extends AbstractTCKTest { @Test public void factory_seconds_long_long_nanosNegativeAdjusted() { Duration test = Duration.ofSeconds(2L, -1); - assertEquals(test.getSeconds(), 1); - assertEquals(test.getNano(), 999999999); + assertEquals(1, test.getSeconds()); + assertEquals(999999999, test.getNano()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void factory_seconds_long_long_tooBig() { - Duration.ofSeconds(Long.MAX_VALUE, 1000000000); + Assertions.assertThrows(ArithmeticException.class, () -> Duration.ofSeconds(Long.MAX_VALUE, 1000000000)); } //----------------------------------------------------------------------- // ofMillis(long) //----------------------------------------------------------------------- - @DataProvider(name="MillisDurationNoNanos") Object[][] provider_factory_millis_long() { return new Object[][] { {0, 0, 0}, @@ -223,11 +226,12 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="MillisDurationNoNanos") + @ParameterizedTest + @MethodSource("provider_factory_millis_long") public void factory_millis_long(long millis, long expectedSeconds, int expectedNanoOfSecond) { Duration test = Duration.ofMillis(millis); - assertEquals(test.getSeconds(), expectedSeconds); - assertEquals(test.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, test.getSeconds()); + assertEquals(expectedNanoOfSecond, test.getNano()); } //----------------------------------------------------------------------- @@ -236,36 +240,36 @@ public class TCKDuration extends AbstractTCKTest { @Test public void factory_nanos_nanos() { Duration test = Duration.ofNanos(1); - assertEquals(test.getSeconds(), 0); - assertEquals(test.getNano(), 1); + assertEquals(0, test.getSeconds()); + assertEquals(1, test.getNano()); } @Test public void factory_nanos_nanosSecs() { Duration test = Duration.ofNanos(1000000002); - assertEquals(test.getSeconds(), 1); - assertEquals(test.getNano(), 2); + assertEquals(1, test.getSeconds()); + assertEquals(2, test.getNano()); } @Test public void factory_nanos_negative() { Duration test = Duration.ofNanos(-2000000001); - assertEquals(test.getSeconds(), -3); - assertEquals(test.getNano(), 999999999); + assertEquals(-3, test.getSeconds()); + assertEquals(999999999, test.getNano()); } @Test public void factory_nanos_max() { Duration test = Duration.ofNanos(Long.MAX_VALUE); - assertEquals(test.getSeconds(), Long.MAX_VALUE / 1000000000); - assertEquals(test.getNano(), Long.MAX_VALUE % 1000000000); + assertEquals(Long.MAX_VALUE / 1000000000, test.getSeconds()); + assertEquals(Long.MAX_VALUE % 1000000000, test.getNano()); } @Test public void factory_nanos_min() { Duration test = Duration.ofNanos(Long.MIN_VALUE); - assertEquals(test.getSeconds(), Long.MIN_VALUE / 1000000000 - 1); - assertEquals(test.getNano(), Long.MIN_VALUE % 1000000000 + 1000000000); + assertEquals(Long.MIN_VALUE / 1000000000 - 1, test.getSeconds()); + assertEquals(Long.MIN_VALUE % 1000000000 + 1000000000, test.getNano()); } //----------------------------------------------------------------------- @@ -274,32 +278,32 @@ public class TCKDuration extends AbstractTCKTest { @Test public void factory_minutes() { Duration test = Duration.ofMinutes(2); - assertEquals(test.getSeconds(), 120); - assertEquals(test.getNano(), 0); + assertEquals(120, test.getSeconds()); + assertEquals(0, test.getNano()); } @Test public void factory_minutes_max() { Duration test = Duration.ofMinutes(Long.MAX_VALUE / 60); - assertEquals(test.getSeconds(), (Long.MAX_VALUE / 60) * 60); - assertEquals(test.getNano(), 0); + assertEquals((Long.MAX_VALUE / 60) * 60, test.getSeconds()); + assertEquals(0, test.getNano()); } @Test public void factory_minutes_min() { Duration test = Duration.ofMinutes(Long.MIN_VALUE / 60); - assertEquals(test.getSeconds(), (Long.MIN_VALUE / 60) * 60); - assertEquals(test.getNano(), 0); + assertEquals((Long.MIN_VALUE / 60) * 60, test.getSeconds()); + assertEquals(0, test.getNano()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void factory_minutes_tooBig() { - Duration.ofMinutes(Long.MAX_VALUE / 60 + 1); + Assertions.assertThrows(ArithmeticException.class, () -> Duration.ofMinutes(Long.MAX_VALUE / 60 + 1)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void factory_minutes_tooSmall() { - Duration.ofMinutes(Long.MIN_VALUE / 60 - 1); + Assertions.assertThrows(ArithmeticException.class, () -> Duration.ofMinutes(Long.MIN_VALUE / 60 - 1)); } //----------------------------------------------------------------------- @@ -308,32 +312,32 @@ public class TCKDuration extends AbstractTCKTest { @Test public void factory_hours() { Duration test = Duration.ofHours(2); - assertEquals(test.getSeconds(), 2 * 3600); - assertEquals(test.getNano(), 0); + assertEquals(2 * 3600, test.getSeconds()); + assertEquals(0, test.getNano()); } @Test public void factory_hours_max() { Duration test = Duration.ofHours(Long.MAX_VALUE / 3600); - assertEquals(test.getSeconds(), (Long.MAX_VALUE / 3600) * 3600); - assertEquals(test.getNano(), 0); + assertEquals((Long.MAX_VALUE / 3600) * 3600, test.getSeconds()); + assertEquals(0, test.getNano()); } @Test public void factory_hours_min() { Duration test = Duration.ofHours(Long.MIN_VALUE / 3600); - assertEquals(test.getSeconds(), (Long.MIN_VALUE / 3600) * 3600); - assertEquals(test.getNano(), 0); + assertEquals((Long.MIN_VALUE / 3600) * 3600, test.getSeconds()); + assertEquals(0, test.getNano()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void factory_hours_tooBig() { - Duration.ofHours(Long.MAX_VALUE / 3600 + 1); + Assertions.assertThrows(ArithmeticException.class, () -> Duration.ofHours(Long.MAX_VALUE / 3600 + 1)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void factory_hours_tooSmall() { - Duration.ofHours(Long.MIN_VALUE / 3600 - 1); + Assertions.assertThrows(ArithmeticException.class, () -> Duration.ofHours(Long.MIN_VALUE / 3600 - 1)); } //----------------------------------------------------------------------- @@ -342,38 +346,37 @@ public class TCKDuration extends AbstractTCKTest { @Test public void factory_days() { Duration test = Duration.ofDays(2); - assertEquals(test.getSeconds(), 2 * 86400); - assertEquals(test.getNano(), 0); + assertEquals(2 * 86400, test.getSeconds()); + assertEquals(0, test.getNano()); } @Test public void factory_days_max() { Duration test = Duration.ofDays(Long.MAX_VALUE / 86400); - assertEquals(test.getSeconds(), (Long.MAX_VALUE / 86400) * 86400); - assertEquals(test.getNano(), 0); + assertEquals((Long.MAX_VALUE / 86400) * 86400, test.getSeconds()); + assertEquals(0, test.getNano()); } @Test public void factory_days_min() { Duration test = Duration.ofDays(Long.MIN_VALUE / 86400); - assertEquals(test.getSeconds(), (Long.MIN_VALUE / 86400) * 86400); - assertEquals(test.getNano(), 0); + assertEquals((Long.MIN_VALUE / 86400) * 86400, test.getSeconds()); + assertEquals(0, test.getNano()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void factory_days_tooBig() { - Duration.ofDays(Long.MAX_VALUE / 86400 + 1); + Assertions.assertThrows(ArithmeticException.class, () -> Duration.ofDays(Long.MAX_VALUE / 86400 + 1)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void factory_days_tooSmall() { - Duration.ofDays(Long.MIN_VALUE / 86400 - 1); + Assertions.assertThrows(ArithmeticException.class, () -> Duration.ofDays(Long.MIN_VALUE / 86400 - 1)); } //----------------------------------------------------------------------- // of(long,TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="OfTemporalUnit") Object[][] provider_factory_of_longTemporalUnit() { return new Object[][] { {0, NANOS, 0, 0}, @@ -433,14 +436,14 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="OfTemporalUnit") + @ParameterizedTest + @MethodSource("provider_factory_of_longTemporalUnit") public void factory_of_longTemporalUnit(long amount, TemporalUnit unit, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.of(amount, unit); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @DataProvider(name="OfTemporalUnitOutOfRange") Object[][] provider_factory_of_longTemporalUnit_outOfRange() { return new Object[][] { {Long.MAX_VALUE / 60 + 1, MINUTES}, @@ -452,19 +455,20 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="OfTemporalUnitOutOfRange", expectedExceptions=ArithmeticException.class) + @ParameterizedTest + @MethodSource("provider_factory_of_longTemporalUnit_outOfRange") public void factory_of_longTemporalUnit_outOfRange(long amount, TemporalUnit unit) { - Duration.of(amount, unit); + Assertions.assertThrows(ArithmeticException.class, () -> Duration.of(amount, unit)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_longTemporalUnit_estimatedUnit() { - Duration.of(2, WEEKS); + Assertions.assertThrows(DateTimeException.class, () -> Duration.of(2, WEEKS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_longTemporalUnit_null() { - Duration.of(1, (TemporalUnit) null); + Assertions.assertThrows(NullPointerException.class, () -> Duration.of(1, (TemporalUnit) null)); } //----------------------------------------------------------------------- @@ -473,7 +477,7 @@ public class TCKDuration extends AbstractTCKTest { @Test public void factory_from_TemporalAmount_Duration() { TemporalAmount amount = Duration.ofHours(3); - assertEquals(Duration.from(amount), Duration.ofHours(3)); + assertEquals(Duration.ofHours(3), Duration.from(amount)); } @Test @@ -504,47 +508,48 @@ public class TCKDuration extends AbstractTCKTest { } }; Duration t = Duration.from(amount); - assertEquals(t.getSeconds(), 23 * 86400); - assertEquals(t.getNano(), 45); + assertEquals(23 * 86400, t.getSeconds()); + assertEquals(45, t.getNano()); } - @Test(expectedExceptions = ArithmeticException.class) + @Test public void factory_from_TemporalAmount_Minutes_tooBig() { - TemporalAmount amount = new TemporalAmount() { - @Override - public long get(TemporalUnit unit) { - return (Long.MAX_VALUE / 60) + 2; - } - @Override - public List getUnits() { - return Collections.singletonList(MINUTES); - } - @Override - public Temporal addTo(Temporal temporal) { - throw new UnsupportedOperationException(); - } - @Override - public Temporal subtractFrom(Temporal temporal) { - throw new UnsupportedOperationException(); - } - }; - Duration.from(amount); + Assertions.assertThrows(ArithmeticException.class, () -> { + TemporalAmount amount = new TemporalAmount() { + @Override + public long get(TemporalUnit unit) { + return (Long.MAX_VALUE / 60) + 2; + } + @Override + public List getUnits() { + return Collections.singletonList(MINUTES); + } + @Override + public Temporal addTo(Temporal temporal) { + throw new UnsupportedOperationException(); + } + @Override + public Temporal subtractFrom(Temporal temporal) { + throw new UnsupportedOperationException(); + } + }; + Duration.from(amount); + }); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void factory_from_TemporalAmount_Period() { - Duration.from(Period.ZERO); + Assertions.assertThrows(DateTimeException.class, () -> Duration.from(Period.ZERO)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void factory_from_TemporalAmount_null() { - Duration.from(null); + Assertions.assertThrows(NullPointerException.class, () -> Duration.from(null)); } //----------------------------------------------------------------------- // parse(String) //----------------------------------------------------------------------- - @DataProvider(name="parseSuccess") Object[][] data_parseSuccess() { return new Object[][] { {"PT0S", 0, 0}, @@ -687,49 +692,53 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void factory_parse(String text, long expectedSeconds, int expectedNanoOfSecond) { Duration test = Duration.parse(text); - assertEquals(test.getSeconds(), expectedSeconds); - assertEquals(test.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, test.getSeconds()); + assertEquals(expectedNanoOfSecond, test.getNano()); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void factory_parse_plus(String text, long expectedSeconds, int expectedNanoOfSecond) { Duration test = Duration.parse("+" + text); - assertEquals(test.getSeconds(), expectedSeconds); - assertEquals(test.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, test.getSeconds()); + assertEquals(expectedNanoOfSecond, test.getNano()); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void factory_parse_minus(String text, long expectedSeconds, int expectedNanoOfSecond) { Duration test; try { test = Duration.parse("-" + text); } catch (DateTimeParseException ex) { - assertEquals(expectedSeconds == Long.MIN_VALUE, true); + assertEquals(true, expectedSeconds == Long.MIN_VALUE); return; } // not inside try/catch or it breaks test - assertEquals(test, Duration.ofSeconds(expectedSeconds, expectedNanoOfSecond).negated()); + assertEquals(Duration.ofSeconds(expectedSeconds, expectedNanoOfSecond).negated(), test); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void factory_parse_comma(String text, long expectedSeconds, int expectedNanoOfSecond) { text = text.replace('.', ','); Duration test = Duration.parse(text); - assertEquals(test.getSeconds(), expectedSeconds); - assertEquals(test.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, test.getSeconds()); + assertEquals(expectedNanoOfSecond, test.getNano()); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void factory_parse_lowerCase(String text, long expectedSeconds, int expectedNanoOfSecond) { Duration test = Duration.parse(text.toLowerCase(Locale.ENGLISH)); - assertEquals(test.getSeconds(), expectedSeconds); - assertEquals(test.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, test.getSeconds()); + assertEquals(expectedNanoOfSecond, test.getNano()); } - @DataProvider(name="parseFailure") Object[][] data_parseFailure() { return new Object[][] { {""}, @@ -778,46 +787,47 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="parseFailure", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("data_parseFailure") public void factory_parseFailures(String text) { - Duration.parse(text); + Assertions.assertThrows(DateTimeParseException.class, () -> Duration.parse(text)); } - @Test(dataProvider="parseFailure", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("data_parseFailure") public void factory_parseFailures_comma(String text) { - text = text.replace('.', ','); - Duration.parse(text); + var commaText = text.replace('.', ','); + Assertions.assertThrows(DateTimeParseException.class, () -> Duration.parse(commaText)); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_tooBig() { - Duration.parse("PT" + Long.MAX_VALUE + "1S"); + Assertions.assertThrows(DateTimeParseException.class, () -> Duration.parse("PT" + Long.MAX_VALUE + "1S")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_tooBig_decimal() { - Duration.parse("PT" + Long.MAX_VALUE + "1.1S"); + Assertions.assertThrows(DateTimeParseException.class, () -> Duration.parse("PT" + Long.MAX_VALUE + "1.1S")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_tooSmall() { - Duration.parse("PT" + Long.MIN_VALUE + "1S"); + Assertions.assertThrows(DateTimeParseException.class, () -> Duration.parse("PT" + Long.MIN_VALUE + "1S")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_tooSmall_decimal() { - Duration.parse("PT" + Long.MIN_VALUE + ".1S"); + Assertions.assertThrows(DateTimeParseException.class, () -> Duration.parse("PT" + Long.MIN_VALUE + ".1S")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_nullText() { - Duration.parse(null); + Assertions.assertThrows(NullPointerException.class, () -> Duration.parse(null)); } //----------------------------------------------------------------------- // between() //----------------------------------------------------------------------- - @DataProvider(name="durationBetweenInstant") Object[][] data_durationBetweenInstant() { return new Object[][] { {0, 0, 0, 0, 0, 0}, @@ -832,23 +842,24 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="durationBetweenInstant") + @ParameterizedTest + @MethodSource("data_durationBetweenInstant") public void factory_between_TemporalTemporal_Instant(long secs1, int nanos1, long secs2, int nanos2, long expectedSeconds, int expectedNanoOfSecond) { Instant start = Instant.ofEpochSecond(secs1, nanos1); Instant end = Instant.ofEpochSecond(secs2, nanos2); Duration t = Duration.between(start, end); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(dataProvider="durationBetweenInstant") + @ParameterizedTest + @MethodSource("data_durationBetweenInstant") public void factory_between_TemporalTemporal_Instant_negated(long secs1, int nanos1, long secs2, int nanos2, long expectedSeconds, int expectedNanoOfSecond) { Instant start = Instant.ofEpochSecond(secs1, nanos1); Instant end = Instant.ofEpochSecond(secs2, nanos2); - assertEquals(Duration.between(end, start), Duration.between(start, end).negated()); + assertEquals(Duration.between(start, end).negated(), Duration.between(end, start)); } - @DataProvider(name="durationBetweenLocalTime") Object[][] data_durationBetweenLocalTime() { return new Object[][] { {LocalTime.of(11, 0, 30), LocalTime.of(11, 0, 45), 15L, 0}, @@ -856,19 +867,20 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="durationBetweenLocalTime") + @ParameterizedTest + @MethodSource("data_durationBetweenLocalTime") public void factory_between_TemporalTemporal_LT(LocalTime start, LocalTime end, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.between(start, end); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(dataProvider="durationBetweenLocalTime") + @ParameterizedTest + @MethodSource("data_durationBetweenLocalTime") public void factory_between_TemporalTemporal_LT_negated(LocalTime start, LocalTime end, long expectedSeconds, int expectedNanoOfSecond) { - assertEquals(Duration.between(end, start), Duration.between(start, end).negated()); + assertEquals(Duration.between(start, end).negated(), Duration.between(end, start)); } - @DataProvider(name="durationBetweenLocalDateTime") Object[][] data_durationBetweenLocalDateTime() { return new Object[][] { {LocalDateTime.of(2013, 3, 24, 0, 44, 31, 565_000_000), LocalDateTime.of(2013, 3, 24, 0, 44, 30, 65_000_000), -2L, 500_000_000}, @@ -895,42 +907,50 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="durationBetweenLocalDateTime") + @ParameterizedTest + @MethodSource("data_durationBetweenLocalDateTime") public void factory_between_TemporalTemporal_LDT(LocalDateTime start, LocalDateTime end, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.between(start, end); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(dataProvider="durationBetweenLocalDateTime") + @ParameterizedTest + @MethodSource("data_durationBetweenLocalDateTime") public void factory_between_TemporalTemporal_LDT_negated(LocalDateTime start, LocalDateTime end, long expectedSeconds, int expectedNanoOfSecond) { - assertEquals(Duration.between(end, start), Duration.between(start, end).negated()); + assertEquals(Duration.between(start, end).negated(), Duration.between(end, start)); } @Test public void factory_between_TemporalTemporal_mixedTypes() { Instant start = Instant.ofEpochSecond(1); ZonedDateTime end = Instant.ofEpochSecond(4).atZone(ZoneOffset.UTC); - assertEquals(Duration.between(start, end), Duration.ofSeconds(3)); + assertEquals(Duration.ofSeconds(3), Duration.between(start, end)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_between_TemporalTemporal_invalidMixedTypes() { - Instant start = Instant.ofEpochSecond(1); - LocalDate end = LocalDate.of(2010, 6, 20); - Duration.between(start, end); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant start = Instant.ofEpochSecond(1); + LocalDate end = LocalDate.of(2010, 6, 20); + Duration.between(start, end); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_between__TemporalTemporal_startNull() { - Instant end = Instant.ofEpochSecond(1); - Duration.between(null, end); + Assertions.assertThrows(NullPointerException.class, () -> { + Instant end = Instant.ofEpochSecond(1); + Duration.between(null, end); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_between__TemporalTemporal_endNull() { - Instant start = Instant.ofEpochSecond(1); - Duration.between(start, null); + Assertions.assertThrows(NullPointerException.class, () -> { + Instant start = Instant.ofEpochSecond(1); + Duration.between(start, null); + }); } //----------------------------------------------------------------------- @@ -938,48 +958,47 @@ public class TCKDuration extends AbstractTCKTest { //----------------------------------------------------------------------- @Test public void test_isZero() { - assertEquals(Duration.ofNanos(0).isZero(), true); - assertEquals(Duration.ofSeconds(0).isZero(), true); - assertEquals(Duration.ofNanos(1).isZero(), false); - assertEquals(Duration.ofSeconds(1).isZero(), false); - assertEquals(Duration.ofSeconds(1, 1).isZero(), false); - assertEquals(Duration.ofNanos(-1).isZero(), false); - assertEquals(Duration.ofSeconds(-1).isZero(), false); - assertEquals(Duration.ofSeconds(-1, -1).isZero(), false); + assertEquals(true, Duration.ofNanos(0).isZero()); + assertEquals(true, Duration.ofSeconds(0).isZero()); + assertEquals(false, Duration.ofNanos(1).isZero()); + assertEquals(false, Duration.ofSeconds(1).isZero()); + assertEquals(false, Duration.ofSeconds(1, 1).isZero()); + assertEquals(false, Duration.ofNanos(-1).isZero()); + assertEquals(false, Duration.ofSeconds(-1).isZero()); + assertEquals(false, Duration.ofSeconds(-1, -1).isZero()); } @Test public void test_isPositive() { - assertEquals(Duration.ofNanos(0).isPositive(), false); - assertEquals(Duration.ofSeconds(0).isPositive(), false); - assertEquals(Duration.ofNanos(1).isPositive(), true); - assertEquals(Duration.ofSeconds(1).isPositive(), true); - assertEquals(Duration.ofSeconds(1, 1).isPositive(), true); - assertEquals(Duration.ofSeconds(Long.MAX_VALUE, 999_999_999).isPositive(), true); - assertEquals(Duration.ofNanos(-1).isPositive(), false); - assertEquals(Duration.ofSeconds(-1).isPositive(), false); - assertEquals(Duration.ofSeconds(-1, -1).isPositive(), false); - assertEquals(Duration.ofSeconds(Long.MIN_VALUE).isPositive(), false); + assertEquals(false, Duration.ofNanos(0).isPositive()); + assertEquals(false, Duration.ofSeconds(0).isPositive()); + assertEquals(true, Duration.ofNanos(1).isPositive()); + assertEquals(true, Duration.ofSeconds(1).isPositive()); + assertEquals(true, Duration.ofSeconds(1, 1).isPositive()); + assertEquals(true, Duration.ofSeconds(Long.MAX_VALUE, 999_999_999).isPositive()); + assertEquals(false, Duration.ofNanos(-1).isPositive()); + assertEquals(false, Duration.ofSeconds(-1).isPositive()); + assertEquals(false, Duration.ofSeconds(-1, -1).isPositive()); + assertEquals(false, Duration.ofSeconds(Long.MIN_VALUE).isPositive()); } @Test public void test_isNegative() { - assertEquals(Duration.ofNanos(0).isNegative(), false); - assertEquals(Duration.ofSeconds(0).isNegative(), false); - assertEquals(Duration.ofNanos(1).isNegative(), false); - assertEquals(Duration.ofSeconds(1).isNegative(), false); - assertEquals(Duration.ofSeconds(1, 1).isNegative(), false); - assertEquals(Duration.ofSeconds(Long.MAX_VALUE, 999_999_999).isNegative(), false); - assertEquals(Duration.ofNanos(-1).isNegative(), true); - assertEquals(Duration.ofSeconds(-1).isNegative(), true); - assertEquals(Duration.ofSeconds(-1, -1).isNegative(), true); - assertEquals(Duration.ofSeconds(Long.MIN_VALUE).isNegative(), true); + assertEquals(false, Duration.ofNanos(0).isNegative()); + assertEquals(false, Duration.ofSeconds(0).isNegative()); + assertEquals(false, Duration.ofNanos(1).isNegative()); + assertEquals(false, Duration.ofSeconds(1).isNegative()); + assertEquals(false, Duration.ofSeconds(1, 1).isNegative()); + assertEquals(false, Duration.ofSeconds(Long.MAX_VALUE, 999_999_999).isNegative()); + assertEquals(true, Duration.ofNanos(-1).isNegative()); + assertEquals(true, Duration.ofSeconds(-1).isNegative()); + assertEquals(true, Duration.ofSeconds(-1, -1).isNegative()); + assertEquals(true, Duration.ofSeconds(Long.MIN_VALUE).isNegative()); } //----------------------------------------------------------------------- // plus() //----------------------------------------------------------------------- - @DataProvider(name="Plus") Object[][] provider_plus() { return new Object[][] { {Long.MIN_VALUE, 0, Long.MAX_VALUE, 0, -1, 0}, @@ -1164,23 +1183,28 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="Plus") + @ParameterizedTest + @MethodSource("provider_plus") public void plus(long seconds, int nanos, long otherSeconds, int otherNanos, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos).plus(Duration.ofSeconds(otherSeconds, otherNanos)); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void plusOverflowTooBig() { - Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999999999); - t.plus(Duration.ofSeconds(0, 1)); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999999999); + t.plus(Duration.ofSeconds(0, 1)); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void plusOverflowTooSmall() { - Duration t = Duration.ofSeconds(Long.MIN_VALUE); - t.plus(Duration.ofSeconds(-1, 999999999)); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MIN_VALUE); + t.plus(Duration.ofSeconds(-1, 999999999)); + }); } //----------------------------------------------------------------------- @@ -1216,14 +1240,15 @@ public class TCKDuration extends AbstractTCKTest { assertEquals(1, t.getNano()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void plus_longTemporalUnit_null() { - Duration t = Duration.ofSeconds(1); - t.plus(1, (TemporalUnit) null); + Assertions.assertThrows(NullPointerException.class, () -> { + Duration t = Duration.ofSeconds(1); + t.plus(1, (TemporalUnit) null); + }); } //----------------------------------------------------------------------- - @DataProvider(name="PlusDays") Object[][] provider_plusDays_long() { return new Object[][] { {0, 0, 0}, @@ -1245,27 +1270,31 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="PlusDays") + @ParameterizedTest + @MethodSource("provider_plusDays_long") public void plusDays_long(long days, long amount, long expectedDays) { Duration t = Duration.ofDays(days); t = t.plusDays(amount); - assertEquals(t.toDays(), expectedDays); + assertEquals(expectedDays, t.toDays()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusDays_long_overflowTooBig() { - Duration t = Duration.ofDays(1); - t.plusDays(Long.MAX_VALUE/3600/24); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofDays(1); + t.plusDays(Long.MAX_VALUE/3600/24); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusDays_long_overflowTooSmall() { - Duration t = Duration.ofDays(-1); - t.plusDays(Long.MIN_VALUE/3600/24); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofDays(-1); + t.plusDays(Long.MIN_VALUE/3600/24); + }); } //----------------------------------------------------------------------- - @DataProvider(name="PlusHours") Object[][] provider_plusHours_long() { return new Object[][] { {0, 0, 0}, @@ -1287,27 +1316,31 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="PlusHours") + @ParameterizedTest + @MethodSource("provider_plusHours_long") public void plusHours_long(long hours, long amount, long expectedHours) { Duration t = Duration.ofHours(hours); t = t.plusHours(amount); - assertEquals(t.toHours(), expectedHours); + assertEquals(expectedHours, t.toHours()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusHours_long_overflowTooBig() { - Duration t = Duration.ofHours(1); - t.plusHours(Long.MAX_VALUE/3600); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofHours(1); + t.plusHours(Long.MAX_VALUE/3600); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusHours_long_overflowTooSmall() { - Duration t = Duration.ofHours(-1); - t.plusHours(Long.MIN_VALUE/3600); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofHours(-1); + t.plusHours(Long.MIN_VALUE/3600); + }); } //----------------------------------------------------------------------- - @DataProvider(name="PlusMinutes") Object[][] provider_plusMinutes_long() { return new Object[][] { {0, 0, 0}, @@ -1329,27 +1362,31 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="PlusMinutes") + @ParameterizedTest + @MethodSource("provider_plusMinutes_long") public void plusMinutes_long(long minutes, long amount, long expectedMinutes) { Duration t = Duration.ofMinutes(minutes); t = t.plusMinutes(amount); - assertEquals(t.toMinutes(), expectedMinutes); + assertEquals(expectedMinutes, t.toMinutes()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusMinutes_long_overflowTooBig() { - Duration t = Duration.ofMinutes(1); - t.plusMinutes(Long.MAX_VALUE/60); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofMinutes(1); + t.plusMinutes(Long.MAX_VALUE/60); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusMinutes_long_overflowTooSmall() { - Duration t = Duration.ofMinutes(-1); - t.plusMinutes(Long.MIN_VALUE/60); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofMinutes(-1); + t.plusMinutes(Long.MIN_VALUE/60); + }); } //----------------------------------------------------------------------- - @DataProvider(name="PlusSeconds") Object[][] provider_plusSeconds_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -1375,28 +1412,32 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="PlusSeconds") + @ParameterizedTest + @MethodSource("provider_plusSeconds_long") public void plusSeconds_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.plusSeconds(amount); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusSeconds_long_overflowTooBig() { - Duration t = Duration.ofSeconds(1, 0); - t.plusSeconds(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(1, 0); + t.plusSeconds(Long.MAX_VALUE); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusSeconds_long_overflowTooSmall() { - Duration t = Duration.ofSeconds(-1, 0); - t.plusSeconds(Long.MIN_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(-1, 0); + t.plusSeconds(Long.MIN_VALUE); + }); } //----------------------------------------------------------------------- - @DataProvider(name="PlusMillis") Object[][] provider_plusMillis_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -1451,58 +1492,64 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="PlusMillis") + @ParameterizedTest + @MethodSource("provider_plusMillis_long") public void plusMillis_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.plusMillis(amount); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(dataProvider="PlusMillis") + @ParameterizedTest + @MethodSource("provider_plusMillis_long") public void plusMillis_long_oneMore(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds + 1, nanos); t = t.plusMillis(amount); - assertEquals(t.getSeconds(), expectedSeconds + 1); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds + 1, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(dataProvider="PlusMillis") + @ParameterizedTest + @MethodSource("provider_plusMillis_long") public void plusMillis_long_minusOneLess(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds - 1, nanos); t = t.plusMillis(amount); - assertEquals(t.getSeconds(), expectedSeconds - 1); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds - 1, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } @Test public void plusMillis_long_max() { Duration t = Duration.ofSeconds(Long.MAX_VALUE, 998999999); t = t.plusMillis(1); - assertEquals(t.getSeconds(), Long.MAX_VALUE); - assertEquals(t.getNano(), 999999999); + assertEquals(Long.MAX_VALUE, t.getSeconds()); + assertEquals(999999999, t.getNano()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusMillis_long_overflowTooBig() { - Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999000000); - t.plusMillis(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999000000); + t.plusMillis(1); + }); } @Test public void plusMillis_long_min() { Duration t = Duration.ofSeconds(Long.MIN_VALUE, 1000000); t = t.plusMillis(-1); - assertEquals(t.getSeconds(), Long.MIN_VALUE); - assertEquals(t.getNano(), 0); + assertEquals(Long.MIN_VALUE, t.getSeconds()); + assertEquals(0, t.getNano()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusMillis_long_overflowTooSmall() { - Duration t = Duration.ofSeconds(Long.MIN_VALUE, 0); - t.plusMillis(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MIN_VALUE, 0); + t.plusMillis(-1); + }); } //----------------------------------------------------------------------- - @DataProvider(name="PlusNanos") Object[][] provider_plusNanos_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -1577,28 +1624,32 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="PlusNanos") + @ParameterizedTest + @MethodSource("provider_plusNanos_long") public void plusNanos_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.plusNanos(amount); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusNanos_long_overflowTooBig() { - Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999999999); - t.plusNanos(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999999999); + t.plusNanos(1); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void plusNanos_long_overflowTooSmall() { - Duration t = Duration.ofSeconds(Long.MIN_VALUE, 0); - t.plusNanos(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MIN_VALUE, 0); + t.plusNanos(-1); + }); } //----------------------------------------------------------------------- - @DataProvider(name="Minus") Object[][] provider_minus() { return new Object[][] { {Long.MIN_VALUE, 0, Long.MIN_VALUE + 1, 0, -1, 0}, @@ -1783,23 +1834,28 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="Minus") + @ParameterizedTest + @MethodSource("provider_minus") public void minus(long seconds, int nanos, long otherSeconds, int otherNanos, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos).minus(Duration.ofSeconds(otherSeconds, otherNanos)); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void minusOverflowTooSmall() { - Duration t = Duration.ofSeconds(Long.MIN_VALUE); - t.minus(Duration.ofSeconds(0, 1)); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MIN_VALUE); + t.minus(Duration.ofSeconds(0, 1)); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void minusOverflowTooBig() { - Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999999999); - t.minus(Duration.ofSeconds(-1, 999999999)); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999999999); + t.minus(Duration.ofSeconds(-1, 999999999)); + }); } //----------------------------------------------------------------------- @@ -1835,14 +1891,15 @@ public class TCKDuration extends AbstractTCKTest { assertEquals(999999999, t.getNano()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void minus_longTemporalUnit_null() { - Duration t = Duration.ofSeconds(1); - t.minus(1, (TemporalUnit) null); + Assertions.assertThrows(NullPointerException.class, () -> { + Duration t = Duration.ofSeconds(1); + t.minus(1, (TemporalUnit) null); + }); } //----------------------------------------------------------------------- - @DataProvider(name="MinusDays") Object[][] provider_minusDays_long() { return new Object[][] { {0, 0, 0}, @@ -1864,27 +1921,31 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="MinusDays") + @ParameterizedTest + @MethodSource("provider_minusDays_long") public void minusDays_long(long days, long amount, long expectedDays) { Duration t = Duration.ofDays(days); t = t.minusDays(amount); - assertEquals(t.toDays(), expectedDays); + assertEquals(expectedDays, t.toDays()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusDays_long_overflowTooBig() { - Duration t = Duration.ofDays(Long.MAX_VALUE/3600/24); - t.minusDays(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofDays(Long.MAX_VALUE/3600/24); + t.minusDays(-1); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusDays_long_overflowTooSmall() { - Duration t = Duration.ofDays(Long.MIN_VALUE/3600/24); - t.minusDays(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofDays(Long.MIN_VALUE/3600/24); + t.minusDays(1); + }); } //----------------------------------------------------------------------- - @DataProvider(name="MinusHours") Object[][] provider_minusHours_long() { return new Object[][] { {0, 0, 0}, @@ -1906,27 +1967,31 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="MinusHours") + @ParameterizedTest + @MethodSource("provider_minusHours_long") public void minusHours_long(long hours, long amount, long expectedHours) { Duration t = Duration.ofHours(hours); t = t.minusHours(amount); - assertEquals(t.toHours(), expectedHours); + assertEquals(expectedHours, t.toHours()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusHours_long_overflowTooBig() { - Duration t = Duration.ofHours(Long.MAX_VALUE/3600); - t.minusHours(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofHours(Long.MAX_VALUE/3600); + t.minusHours(-1); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusHours_long_overflowTooSmall() { - Duration t = Duration.ofHours(Long.MIN_VALUE/3600); - t.minusHours(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofHours(Long.MIN_VALUE/3600); + t.minusHours(1); + }); } //----------------------------------------------------------------------- - @DataProvider(name="MinusMinutes") Object[][] provider_minusminutes_long() { return new Object[][] { {0, 0, 0}, @@ -1948,27 +2013,31 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="MinusMinutes") + @ParameterizedTest + @MethodSource("provider_minusminutes_long") public void minusMinutes_long(long minutes, long amount, long expectedMinutes) { Duration t = Duration.ofMinutes(minutes); t = t.minusMinutes(amount); - assertEquals(t.toMinutes(), expectedMinutes); + assertEquals(expectedMinutes, t.toMinutes()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusMinutes_long_overflowTooBig() { - Duration t = Duration.ofMinutes(Long.MAX_VALUE/60); - t.minusMinutes(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofMinutes(Long.MAX_VALUE/60); + t.minusMinutes(-1); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusMinutes_long_overflowTooSmall() { - Duration t = Duration.ofMinutes(Long.MIN_VALUE/60); - t.minusMinutes(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofMinutes(Long.MIN_VALUE/60); + t.minusMinutes(1); + }); } //----------------------------------------------------------------------- - @DataProvider(name="MinusSeconds") Object[][] provider_minusSeconds_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -1994,28 +2063,32 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="MinusSeconds") + @ParameterizedTest + @MethodSource("provider_minusSeconds_long") public void minusSeconds_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.minusSeconds(amount); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusSeconds_long_overflowTooBig() { - Duration t = Duration.ofSeconds(1, 0); - t.minusSeconds(Long.MIN_VALUE + 1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(1, 0); + t.minusSeconds(Long.MIN_VALUE + 1); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusSeconds_long_overflowTooSmall() { - Duration t = Duration.ofSeconds(-2, 0); - t.minusSeconds(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(-2, 0); + t.minusSeconds(Long.MAX_VALUE); + }); } //----------------------------------------------------------------------- - @DataProvider(name="MinusMillis") Object[][] provider_minusMillis_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -2070,58 +2143,64 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="MinusMillis") + @ParameterizedTest + @MethodSource("provider_minusMillis_long") public void minusMillis_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.minusMillis(amount); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(dataProvider="MinusMillis") + @ParameterizedTest + @MethodSource("provider_minusMillis_long") public void minusMillis_long_oneMore(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds + 1, nanos); t = t.minusMillis(amount); - assertEquals(t.getSeconds(), expectedSeconds + 1); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds + 1, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(dataProvider="MinusMillis") + @ParameterizedTest + @MethodSource("provider_minusMillis_long") public void minusMillis_long_minusOneLess(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds - 1, nanos); t = t.minusMillis(amount); - assertEquals(t.getSeconds(), expectedSeconds - 1); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds - 1, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } @Test public void minusMillis_long_max() { Duration t = Duration.ofSeconds(Long.MAX_VALUE, 998999999); t = t.minusMillis(-1); - assertEquals(t.getSeconds(), Long.MAX_VALUE); - assertEquals(t.getNano(), 999999999); + assertEquals(Long.MAX_VALUE, t.getSeconds()); + assertEquals(999999999, t.getNano()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusMillis_long_overflowTooBig() { - Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999000000); - t.minusMillis(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999000000); + t.minusMillis(-1); + }); } @Test public void minusMillis_long_min() { Duration t = Duration.ofSeconds(Long.MIN_VALUE, 1000000); t = t.minusMillis(1); - assertEquals(t.getSeconds(), Long.MIN_VALUE); - assertEquals(t.getNano(), 0); + assertEquals(Long.MIN_VALUE, t.getSeconds()); + assertEquals(0, t.getNano()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusMillis_long_overflowTooSmall() { - Duration t = Duration.ofSeconds(Long.MIN_VALUE, 0); - t.minusMillis(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MIN_VALUE, 0); + t.minusMillis(1); + }); } //----------------------------------------------------------------------- - @DataProvider(name="MinusNanos") Object[][] provider_minusNanos_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -2196,30 +2275,34 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="MinusNanos") + @ParameterizedTest + @MethodSource("provider_minusNanos_long") public void minusNanos_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.minusNanos(amount); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusNanos_long_overflowTooBig() { - Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999999999); - t.minusNanos(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MAX_VALUE, 999999999); + t.minusNanos(-1); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusNanos_long_overflowTooSmall() { - Duration t = Duration.ofSeconds(Long.MIN_VALUE, 0); - t.minusNanos(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(Long.MIN_VALUE, 0); + t.minusNanos(1); + }); } //----------------------------------------------------------------------- // multipliedBy() //----------------------------------------------------------------------- - @DataProvider(name="MultipliedBy") Object[][] provider_multipliedBy() { return new Object[][] { {-4, 666666667, -3, 9, 999999999}, @@ -2312,36 +2395,41 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="MultipliedBy") + @ParameterizedTest + @MethodSource("provider_multipliedBy") public void multipliedBy(long seconds, int nanos, int multiplicand, long expectedSeconds, int expectedNanos) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.multipliedBy(multiplicand); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanos); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanos, t.getNano()); } @Test public void multipliedBy_max() { Duration test = Duration.ofSeconds(1); - assertEquals(test.multipliedBy(Long.MAX_VALUE), Duration.ofSeconds(Long.MAX_VALUE)); + assertEquals(Duration.ofSeconds(Long.MAX_VALUE), test.multipliedBy(Long.MAX_VALUE)); } @Test public void multipliedBy_min() { Duration test = Duration.ofSeconds(1); - assertEquals(test.multipliedBy(Long.MIN_VALUE), Duration.ofSeconds(Long.MIN_VALUE)); + assertEquals(Duration.ofSeconds(Long.MIN_VALUE), test.multipliedBy(Long.MIN_VALUE)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void multipliedBy_tooBig() { - Duration test = Duration.ofSeconds(1, 1); - test.multipliedBy(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration test = Duration.ofSeconds(1, 1); + test.multipliedBy(Long.MAX_VALUE); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void multipliedBy_tooBig_negative() { - Duration test = Duration.ofSeconds(1, 1); - test.multipliedBy(Long.MIN_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration test = Duration.ofSeconds(1, 1); + test.multipliedBy(Long.MIN_VALUE); + }); } //----------------------------------------------------------------------- @@ -2417,7 +2505,6 @@ public class TCKDuration extends AbstractTCKTest { } }; - @DataProvider(name="truncatedToValid") Object[][] data_truncatedToValid() { return new Object[][] { {Duration.ofSeconds(86400 + 3600 + 60 + 1, 123_456_789), NANOS, Duration.ofSeconds(86400 + 3600 + 60 + 1, 123_456_789)}, @@ -2446,12 +2533,12 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="truncatedToValid") + @ParameterizedTest + @MethodSource("data_truncatedToValid") public void test_truncatedTo_valid(Duration input, TemporalUnit unit, Duration expected) { - assertEquals(input.truncatedTo(unit), expected); + assertEquals(expected, input.truncatedTo(unit)); } - @DataProvider(name="truncatedToInvalid") Object[][] data_truncatedToInvalid() { return new Object[][] { {Duration.ofSeconds(1, 123_456_789), NINETY_FIVE_MINS}, @@ -2461,20 +2548,20 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="truncatedToInvalid", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_truncatedToInvalid") public void test_truncatedTo_invalid(Duration input, TemporalUnit unit) { - input.truncatedTo(unit); + Assertions.assertThrows(DateTimeException.class, () -> input.truncatedTo(unit)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_truncatedTo_null() { - Duration.ofSeconds(1234).truncatedTo(null); + Assertions.assertThrows(NullPointerException.class, () -> Duration.ofSeconds(1234).truncatedTo(null)); } //----------------------------------------------------------------------- // dividedBy() //----------------------------------------------------------------------- - @DataProvider(name="DividedBy") Object[][] provider_dividedBy() { return new Object[][] { {-4, 666666667, -3, 1, 111111111}, @@ -2556,32 +2643,35 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="DividedBy") + @ParameterizedTest + @MethodSource("provider_dividedBy") public void dividedBy(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.dividedBy(divisor); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanos); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanos, t.getNano()); } - @Test(dataProvider="DividedBy", expectedExceptions=ArithmeticException.class) + @ParameterizedTest + @MethodSource("provider_dividedBy") public void dividedByZero(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) { - Duration t = Duration.ofSeconds(seconds, nanos); - t.dividedBy(0); - fail(t + " divided by zero did not throw ArithmeticException"); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(seconds, nanos); + t.dividedBy(0); + fail(t + " divided by zero did not throw ArithmeticException"); + }); } @Test public void dividedBy_max() { Duration test = Duration.ofSeconds(Long.MAX_VALUE); - assertEquals(test.dividedBy(Long.MAX_VALUE), Duration.ofSeconds(1)); + assertEquals(Duration.ofSeconds(1), test.dividedBy(Long.MAX_VALUE)); } //----------------------------------------------------------------------- // dividedbyDur() //----------------------------------------------------------------------- - @DataProvider(name="dividedByDur_provider") Object[][] provider_dividedByDur() { return new Object[][] { {Duration.ofSeconds(0, 0), Duration.ofSeconds(1, 0), 0}, @@ -2612,28 +2702,35 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="dividedByDur_provider") + @ParameterizedTest + @MethodSource("provider_dividedByDur") public void test_dividedByDur(Duration dividend, Duration divisor, long expected) { - assertEquals(dividend.dividedBy(divisor), expected); + assertEquals(expected, dividend.dividedBy(divisor)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_dividedByDur_zero() { - Duration t = Duration.ofSeconds(1, 0); - t.dividedBy(Duration.ZERO); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration t = Duration.ofSeconds(1, 0); + t.dividedBy(Duration.ZERO); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_dividedByDur_null() { - Duration t = Duration.ofSeconds(1, 0); - t.dividedBy(null); + Assertions.assertThrows(NullPointerException.class, () -> { + Duration t = Duration.ofSeconds(1, 0); + t.dividedBy(null); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_dividedByDur_overflow() { - Duration dur1 = Duration.ofSeconds(Long.MAX_VALUE, 0); - Duration dur2 = Duration.ofNanos(1); - dur1.dividedBy(dur2); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration dur1 = Duration.ofSeconds(Long.MAX_VALUE, 0); + Duration dur2 = Duration.ofNanos(1); + dur1.dividedBy(dur2); + }); } //----------------------------------------------------------------------- @@ -2641,19 +2738,19 @@ public class TCKDuration extends AbstractTCKTest { //----------------------------------------------------------------------- @Test public void test_negated() { - assertEquals(Duration.ofSeconds(0).negated(), Duration.ofSeconds(0)); - assertEquals(Duration.ofSeconds(12).negated(), Duration.ofSeconds(-12)); - assertEquals(Duration.ofSeconds(-12).negated(), Duration.ofSeconds(12)); - assertEquals(Duration.ofSeconds(12, 20).negated(), Duration.ofSeconds(-12, -20)); - assertEquals(Duration.ofSeconds(12, -20).negated(), Duration.ofSeconds(-12, 20)); - assertEquals(Duration.ofSeconds(-12, -20).negated(), Duration.ofSeconds(12, 20)); - assertEquals(Duration.ofSeconds(-12, 20).negated(), Duration.ofSeconds(12, -20)); - assertEquals(Duration.ofSeconds(Long.MAX_VALUE).negated(), Duration.ofSeconds(-Long.MAX_VALUE)); + assertEquals(Duration.ofSeconds(0), Duration.ofSeconds(0).negated()); + assertEquals(Duration.ofSeconds(-12), Duration.ofSeconds(12).negated()); + assertEquals(Duration.ofSeconds(12), Duration.ofSeconds(-12).negated()); + assertEquals(Duration.ofSeconds(-12, -20), Duration.ofSeconds(12, 20).negated()); + assertEquals(Duration.ofSeconds(-12, 20), Duration.ofSeconds(12, -20).negated()); + assertEquals(Duration.ofSeconds(12, 20), Duration.ofSeconds(-12, -20).negated()); + assertEquals(Duration.ofSeconds(12, -20), Duration.ofSeconds(-12, 20).negated()); + assertEquals(Duration.ofSeconds(-Long.MAX_VALUE), Duration.ofSeconds(Long.MAX_VALUE).negated()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_negated_overflow() { - Duration.ofSeconds(Long.MIN_VALUE).negated(); + Assertions.assertThrows(ArithmeticException.class, () -> Duration.ofSeconds(Long.MIN_VALUE).negated()); } //----------------------------------------------------------------------- @@ -2661,19 +2758,19 @@ public class TCKDuration extends AbstractTCKTest { //----------------------------------------------------------------------- @Test public void test_abs() { - assertEquals(Duration.ofSeconds(0).abs(), Duration.ofSeconds(0)); - assertEquals(Duration.ofSeconds(12).abs(), Duration.ofSeconds(12)); - assertEquals(Duration.ofSeconds(-12).abs(), Duration.ofSeconds(12)); - assertEquals(Duration.ofSeconds(12, 20).abs(), Duration.ofSeconds(12, 20)); - assertEquals(Duration.ofSeconds(12, -20).abs(), Duration.ofSeconds(12, -20)); - assertEquals(Duration.ofSeconds(-12, -20).abs(), Duration.ofSeconds(12, 20)); - assertEquals(Duration.ofSeconds(-12, 20).abs(), Duration.ofSeconds(12, -20)); - assertEquals(Duration.ofSeconds(Long.MAX_VALUE).abs(), Duration.ofSeconds(Long.MAX_VALUE)); + assertEquals(Duration.ofSeconds(0), Duration.ofSeconds(0).abs()); + assertEquals(Duration.ofSeconds(12), Duration.ofSeconds(12).abs()); + assertEquals(Duration.ofSeconds(12), Duration.ofSeconds(-12).abs()); + assertEquals(Duration.ofSeconds(12, 20), Duration.ofSeconds(12, 20).abs()); + assertEquals(Duration.ofSeconds(12, -20), Duration.ofSeconds(12, -20).abs()); + assertEquals(Duration.ofSeconds(12, 20), Duration.ofSeconds(-12, -20).abs()); + assertEquals(Duration.ofSeconds(12, -20), Duration.ofSeconds(-12, 20).abs()); + assertEquals(Duration.ofSeconds(Long.MAX_VALUE), Duration.ofSeconds(Long.MAX_VALUE).abs()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_abs_overflow() { - Duration.ofSeconds(Long.MIN_VALUE).abs(); + Assertions.assertThrows(ArithmeticException.class, () -> Duration.ofSeconds(Long.MIN_VALUE).abs()); } //----------------------------------------------------------------------- @@ -2681,33 +2778,37 @@ public class TCKDuration extends AbstractTCKTest { //----------------------------------------------------------------------- @Test public void test_toNanos() { - assertEquals(Duration.ofSeconds(321, 123456789).toNanos(), 321123456789L); - assertEquals(Duration.ofNanos(Long.MAX_VALUE).toNanos(), 9223372036854775807L); - assertEquals(Duration.ofNanos(Long.MIN_VALUE).toNanos(), -9223372036854775808L); + assertEquals(321123456789L, Duration.ofSeconds(321, 123456789).toNanos()); + assertEquals(9223372036854775807L, Duration.ofNanos(Long.MAX_VALUE).toNanos()); + assertEquals(-9223372036854775808L, Duration.ofNanos(Long.MIN_VALUE).toNanos()); } @Test public void test_toNanos_max() { Duration test = Duration.ofSeconds(0, Long.MAX_VALUE); - assertEquals(test.toNanos(), Long.MAX_VALUE); + assertEquals(Long.MAX_VALUE, test.toNanos()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_toNanos_tooBig() { - Duration test = Duration.ofSeconds(0, Long.MAX_VALUE).plusNanos(1); - test.toNanos(); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration test = Duration.ofSeconds(0, Long.MAX_VALUE).plusNanos(1); + test.toNanos(); + }); } @Test public void test_toNanos_min() { Duration test = Duration.ofSeconds(0, Long.MIN_VALUE); - assertEquals(test.toNanos(), Long.MIN_VALUE); + assertEquals(Long.MIN_VALUE, test.toNanos()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_toNanos_tooSmall() { - Duration test = Duration.ofSeconds(0, Long.MIN_VALUE).minusNanos(1); - test.toNanos(); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration test = Duration.ofSeconds(0, Long.MIN_VALUE).minusNanos(1); + test.toNanos(); + }); } //----------------------------------------------------------------------- @@ -2715,39 +2816,42 @@ public class TCKDuration extends AbstractTCKTest { //----------------------------------------------------------------------- @Test public void test_toMillis() { - assertEquals(Duration.ofSeconds(321, 123456789).toMillis(), 321000 + 123); - assertEquals(Duration.ofMillis(Long.MAX_VALUE).toMillis(), 9223372036854775807L); - assertEquals(Duration.ofMillis(Long.MIN_VALUE).toMillis(), -9223372036854775808L); + assertEquals(321000 + 123, Duration.ofSeconds(321, 123456789).toMillis()); + assertEquals(9223372036854775807L, Duration.ofMillis(Long.MAX_VALUE).toMillis()); + assertEquals(-9223372036854775808L, Duration.ofMillis(Long.MIN_VALUE).toMillis()); } @Test public void test_toMillis_max() { Duration test = Duration.ofSeconds(Long.MAX_VALUE / 1000, (Long.MAX_VALUE % 1000) * 1000000); - assertEquals(test.toMillis(), Long.MAX_VALUE); + assertEquals(Long.MAX_VALUE, test.toMillis()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_toMillis_tooBig() { - Duration test = Duration.ofSeconds(Long.MAX_VALUE / 1000, ((Long.MAX_VALUE % 1000) + 1) * 1000000); - test.toMillis(); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration test = Duration.ofSeconds(Long.MAX_VALUE / 1000, ((Long.MAX_VALUE % 1000) + 1) * 1000000); + test.toMillis(); + }); } @Test public void test_toMillis_min() { Duration test = Duration.ofSeconds(Long.MIN_VALUE / 1000, (Long.MIN_VALUE % 1000) * 1000000); - assertEquals(test.toMillis(), Long.MIN_VALUE); + assertEquals(Long.MIN_VALUE, test.toMillis()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_toMillis_tooSmall() { - Duration test = Duration.ofSeconds(Long.MIN_VALUE / 1000, ((Long.MIN_VALUE % 1000) - 1) * 1000000); - test.toMillis(); + Assertions.assertThrows(ArithmeticException.class, () -> { + Duration test = Duration.ofSeconds(Long.MIN_VALUE / 1000, ((Long.MIN_VALUE % 1000) - 1) * 1000000); + test.toMillis(); + }); } //----------------------------------------------------------------------- // toSeconds() //----------------------------------------------------------------------- - @DataProvider(name="toSeconds_provider") Object[][] provider_toSeconds() { return new Object[][] { {Duration.ofSeconds(365 * 86400 + 5 * 3600 + 48 * 60 + 46, 123_456_789), 31556926L}, @@ -2761,15 +2865,15 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="toSeconds_provider") + @ParameterizedTest + @MethodSource("provider_toSeconds") public void test_toSeconds(Duration dur, long seconds) { - assertEquals(dur.toSeconds(), seconds); + assertEquals(seconds, dur.toSeconds()); } //----------------------------------------------------------------------- // toDaysPart() //----------------------------------------------------------------------- - @DataProvider(name="toDaysPart_provider") Object[][] provider_toDaysPart() { return new Object[][] { {Duration.ofSeconds(365 * 86400 + 5 * 3600 + 48 * 60 + 46, 123_456_789), 365L}, @@ -2781,15 +2885,15 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="toDaysPart_provider") + @ParameterizedTest + @MethodSource("provider_toDaysPart") public void test_toDaysPart(Duration dur, long days) { - assertEquals(dur.toDaysPart(), days); + assertEquals(days, dur.toDaysPart()); } //----------------------------------------------------------------------- // toHoursPart() //----------------------------------------------------------------------- - @DataProvider(name="toHoursPart_provider") Object[][] provider_toHoursPart() { return new Object[][] { {Duration.ofSeconds(365 * 86400 + 5 * 3600 + 48 * 60 + 46, 123_456_789), 5}, @@ -2800,15 +2904,15 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="toHoursPart_provider") + @ParameterizedTest + @MethodSource("provider_toHoursPart") public void test_toHoursPart(Duration dur, int hours) { - assertEquals(dur.toHoursPart(), hours); + assertEquals(hours, dur.toHoursPart()); } //----------------------------------------------------------------------- // toMinutesPart() //----------------------------------------------------------------------- - @DataProvider(name="toMinutesPart_provider") Object[][] provider_toMinutesPart() { return new Object[][] { {Duration.ofSeconds(365 * 86400 + 5 * 3600 + 48 * 60 + 46, 123_456_789), 48}, @@ -2820,15 +2924,15 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="toMinutesPart_provider") + @ParameterizedTest + @MethodSource("provider_toMinutesPart") public void test_toMinutesPart(Duration dur, int minutes) { - assertEquals(dur.toMinutesPart(), minutes); + assertEquals(minutes, dur.toMinutesPart()); } //----------------------------------------------------------------------- // toSecondsPart() //----------------------------------------------------------------------- - @DataProvider(name="toSecondsPart_provider") Object[][] provider_toSecondsPart() { return new Object[][] { {Duration.ofSeconds(365 * 86400 + 5 * 3600 + 48 * 60 + 46, 123_456_789), 46}, @@ -2840,15 +2944,15 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="toSecondsPart_provider") + @ParameterizedTest + @MethodSource("provider_toSecondsPart") public void test_toSecondsPart(Duration dur, int seconds) { - assertEquals(dur.toSecondsPart(), seconds); + assertEquals(seconds, dur.toSecondsPart()); } //----------------------------------------------------------------------- // toMillisPart() //----------------------------------------------------------------------- - @DataProvider(name="toMillisPart_provider") Object[][] provider_toMillisPart() { return new Object[][] { {Duration.ofSeconds(365 * 86400 + 5 * 3600 + 48 * 60 + 46, 123_456_789), 123}, @@ -2860,15 +2964,15 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="toMillisPart_provider") + @ParameterizedTest + @MethodSource("provider_toMillisPart") public void test_toMillisPart(Duration dur, int millis) { - assertEquals(dur.toMillisPart(), millis); + assertEquals(millis, dur.toMillisPart()); } //----------------------------------------------------------------------- // toNanosPart() //----------------------------------------------------------------------- - @DataProvider(name="toNanosPart_provider") Object[][] provider_toNanosPart() { return new Object[][] { {Duration.ofSeconds(365 * 86400 + 5 * 3600 + 48 * 60 + 46, 123_456_789), 123_456_789}, @@ -2880,9 +2984,10 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="toNanosPart_provider") + @ParameterizedTest + @MethodSource("provider_toNanosPart") public void test_toNanosPart(Duration dur, int nanos) { - assertEquals(dur.toNanosPart(), nanos); + assertEquals(nanos, dur.toNanosPart()); } //----------------------------------------------------------------------- @@ -2913,30 +3018,34 @@ public class TCKDuration extends AbstractTCKTest { for (int j = 0; j < durations.length; j++) { Duration b = durations[j]; if (i < j) { - assertEquals(a.compareTo(b)< 0, true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.compareTo(b)< 0, a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { - assertEquals(a.compareTo(b) > 0, true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.compareTo(b) > 0, a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_ObjectNull() { - Duration a = Duration.ofSeconds(0L, 0); - a.compareTo(null); + Assertions.assertThrows(NullPointerException.class, () -> { + Duration a = Duration.ofSeconds(0L, 0); + a.compareTo(null); + }); } - @Test(expectedExceptions=ClassCastException.class) @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test public void compareToNonDuration() { - Comparable c = Duration.ofSeconds(0L); - c.compareTo(new Object()); + Assertions.assertThrows(ClassCastException.class, () -> { + Comparable c = Duration.ofSeconds(0L); + c.compareTo(new Object()); + }); } //----------------------------------------------------------------------- @@ -2949,37 +3058,37 @@ public class TCKDuration extends AbstractTCKTest { Duration test5n = Duration.ofSeconds(5L, 30); Duration test6 = Duration.ofSeconds(6L, 20); - assertEquals(test5a.equals(test5a), true); - assertEquals(test5a.equals(test5b), true); - assertEquals(test5a.equals(test5n), false); - assertEquals(test5a.equals(test6), false); + assertEquals(true, test5a.equals(test5a)); + assertEquals(true, test5a.equals(test5b)); + assertEquals(false, test5a.equals(test5n)); + assertEquals(false, test5a.equals(test6)); - assertEquals(test5b.equals(test5a), true); - assertEquals(test5b.equals(test5b), true); - assertEquals(test5b.equals(test5n), false); - assertEquals(test5b.equals(test6), false); + assertEquals(true, test5b.equals(test5a)); + assertEquals(true, test5b.equals(test5b)); + assertEquals(false, test5b.equals(test5n)); + assertEquals(false, test5b.equals(test6)); - assertEquals(test5n.equals(test5a), false); - assertEquals(test5n.equals(test5b), false); - assertEquals(test5n.equals(test5n), true); - assertEquals(test5n.equals(test6), false); + assertEquals(false, test5n.equals(test5a)); + assertEquals(false, test5n.equals(test5b)); + assertEquals(true, test5n.equals(test5n)); + assertEquals(false, test5n.equals(test6)); - assertEquals(test6.equals(test5a), false); - assertEquals(test6.equals(test5b), false); - assertEquals(test6.equals(test5n), false); - assertEquals(test6.equals(test6), true); + assertEquals(false, test6.equals(test5a)); + assertEquals(false, test6.equals(test5b)); + assertEquals(false, test6.equals(test5n)); + assertEquals(true, test6.equals(test6)); } @Test public void test_equals_null() { Duration test5 = Duration.ofSeconds(5L, 20); - assertEquals(test5.equals(null), false); + assertEquals(false, test5.equals(null)); } @Test public void test_equals_otherClass() { Duration test5 = Duration.ofSeconds(5L, 20); - assertEquals(test5.equals(""), false); + assertEquals(false, test5.equals("")); } //----------------------------------------------------------------------- @@ -2992,16 +3101,15 @@ public class TCKDuration extends AbstractTCKTest { Duration test5n = Duration.ofSeconds(5L, 30); Duration test6 = Duration.ofSeconds(6L, 20); - assertEquals(test5a.hashCode() == test5a.hashCode(), true); - assertEquals(test5a.hashCode() == test5b.hashCode(), true); - assertEquals(test5b.hashCode() == test5b.hashCode(), true); + assertEquals(true, test5a.hashCode() == test5a.hashCode()); + assertEquals(true, test5a.hashCode() == test5b.hashCode()); + assertEquals(true, test5b.hashCode() == test5b.hashCode()); - assertEquals(test5a.hashCode() == test5n.hashCode(), false); - assertEquals(test5a.hashCode() == test6.hashCode(), false); + assertEquals(false, test5a.hashCode() == test5n.hashCode()); + assertEquals(false, test5a.hashCode() == test6.hashCode()); } //----------------------------------------------------------------------- - @DataProvider(name="withNanos") Object[][] provider_withNanos_int() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -3025,16 +3133,16 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="withNanos") + @ParameterizedTest + @MethodSource("provider_withNanos_int") public void withNanos_long(long seconds, int nanos, int amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.withNanos(amount); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } //----------------------------------------------------------------------- - @DataProvider(name="withSeconds") Object[][] provider_withSeconds_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -3057,18 +3165,18 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="withSeconds") + @ParameterizedTest + @MethodSource("provider_withSeconds_long") public void withSeconds_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.withSeconds(amount); - assertEquals(t.getSeconds(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getSeconds()); + assertEquals(expectedNanoOfSecond, t.getNano()); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="toString") Object[][] provider_toString() { return new Object[][] { {0, 0, "PT0S"}, @@ -3114,18 +3222,19 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="toString") + @ParameterizedTest + @MethodSource("provider_toString") public void test_toString(long seconds, int nanos, String expected) { Duration t = Duration.ofSeconds(seconds, nanos); - assertEquals(t.toString(), expected); + assertEquals(expected, t.toString()); } //----------------------------------------------------------------------- - @Test(groups="{tck}") + @Test public void test_duration_getUnits() { Duration duration = Duration.ofSeconds(5000, 1000); List units = duration.getUnits(); - assertEquals(units.size(), 2, "Period.getUnits length"); + assertEquals(2, units.size(), "Period.getUnits length"); assertTrue(units.contains(ChronoUnit.SECONDS), "Period.getUnits contains ChronoUnit.SECONDS"); assertTrue(units.contains(ChronoUnit.NANOS), "contains ChronoUnit.NANOS"); } @@ -3134,12 +3243,11 @@ public class TCKDuration extends AbstractTCKTest { public void test_getUnit() { Duration test = Duration.ofSeconds(2000, 1000); long seconds = test.get(ChronoUnit.SECONDS); - assertEquals(seconds, 2000, "duration.get(SECONDS)"); + assertEquals(2000, seconds, "duration.get(SECONDS)"); long nanos = test.get(ChronoUnit.NANOS); - assertEquals(nanos, 1000, "duration.get(NANOS)"); + assertEquals(1000, nanos, "duration.get(NANOS)"); } - @DataProvider(name="BadTemporalUnit") Object[][] provider_factory_of_badTemporalUnit() { return new Object[][] { {0, MICROS}, @@ -3156,9 +3264,12 @@ public class TCKDuration extends AbstractTCKTest { }; } - @Test(dataProvider="BadTemporalUnit", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("provider_factory_of_badTemporalUnit") public void test_bad_getUnit(long amount, TemporalUnit unit) { - Duration t = Duration.of(amount, unit); - t.get(unit); + Assertions.assertThrows(DateTimeException.class, () -> { + Duration t = Duration.of(amount, unit); + t.get(unit); + }); } } diff --git a/test/jdk/java/time/tck/java/time/TCKInstant.java b/test/jdk/java/time/tck/java/time/TCKInstant.java index abbfe404a0e..8c245d69810 100644 --- a/test/jdk/java/time/tck/java/time/TCKInstant.java +++ b/test/jdk/java/time/tck/java/time/TCKInstant.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -73,9 +73,10 @@ import static java.time.temporal.ChronoUnit.NANOS; import static java.time.temporal.ChronoUnit.SECONDS; import static java.time.temporal.ChronoUnit.WEEKS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; @@ -107,16 +108,20 @@ import java.util.List; import java.util.Locale; import java.util.Optional; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test Instant. * * @bug 8133022 8307466 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKInstant extends AbstractDateTimeTest { private static final long MIN_SECOND = Instant.MIN.getEpochSecond(); @@ -126,7 +131,7 @@ public class TCKInstant extends AbstractDateTimeTest { private Instant TEST_12345_123456789; - @BeforeMethod + @BeforeEach public void setUp() { TEST_12345_123456789 = Instant.ofEpochSecond(12345, 123456789); } @@ -134,7 +139,8 @@ public class TCKInstant extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Override protected List samples() { - TemporalAccessor[] array = {TEST_12345_123456789, Instant.MIN, Instant.MAX, Instant.EPOCH}; + TemporalAccessor[] array = {Instant.ofEpochSecond(12345, 123456789), + Instant.MIN, Instant.MAX, Instant.EPOCH}; return Arrays.asList(array); } @@ -161,8 +167,8 @@ public class TCKInstant extends AbstractDateTimeTest { //----------------------------------------------------------------------- private void check(Instant instant, long epochSecs, int nos) { - assertEquals(instant.getEpochSecond(), epochSecs); - assertEquals(instant.getNano(), nos); + assertEquals(epochSecs, instant.getEpochSecond()); + assertEquals(nos, instant.getNano()); assertEquals(instant, instant); assertEquals(instant.hashCode(), instant.hashCode()); } @@ -208,9 +214,9 @@ public class TCKInstant extends AbstractDateTimeTest { //----------------------------------------------------------------------- // now(Clock) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullClock() { - Instant.now(null); + Assertions.assertThrows(NullPointerException.class, () -> Instant.now(null)); } @Test @@ -219,7 +225,7 @@ public class TCKInstant extends AbstractDateTimeTest { Instant expected = Instant.ofEpochSecond(i).plusNanos(123456789L); Clock clock = Clock.fixed(expected, ZoneOffset.UTC); Instant test = Instant.now(clock); - assertEquals(test, expected); + assertEquals(expected, test); } } @@ -229,7 +235,7 @@ public class TCKInstant extends AbstractDateTimeTest { Instant expected = Instant.ofEpochSecond(i).plusNanos(123456789L); Clock clock = Clock.fixed(expected, ZoneOffset.UTC); Instant test = Instant.now(clock); - assertEquals(test, expected); + assertEquals(expected, test); } } @@ -240,8 +246,8 @@ public class TCKInstant extends AbstractDateTimeTest { public void factory_seconds_long() { for (long i = -2; i <= 2; i++) { Instant t = Instant.ofEpochSecond(i); - assertEquals(t.getEpochSecond(), i); - assertEquals(t.getNano(), 0); + assertEquals(i, t.getEpochSecond()); + assertEquals(0, t.getNano()); } } @@ -253,18 +259,18 @@ public class TCKInstant extends AbstractDateTimeTest { for (long i = -2; i <= 2; i++) { for (int j = 0; j < 10; j++) { Instant t = Instant.ofEpochSecond(i, j); - assertEquals(t.getEpochSecond(), i); - assertEquals(t.getNano(), j); + assertEquals(i, t.getEpochSecond()); + assertEquals(j, t.getNano()); } for (int j = -10; j < 0; j++) { Instant t = Instant.ofEpochSecond(i, j); - assertEquals(t.getEpochSecond(), i - 1); - assertEquals(t.getNano(), j + 1000000000); + assertEquals(i - 1, t.getEpochSecond()); + assertEquals(j + 1000000000, t.getNano()); } for (int j = 999999990; j < 1000000000; j++) { Instant t = Instant.ofEpochSecond(i, j); - assertEquals(t.getEpochSecond(), i); - assertEquals(t.getNano(), j); + assertEquals(i, t.getEpochSecond()); + assertEquals(j, t.getNano()); } } } @@ -272,24 +278,23 @@ public class TCKInstant extends AbstractDateTimeTest { @Test public void factory_seconds_long_long_nanosNegativeAdjusted() { Instant test = Instant.ofEpochSecond(2L, -1); - assertEquals(test.getEpochSecond(), 1); - assertEquals(test.getNano(), 999999999); + assertEquals(1, test.getEpochSecond()); + assertEquals(999999999, test.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_seconds_long_long_tooBig() { - Instant.ofEpochSecond(MAX_SECOND, 1000000000); + Assertions.assertThrows(DateTimeException.class, () -> Instant.ofEpochSecond(MAX_SECOND, 1000000000)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void factory_seconds_long_long_tooBigBig() { - Instant.ofEpochSecond(Long.MAX_VALUE, Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> Instant.ofEpochSecond(Long.MAX_VALUE, Long.MAX_VALUE)); } //----------------------------------------------------------------------- // ofEpochMilli(long) //----------------------------------------------------------------------- - @DataProvider(name="MillisInstantNoNanos") Object[][] provider_factory_millis_long() { return new Object[][] { {0, 0, 0}, @@ -306,18 +311,18 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="MillisInstantNoNanos") + @ParameterizedTest + @MethodSource("provider_factory_millis_long") public void factory_millis_long(long millis, long expectedSeconds, int expectedNanoOfSecond) { Instant t = Instant.ofEpochMilli(millis); - assertEquals(t.getEpochSecond(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getEpochSecond()); + assertEquals(expectedNanoOfSecond, t.getNano()); } //----------------------------------------------------------------------- // parse(String) //----------------------------------------------------------------------- // see also parse tests under toString() - @DataProvider(name="Parse") Object[][] provider_factory_parse() { return new Object[][] { {"1970-01-01T00:00:00Z", 0, 0}, @@ -338,18 +343,20 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="Parse") + @ParameterizedTest + @MethodSource("provider_factory_parse") public void factory_parse(String text, long expectedEpochSeconds, int expectedNanoOfSecond) { Instant t = Instant.parse(text); - assertEquals(t.getEpochSecond(), expectedEpochSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedEpochSeconds, t.getEpochSecond()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(dataProvider="Parse") + @ParameterizedTest + @MethodSource("provider_factory_parse") public void factory_parseLowercase(String text, long expectedEpochSeconds, int expectedNanoOfSecond) { Instant t = Instant.parse(text.toLowerCase(Locale.ENGLISH)); - assertEquals(t.getEpochSecond(), expectedEpochSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedEpochSeconds, t.getEpochSecond()); + assertEquals(expectedNanoOfSecond, t.getNano()); } // TODO: should comma be accepted? @@ -361,7 +368,6 @@ public class TCKInstant extends AbstractDateTimeTest { // assertEquals(t.getNano(), expectedNanoOfSecond); // } - @DataProvider(name="ParseFailures") Object[][] provider_factory_parseFailures() { return new Object[][] { {""}, @@ -374,20 +380,22 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="ParseFailures", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("provider_factory_parseFailures") public void factory_parseFailures(String text) { - Instant.parse(text); + Assertions.assertThrows(DateTimeParseException.class, () -> Instant.parse(text)); } - @Test(dataProvider="ParseFailures", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("provider_factory_parseFailures") public void factory_parseFailures_comma(String text) { - text = text.replace('.', ','); - Instant.parse(text); + var commaText = text.replace('.', ','); + Assertions.assertThrows(DateTimeParseException.class, () -> Instant.parse(commaText)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_nullText() { - Instant.parse(null); + Assertions.assertThrows(NullPointerException.class, () -> Instant.parse(null)); } //----------------------------------------------------------------------- @@ -396,24 +404,23 @@ public class TCKInstant extends AbstractDateTimeTest { @Test public void test_get_TemporalField() { Instant test = TEST_12345_123456789; - assertEquals(test.get(ChronoField.NANO_OF_SECOND), 123456789); - assertEquals(test.get(ChronoField.MICRO_OF_SECOND), 123456); - assertEquals(test.get(ChronoField.MILLI_OF_SECOND), 123); + assertEquals(123456789, test.get(ChronoField.NANO_OF_SECOND)); + assertEquals(123456, test.get(ChronoField.MICRO_OF_SECOND)); + assertEquals(123, test.get(ChronoField.MILLI_OF_SECOND)); } @Test public void test_getLong_TemporalField() { Instant test = TEST_12345_123456789; - assertEquals(test.getLong(ChronoField.NANO_OF_SECOND), 123456789); - assertEquals(test.getLong(ChronoField.MICRO_OF_SECOND), 123456); - assertEquals(test.getLong(ChronoField.MILLI_OF_SECOND), 123); - assertEquals(test.getLong(ChronoField.INSTANT_SECONDS), 12345); + assertEquals(123456789, test.getLong(ChronoField.NANO_OF_SECOND)); + assertEquals(123456, test.getLong(ChronoField.MICRO_OF_SECOND)); + assertEquals(123, test.getLong(ChronoField.MILLI_OF_SECOND)); + assertEquals(12345, test.getLong(ChronoField.INSTANT_SECONDS)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {TEST_12345_123456789, TemporalQueries.chronology(), null}, @@ -426,25 +433,26 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - TEST_12345_123456789.query(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12345_123456789.query(null)); } //----------------------------------------------------------------------- // adjustInto(Temporal) //----------------------------------------------------------------------- - @DataProvider(name="adjustInto") Object[][] data_adjustInto() { return new Object[][]{ {Instant.ofEpochSecond(10, 200), Instant.ofEpochSecond(20), Instant.ofEpochSecond(10, 200), null}, @@ -464,11 +472,12 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="adjustInto") + @ParameterizedTest + @MethodSource("data_adjustInto") public void test_adjustInto(Instant test, Temporal temporal, Temporal expected, Class expectedEx) { if (expectedEx == null) { Temporal result = test.adjustInto(temporal); - assertEquals(result, expected); + assertEquals(expected, result); } else { try { Temporal result = test.adjustInto(temporal); @@ -482,7 +491,6 @@ public class TCKInstant extends AbstractDateTimeTest { //----------------------------------------------------------------------- // with(TemporalAdjuster) //----------------------------------------------------------------------- - @DataProvider(name="with") Object[][] data_with() { return new Object[][]{ {Instant.ofEpochSecond(10, 200), Instant.ofEpochSecond(20), Instant.ofEpochSecond(20), null}, @@ -500,11 +508,12 @@ public class TCKInstant extends AbstractDateTimeTest { } - @Test(dataProvider="with") + @ParameterizedTest + @MethodSource("data_with") public void test_with_temporalAdjuster(Instant test, TemporalAdjuster adjuster, Instant expected, Class expectedEx) { if (expectedEx == null) { Instant result = test.with(adjuster); - assertEquals(result, expected); + assertEquals(expected, result); } else { try { Instant result = test.with(adjuster); @@ -518,7 +527,6 @@ public class TCKInstant extends AbstractDateTimeTest { //----------------------------------------------------------------------- // with(TemporalField, long) //----------------------------------------------------------------------- - @DataProvider(name="with_longTemporalField") Object[][] data_with_longTemporalField() { return new Object[][]{ {Instant.ofEpochSecond(10, 200), ChronoField.INSTANT_SECONDS, 100, Instant.ofEpochSecond(100, 200), null}, @@ -548,11 +556,12 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="with_longTemporalField") + @ParameterizedTest + @MethodSource("data_with_longTemporalField") public void test_with_longTemporalField(Instant test, TemporalField field, long value, Instant expected, Class expectedEx) { if (expectedEx == null) { Instant result = test.with(field, value); - assertEquals(result, expected); + assertEquals(expected, result); } else { try { Instant result = test.with(field, value); @@ -636,7 +645,6 @@ public class TCKInstant extends AbstractDateTimeTest { } }; - @DataProvider(name="truncatedToValid") Object[][] data_truncatedToValid() { return new Object[][] { {Instant.ofEpochSecond(86400 + 3600 + 60 + 1, 123_456_789), NANOS, Instant.ofEpochSecond(86400 + 3600 + 60 + 1, 123_456_789)}, @@ -658,12 +666,12 @@ public class TCKInstant extends AbstractDateTimeTest { {Instant.ofEpochSecond(-86400 - 3600 - 120, 0), MINUTES, Instant.ofEpochSecond(-86400 - 3600 - 120, 0)}, }; } - @Test(dataProvider="truncatedToValid") + @ParameterizedTest + @MethodSource("data_truncatedToValid") public void test_truncatedTo_valid(Instant input, TemporalUnit unit, Instant expected) { - assertEquals(input.truncatedTo(unit), expected); + assertEquals(expected, input.truncatedTo(unit)); } - @DataProvider(name="truncatedToInvalid") Object[][] data_truncatedToInvalid() { return new Object[][] { {Instant.ofEpochSecond(1, 123_456_789), NINETY_FIVE_MINS}, @@ -673,20 +681,20 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="truncatedToInvalid", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_truncatedToInvalid") public void test_truncatedTo_invalid(Instant input, TemporalUnit unit) { - input.truncatedTo(unit); + Assertions.assertThrows(DateTimeException.class, () -> input.truncatedTo(unit)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_truncatedTo_null() { - TEST_12345_123456789.truncatedTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12345_123456789.truncatedTo(null)); } //----------------------------------------------------------------------- // plus(TemporalAmount) //----------------------------------------------------------------------- - @DataProvider(name="plusTemporalAmount") Object[][] data_plusTemporalAmount() { return new Object[][] { {DAYS, MockSimplePeriod.of(1, DAYS), 86401, 0}, @@ -704,15 +712,15 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="plusTemporalAmount") + @ParameterizedTest + @MethodSource("data_plusTemporalAmount") public void test_plusTemporalAmount(TemporalUnit unit, TemporalAmount amount, int seconds, int nanos) { Instant inst = Instant.ofEpochMilli(1000); Instant actual = inst.plus(amount); Instant expected = Instant.ofEpochSecond(seconds, nanos); - assertEquals(actual, expected, "plus(TemporalAmount) failed"); + assertEquals(expected, actual, "plus(TemporalAmount) failed"); } - @DataProvider(name="badTemporalAmount") Object[][] data_badPlusTemporalAmount() { return new Object[][] { {MockSimplePeriod.of(2, YEARS)}, @@ -720,14 +728,16 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="badTemporalAmount",expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_badPlusTemporalAmount") public void test_badPlusTemporalAmount(TemporalAmount amount) { - Instant inst = Instant.ofEpochMilli(1000); - inst.plus(amount); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant inst = Instant.ofEpochMilli(1000); + inst.plus(amount); + }); } //----------------------------------------------------------------------- - @DataProvider(name="Plus") Object[][] provider_plus() { return new Object[][] { {MIN_SECOND, 0, -MIN_SECOND, 0, 0, 0}, @@ -928,48 +938,57 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="Plus") + @ParameterizedTest + @MethodSource("provider_plus") public void plus_Duration(long seconds, int nanos, long otherSeconds, int otherNanos, long expectedSeconds, int expectedNanoOfSecond) { Instant i = Instant.ofEpochSecond(seconds, nanos).plus(Duration.ofSeconds(otherSeconds, otherNanos)); - assertEquals(i.getEpochSecond(), expectedSeconds); - assertEquals(i.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, i.getEpochSecond()); + assertEquals(expectedNanoOfSecond, i.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void plus_Duration_overflowTooBig() { - Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999); - i.plus(Duration.ofSeconds(0, 1)); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999); + i.plus(Duration.ofSeconds(0, 1)); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void plus_Duration_overflowTooSmall() { - Instant i = Instant.ofEpochSecond(MIN_SECOND); - i.plus(Duration.ofSeconds(-1, 999999999)); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MIN_SECOND); + i.plus(Duration.ofSeconds(-1, 999999999)); + }); } //-----------------------------------------------------------------------a - @Test(dataProvider="Plus") + @ParameterizedTest + @MethodSource("provider_plus") public void plus_longTemporalUnit(long seconds, int nanos, long otherSeconds, int otherNanos, long expectedSeconds, int expectedNanoOfSecond) { Instant i = Instant.ofEpochSecond(seconds, nanos).plus(otherSeconds, SECONDS).plus(otherNanos, NANOS); - assertEquals(i.getEpochSecond(), expectedSeconds); - assertEquals(i.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, i.getEpochSecond()); + assertEquals(expectedNanoOfSecond, i.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void plus_longTemporalUnit_overflowTooBig() { - Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999); - i.plus(1, NANOS); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999); + i.plus(1, NANOS); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void plus_longTemporalUnit_overflowTooSmall() { - Instant i = Instant.ofEpochSecond(MIN_SECOND); - i.plus(999999999, NANOS); - i.plus(-1, SECONDS); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MIN_SECOND); + i.plus(999999999, NANOS); + i.plus(-1, SECONDS); + }); } //----------------------------------------------------------------------- - @DataProvider(name="PlusSeconds") Object[][] provider_plusSeconds_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -998,28 +1017,32 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="PlusSeconds") + @ParameterizedTest + @MethodSource("provider_plusSeconds_long") public void plusSeconds_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Instant t = Instant.ofEpochSecond(seconds, nanos); t = t.plusSeconds(amount); - assertEquals(t.getEpochSecond(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getEpochSecond()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void plusSeconds_long_overflowTooBig() { - Instant t = Instant.ofEpochSecond(1, 0); - t.plusSeconds(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> { + Instant t = Instant.ofEpochSecond(1, 0); + t.plusSeconds(Long.MAX_VALUE); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void plusSeconds_long_overflowTooSmall() { - Instant t = Instant.ofEpochSecond(-1, 0); - t.plusSeconds(Long.MIN_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> { + Instant t = Instant.ofEpochSecond(-1, 0); + t.plusSeconds(Long.MIN_VALUE); + }); } //----------------------------------------------------------------------- - @DataProvider(name="PlusMillis") Object[][] provider_plusMillis_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -1077,58 +1100,64 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="PlusMillis") + @ParameterizedTest + @MethodSource("provider_plusMillis_long") public void plusMillis_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Instant t = Instant.ofEpochSecond(seconds, nanos); t = t.plusMillis(amount); - assertEquals(t.getEpochSecond(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getEpochSecond()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(dataProvider="PlusMillis") + @ParameterizedTest + @MethodSource("provider_plusMillis_long") public void plusMillis_long_oneMore(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Instant t = Instant.ofEpochSecond(seconds + 1, nanos); t = t.plusMillis(amount); - assertEquals(t.getEpochSecond(), expectedSeconds + 1); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds + 1, t.getEpochSecond()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(dataProvider="PlusMillis") + @ParameterizedTest + @MethodSource("provider_plusMillis_long") public void plusMillis_long_minusOneLess(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Instant t = Instant.ofEpochSecond(seconds - 1, nanos); t = t.plusMillis(amount); - assertEquals(t.getEpochSecond(), expectedSeconds - 1); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds - 1, t.getEpochSecond()); + assertEquals(expectedNanoOfSecond, t.getNano()); } @Test public void plusMillis_long_max() { Instant t = Instant.ofEpochSecond(MAX_SECOND, 998999999); t = t.plusMillis(1); - assertEquals(t.getEpochSecond(), MAX_SECOND); - assertEquals(t.getNano(), 999999999); + assertEquals(MAX_SECOND, t.getEpochSecond()); + assertEquals(999999999, t.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void plusMillis_long_overflowTooBig() { - Instant t = Instant.ofEpochSecond(MAX_SECOND, 999000000); - t.plusMillis(1); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant t = Instant.ofEpochSecond(MAX_SECOND, 999000000); + t.plusMillis(1); + }); } @Test public void plusMillis_long_min() { Instant t = Instant.ofEpochSecond(MIN_SECOND, 1000000); t = t.plusMillis(-1); - assertEquals(t.getEpochSecond(), MIN_SECOND); - assertEquals(t.getNano(), 0); + assertEquals(MIN_SECOND, t.getEpochSecond()); + assertEquals(0, t.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void plusMillis_long_overflowTooSmall() { - Instant t = Instant.ofEpochSecond(MIN_SECOND, 0); - t.plusMillis(-1); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant t = Instant.ofEpochSecond(MIN_SECOND, 0); + t.plusMillis(-1); + }); } //----------------------------------------------------------------------- - @DataProvider(name="PlusNanos") Object[][] provider_plusNanos_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -1206,27 +1235,31 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="PlusNanos") + @ParameterizedTest + @MethodSource("provider_plusNanos_long") public void plusNanos_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Instant t = Instant.ofEpochSecond(seconds, nanos); t = t.plusNanos(amount); - assertEquals(t.getEpochSecond(), expectedSeconds); - assertEquals(t.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, t.getEpochSecond()); + assertEquals(expectedNanoOfSecond, t.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void plusNanos_long_overflowTooBig() { - Instant t = Instant.ofEpochSecond(MAX_SECOND, 999999999); - t.plusNanos(1); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant t = Instant.ofEpochSecond(MAX_SECOND, 999999999); + t.plusNanos(1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void plusNanos_long_overflowTooSmall() { - Instant t = Instant.ofEpochSecond(MIN_SECOND, 0); - t.plusNanos(-1); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant t = Instant.ofEpochSecond(MIN_SECOND, 0); + t.plusNanos(-1); + }); } - @DataProvider(name = "PlusSaturating") Object[][] provider_plusSaturating() { return new Object[][]{ // 1. {edge or constant instants} x {edge or constant durations} @@ -1267,27 +1300,27 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider = "PlusSaturating") + @ParameterizedTest + @MethodSource("provider_plusSaturating") public void plusSaturating(Instant i, Duration d, Optional value) { var actual = i.plusSaturating(d); try { - assertEquals(actual, i.plus(d)); + assertEquals(i.plus(d), actual); // If `value` is present, perform an additional check. It may be // important to ensure that not only does the result of `plusSaturating` // match that of `plus`, but that it also matches our expectation. // Because if it doesn’t, then the test isn’t testing what we think // it is, and needs to be fixed. - value.ifPresent(instant -> assertEquals(actual, instant)); + value.ifPresent(instant -> assertEquals(instant, actual)); } catch (DateTimeException /* instant overflow */ | ArithmeticException /* long overflow */ e) { if (value.isEmpty()) { throw new AssertionError(); } - assertEquals(actual, value.get()); + assertEquals(value.get(), actual); } } - @DataProvider(name = "PlusSaturating_null") Object[][] provider_plusSaturating_null() { return new Object[][]{ {Instant.MIN}, @@ -1298,13 +1331,13 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(expectedExceptions = NullPointerException.class, dataProvider = "PlusSaturating_null") + @ParameterizedTest + @MethodSource("provider_plusSaturating_null") public void test_plusSaturating_null(Instant i) { - i.plusSaturating(null); + Assertions.assertThrows(NullPointerException.class, () -> i.plusSaturating(null)); } //----------------------------------------------------------------------- - @DataProvider(name="Minus") Object[][] provider_minus() { return new Object[][] { {MIN_SECOND, 0, MIN_SECOND, 0, 0, 0}, @@ -1505,48 +1538,57 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="Minus") + @ParameterizedTest + @MethodSource("provider_minus") public void minus_Duration(long seconds, int nanos, long otherSeconds, int otherNanos, long expectedSeconds, int expectedNanoOfSecond) { Instant i = Instant.ofEpochSecond(seconds, nanos).minus(Duration.ofSeconds(otherSeconds, otherNanos)); - assertEquals(i.getEpochSecond(), expectedSeconds); - assertEquals(i.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, i.getEpochSecond()); + assertEquals(expectedNanoOfSecond, i.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void minus_Duration_overflowTooSmall() { - Instant i = Instant.ofEpochSecond(MIN_SECOND); - i.minus(Duration.ofSeconds(0, 1)); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MIN_SECOND); + i.minus(Duration.ofSeconds(0, 1)); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void minus_Duration_overflowTooBig() { - Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999); - i.minus(Duration.ofSeconds(-1, 999999999)); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999); + i.minus(Duration.ofSeconds(-1, 999999999)); + }); } //----------------------------------------------------------------------- - @Test(dataProvider="Minus") + @ParameterizedTest + @MethodSource("provider_minus") public void minus_longTemporalUnit(long seconds, int nanos, long otherSeconds, int otherNanos, long expectedSeconds, int expectedNanoOfSecond) { Instant i = Instant.ofEpochSecond(seconds, nanos).minus(otherSeconds, SECONDS).minus(otherNanos, NANOS); - assertEquals(i.getEpochSecond(), expectedSeconds); - assertEquals(i.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, i.getEpochSecond()); + assertEquals(expectedNanoOfSecond, i.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void minus_longTemporalUnit_overflowTooSmall() { - Instant i = Instant.ofEpochSecond(MIN_SECOND); - i.minus(1, NANOS); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MIN_SECOND); + i.minus(1, NANOS); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void minus_longTemporalUnit_overflowTooBig() { - Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999); - i.minus(999999999, NANOS); - i.minus(-1, SECONDS); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999); + i.minus(999999999, NANOS); + i.minus(-1, SECONDS); + }); } //----------------------------------------------------------------------- - @DataProvider(name="MinusSeconds") Object[][] provider_minusSeconds_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -1575,28 +1617,32 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="MinusSeconds") + @ParameterizedTest + @MethodSource("provider_minusSeconds_long") public void minusSeconds_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Instant i = Instant.ofEpochSecond(seconds, nanos); i = i.minusSeconds(amount); - assertEquals(i.getEpochSecond(), expectedSeconds); - assertEquals(i.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, i.getEpochSecond()); + assertEquals(expectedNanoOfSecond, i.getNano()); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusSeconds_long_overflowTooBig() { - Instant i = Instant.ofEpochSecond(1, 0); - i.minusSeconds(Long.MIN_VALUE + 1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Instant i = Instant.ofEpochSecond(1, 0); + i.minusSeconds(Long.MIN_VALUE + 1); + }); } - @Test(expectedExceptions = {ArithmeticException.class}) + @Test public void minusSeconds_long_overflowTooSmall() { - Instant i = Instant.ofEpochSecond(-2, 0); - i.minusSeconds(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> { + Instant i = Instant.ofEpochSecond(-2, 0); + i.minusSeconds(Long.MAX_VALUE); + }); } //----------------------------------------------------------------------- - @DataProvider(name="MinusMillis") Object[][] provider_minusMillis_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -1654,60 +1700,66 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="MinusMillis") + @ParameterizedTest + @MethodSource("provider_minusMillis_long") public void minusMillis_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Instant i = Instant.ofEpochSecond(seconds, nanos); i = i.minusMillis(amount); - assertEquals(i.getEpochSecond(), expectedSeconds); - assertEquals(i.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, i.getEpochSecond()); + assertEquals(expectedNanoOfSecond, i.getNano()); } - @Test(dataProvider="MinusMillis") + @ParameterizedTest + @MethodSource("provider_minusMillis_long") public void minusMillis_long_oneMore(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Instant i = Instant.ofEpochSecond(seconds + 1, nanos); i = i.minusMillis(amount); - assertEquals(i.getEpochSecond(), expectedSeconds + 1); - assertEquals(i.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds + 1, i.getEpochSecond()); + assertEquals(expectedNanoOfSecond, i.getNano()); } - @Test(dataProvider="MinusMillis") + @ParameterizedTest + @MethodSource("provider_minusMillis_long") public void minusMillis_long_minusOneLess(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Instant i = Instant.ofEpochSecond(seconds - 1, nanos); i = i.minusMillis(amount); - assertEquals(i.getEpochSecond(), expectedSeconds - 1); - assertEquals(i.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds - 1, i.getEpochSecond()); + assertEquals(expectedNanoOfSecond, i.getNano()); } @Test public void minusMillis_long_max() { Instant i = Instant.ofEpochSecond(MAX_SECOND, 998999999); i = i.minusMillis(-1); - assertEquals(i.getEpochSecond(), MAX_SECOND); - assertEquals(i.getNano(), 999999999); + assertEquals(MAX_SECOND, i.getEpochSecond()); + assertEquals(999999999, i.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void minusMillis_long_overflowTooBig() { - Instant i = Instant.ofEpochSecond(MAX_SECOND, 999000000); - i.minusMillis(-1); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MAX_SECOND, 999000000); + i.minusMillis(-1); + }); } @Test public void minusMillis_long_min() { Instant i = Instant.ofEpochSecond(MIN_SECOND, 1000000); i = i.minusMillis(1); - assertEquals(i.getEpochSecond(), MIN_SECOND); - assertEquals(i.getNano(), 0); + assertEquals(MIN_SECOND, i.getEpochSecond()); + assertEquals(0, i.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void minusMillis_long_overflowTooSmall() { - Instant i = Instant.ofEpochSecond(MIN_SECOND, 0); - i.minusMillis(1); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MIN_SECOND, 0); + i.minusMillis(1); + }); } //----------------------------------------------------------------------- - @DataProvider(name="MinusNanos") Object[][] provider_minusNanos_long() { return new Object[][] { {0, 0, 0, 0, 0}, @@ -1785,30 +1837,34 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="MinusNanos") + @ParameterizedTest + @MethodSource("provider_minusNanos_long") public void minusNanos_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Instant i = Instant.ofEpochSecond(seconds, nanos); i = i.minusNanos(amount); - assertEquals(i.getEpochSecond(), expectedSeconds); - assertEquals(i.getNano(), expectedNanoOfSecond); + assertEquals(expectedSeconds, i.getEpochSecond()); + assertEquals(expectedNanoOfSecond, i.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void minusNanos_long_overflowTooBig() { - Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999); - i.minusNanos(-1); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MAX_SECOND, 999999999); + i.minusNanos(-1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void minusNanos_long_overflowTooSmall() { - Instant i = Instant.ofEpochSecond(MIN_SECOND, 0); - i.minusNanos(1); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant i = Instant.ofEpochSecond(MIN_SECOND, 0); + i.minusNanos(1); + }); } //----------------------------------------------------------------------- // until(Temporal, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="periodUntilUnit") Object[][] data_periodUntilUnit() { return new Object[][] { {5, 650, -1, 650, SECONDS, -6}, @@ -1958,56 +2014,61 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit(long seconds1, int nanos1, long seconds2, long nanos2, TemporalUnit unit, long expected) { Instant i1 = Instant.ofEpochSecond(seconds1, nanos1); Instant i2 = Instant.ofEpochSecond(seconds2, nanos2); long amount = i1.until(i2, unit); - assertEquals(amount, expected); + assertEquals(expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_negated(long seconds1, int nanos1, long seconds2, long nanos2, TemporalUnit unit, long expected) { Instant i1 = Instant.ofEpochSecond(seconds1, nanos1); Instant i2 = Instant.ofEpochSecond(seconds2, nanos2); long amount = i2.until(i1, unit); - assertEquals(amount, -expected); + assertEquals(-expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_between(long seconds1, int nanos1, long seconds2, long nanos2, TemporalUnit unit, long expected) { Instant i1 = Instant.ofEpochSecond(seconds1, nanos1); Instant i2 = Instant.ofEpochSecond(seconds2, nanos2); long amount = unit.between(i1, i2); - assertEquals(amount, expected); + assertEquals(expected, amount); } @Test public void test_until_convertedType() { Instant start = Instant.ofEpochSecond(12, 3000); OffsetDateTime end = start.plusSeconds(2).atOffset(ZoneOffset.ofHours(2)); - assertEquals(start.until(end, SECONDS), 2); + assertEquals(2, start.until(end, SECONDS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_invalidType() { - Instant start = Instant.ofEpochSecond(12, 3000); - start.until(LocalTime.of(11, 30), SECONDS); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant start = Instant.ofEpochSecond(12, 3000); + start.until(LocalTime.of(11, 30), SECONDS); + }); } - @Test(expectedExceptions = UnsupportedTemporalTypeException.class) + @Test public void test_until_TemporalUnit_unsupportedUnit() { - TEST_12345_123456789.until(TEST_12345_123456789, MONTHS); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> TEST_12345_123456789.until(TEST_12345_123456789, MONTHS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullEnd() { - TEST_12345_123456789.until(null, HOURS); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12345_123456789.until(null, HOURS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullUnit() { - TEST_12345_123456789.until(TEST_12345_123456789, null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12345_123456789.until(TEST_12345_123456789, null)); } //----------------------------------------------------------------------- @@ -2018,18 +2079,18 @@ public class TCKInstant extends AbstractDateTimeTest { for (int i = 0; i < (24 * 60 * 60); i++) { Instant instant = Instant.ofEpochSecond(i); OffsetDateTime test = instant.atOffset(ZoneOffset.ofHours(1)); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonthValue(), 1); - assertEquals(test.getDayOfMonth(), 1 + (i >= 23 * 60 * 60 ? 1 : 0)); - assertEquals(test.getHour(), ((i / (60 * 60)) + 1) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); + assertEquals(1970, test.getYear()); + assertEquals(1, test.getMonthValue()); + assertEquals(1 + (i >= 23 * 60 * 60 ? 1 : 0), test.getDayOfMonth()); + assertEquals(((i / (60 * 60)) + 1) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atOffset_null() { - TEST_12345_123456789.atOffset(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12345_123456789.atOffset(null)); } //----------------------------------------------------------------------- @@ -2040,18 +2101,18 @@ public class TCKInstant extends AbstractDateTimeTest { for (int i = 0; i < (24 * 60 * 60); i++) { Instant instant = Instant.ofEpochSecond(i); ZonedDateTime test = instant.atZone(ZoneOffset.ofHours(1)); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonthValue(), 1); - assertEquals(test.getDayOfMonth(), 1 + (i >= 23 * 60 * 60 ? 1 : 0)); - assertEquals(test.getHour(), ((i / (60 * 60)) + 1) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); + assertEquals(1970, test.getYear()); + assertEquals(1, test.getMonthValue()); + assertEquals(1 + (i >= 23 * 60 * 60 ? 1 : 0), test.getDayOfMonth()); + assertEquals(((i / (60 * 60)) + 1) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atZone_null() { - TEST_12345_123456789.atZone(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12345_123456789.atZone(null)); } //----------------------------------------------------------------------- @@ -2059,40 +2120,40 @@ public class TCKInstant extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_toEpochMilli() { - assertEquals(Instant.ofEpochSecond(1L, 1000000).toEpochMilli(), 1001L); - assertEquals(Instant.ofEpochSecond(1L, 2000000).toEpochMilli(), 1002L); - assertEquals(Instant.ofEpochSecond(1L, 567).toEpochMilli(), 1000L); - assertEquals(Instant.ofEpochSecond(Long.MAX_VALUE / 1000).toEpochMilli(), (Long.MAX_VALUE / 1000) * 1000); - assertEquals(Instant.ofEpochSecond(Long.MIN_VALUE / 1000).toEpochMilli(), (Long.MIN_VALUE / 1000) * 1000); - assertEquals(Instant.ofEpochSecond(0L, -1000000).toEpochMilli(), -1L); - assertEquals(Instant.ofEpochSecond(0L, 1000000).toEpochMilli(), 1); - assertEquals(Instant.ofEpochSecond(0L, 999999).toEpochMilli(), 0); - assertEquals(Instant.ofEpochSecond(0L, 1).toEpochMilli(), 0); - assertEquals(Instant.ofEpochSecond(0L, 0).toEpochMilli(), 0); - assertEquals(Instant.ofEpochSecond(0L, -1).toEpochMilli(), -1L); - assertEquals(Instant.ofEpochSecond(0L, -999999).toEpochMilli(), -1L); - assertEquals(Instant.ofEpochSecond(0L, -1000000).toEpochMilli(), -1L); - assertEquals(Instant.ofEpochSecond(0L, -1000001).toEpochMilli(), -2L); + assertEquals(1001L, Instant.ofEpochSecond(1L, 1000000).toEpochMilli()); + assertEquals(1002L, Instant.ofEpochSecond(1L, 2000000).toEpochMilli()); + assertEquals(1000L, Instant.ofEpochSecond(1L, 567).toEpochMilli()); + assertEquals((Long.MAX_VALUE / 1000) * 1000, Instant.ofEpochSecond(Long.MAX_VALUE / 1000).toEpochMilli()); + assertEquals((Long.MIN_VALUE / 1000) * 1000, Instant.ofEpochSecond(Long.MIN_VALUE / 1000).toEpochMilli()); + assertEquals(-1L, Instant.ofEpochSecond(0L, -1000000).toEpochMilli()); + assertEquals(1, Instant.ofEpochSecond(0L, 1000000).toEpochMilli()); + assertEquals(0, Instant.ofEpochSecond(0L, 999999).toEpochMilli()); + assertEquals(0, Instant.ofEpochSecond(0L, 1).toEpochMilli()); + assertEquals(0, Instant.ofEpochSecond(0L, 0).toEpochMilli()); + assertEquals(-1L, Instant.ofEpochSecond(0L, -1).toEpochMilli()); + assertEquals(-1L, Instant.ofEpochSecond(0L, -999999).toEpochMilli()); + assertEquals(-1L, Instant.ofEpochSecond(0L, -1000000).toEpochMilli()); + assertEquals(-2L, Instant.ofEpochSecond(0L, -1000001).toEpochMilli()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_toEpochMilli_tooBig() { - Instant.ofEpochSecond(Long.MAX_VALUE / 1000 + 1).toEpochMilli(); + Assertions.assertThrows(ArithmeticException.class, () -> Instant.ofEpochSecond(Long.MAX_VALUE / 1000 + 1).toEpochMilli()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_toEpochMilli_tooSmall() { - Instant.ofEpochSecond(Long.MIN_VALUE / 1000 - 1).toEpochMilli(); + Assertions.assertThrows(ArithmeticException.class, () -> Instant.ofEpochSecond(Long.MIN_VALUE / 1000 - 1).toEpochMilli()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_toEpochMillis_overflow() { - Instant.ofEpochSecond(Long.MAX_VALUE / 1000, 809_000_000).toEpochMilli(); + Assertions.assertThrows(ArithmeticException.class, () -> Instant.ofEpochSecond(Long.MAX_VALUE / 1000, 809_000_000).toEpochMilli()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_toEpochMillis_overflow2() { - Instant.ofEpochSecond(-9223372036854776L, 1).toEpochMilli(); + Assertions.assertThrows(ArithmeticException.class, () -> Instant.ofEpochSecond(-9223372036854776L, 1).toEpochMilli()); } //----------------------------------------------------------------------- @@ -2123,48 +2184,56 @@ public class TCKInstant extends AbstractDateTimeTest { for (int j = 0; j < instants.length; j++) { Instant b = instants[j]; if (i < j) { - assertEquals(a.compareTo(b) < 0, true, a + " <=> " + b); - assertEquals(a.isBefore(b), true, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.compareTo(b) < 0, a + " <=> " + b); + assertEquals(true, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { - assertEquals(a.compareTo(b) > 0, true, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.compareTo(b) > 0, a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(true, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_ObjectNull() { - Instant a = Instant.ofEpochSecond(0L, 0); - a.compareTo(null); + Assertions.assertThrows(NullPointerException.class, () -> { + Instant a = Instant.ofEpochSecond(0L, 0); + a.compareTo(null); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isBefore_ObjectNull() { - Instant a = Instant.ofEpochSecond(0L, 0); - a.isBefore(null); + Assertions.assertThrows(NullPointerException.class, () -> { + Instant a = Instant.ofEpochSecond(0L, 0); + a.isBefore(null); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isAfter_ObjectNull() { - Instant a = Instant.ofEpochSecond(0L, 0); - a.isAfter(null); + Assertions.assertThrows(NullPointerException.class, () -> { + Instant a = Instant.ofEpochSecond(0L, 0); + a.isAfter(null); + }); } - @Test(expectedExceptions=ClassCastException.class) @SuppressWarnings({"unchecked", "rawtypes"}) + @Test public void compareToNonInstant() { - Comparable c = Instant.ofEpochSecond(0L); - c.compareTo(new Object()); + Assertions.assertThrows(ClassCastException.class, () -> { + Comparable c = Instant.ofEpochSecond(0L); + c.compareTo(new Object()); + }); } //----------------------------------------------------------------------- @@ -2177,37 +2246,37 @@ public class TCKInstant extends AbstractDateTimeTest { Instant test5n = Instant.ofEpochSecond(5L, 30); Instant test6 = Instant.ofEpochSecond(6L, 20); - assertEquals(test5a.equals(test5a), true); - assertEquals(test5a.equals(test5b), true); - assertEquals(test5a.equals(test5n), false); - assertEquals(test5a.equals(test6), false); + assertEquals(true, test5a.equals(test5a)); + assertEquals(true, test5a.equals(test5b)); + assertEquals(false, test5a.equals(test5n)); + assertEquals(false, test5a.equals(test6)); - assertEquals(test5b.equals(test5a), true); - assertEquals(test5b.equals(test5b), true); - assertEquals(test5b.equals(test5n), false); - assertEquals(test5b.equals(test6), false); + assertEquals(true, test5b.equals(test5a)); + assertEquals(true, test5b.equals(test5b)); + assertEquals(false, test5b.equals(test5n)); + assertEquals(false, test5b.equals(test6)); - assertEquals(test5n.equals(test5a), false); - assertEquals(test5n.equals(test5b), false); - assertEquals(test5n.equals(test5n), true); - assertEquals(test5n.equals(test6), false); + assertEquals(false, test5n.equals(test5a)); + assertEquals(false, test5n.equals(test5b)); + assertEquals(true, test5n.equals(test5n)); + assertEquals(false, test5n.equals(test6)); - assertEquals(test6.equals(test5a), false); - assertEquals(test6.equals(test5b), false); - assertEquals(test6.equals(test5n), false); - assertEquals(test6.equals(test6), true); + assertEquals(false, test6.equals(test5a)); + assertEquals(false, test6.equals(test5b)); + assertEquals(false, test6.equals(test5n)); + assertEquals(true, test6.equals(test6)); } @Test public void test_equals_null() { Instant test5 = Instant.ofEpochSecond(5L, 20); - assertEquals(test5.equals(null), false); + assertEquals(false, test5.equals(null)); } @Test public void test_equals_otherClass() { Instant test5 = Instant.ofEpochSecond(5L, 20); - assertEquals(test5.equals(""), false); + assertEquals(false, test5.equals("")); } //----------------------------------------------------------------------- @@ -2220,18 +2289,17 @@ public class TCKInstant extends AbstractDateTimeTest { Instant test5n = Instant.ofEpochSecond(5L, 30); Instant test6 = Instant.ofEpochSecond(6L, 20); - assertEquals(test5a.hashCode() == test5a.hashCode(), true); - assertEquals(test5a.hashCode() == test5b.hashCode(), true); - assertEquals(test5b.hashCode() == test5b.hashCode(), true); + assertEquals(true, test5a.hashCode() == test5a.hashCode()); + assertEquals(true, test5a.hashCode() == test5b.hashCode()); + assertEquals(true, test5b.hashCode() == test5b.hashCode()); - assertEquals(test5a.hashCode() == test5n.hashCode(), false); - assertEquals(test5a.hashCode() == test6.hashCode(), false); + assertEquals(false, test5a.hashCode() == test5n.hashCode()); + assertEquals(false, test5a.hashCode() == test6.hashCode()); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="toStringParse") Object[][] data_toString() { return new Object[][] { {Instant.ofEpochSecond(65L, 567), "1970-01-01T00:01:05.000000567Z"}, @@ -2297,19 +2365,22 @@ public class TCKInstant extends AbstractDateTimeTest { }; } - @Test(dataProvider="toStringParse") + @ParameterizedTest + @MethodSource("data_toString") public void test_toString(Instant instant, String expected) { - assertEquals(instant.toString(), expected); + assertEquals(expected, instant.toString()); } - @Test(dataProvider="toStringParse") + @ParameterizedTest + @MethodSource("data_toString") public void test_parse(Instant instant, String text) { - assertEquals(Instant.parse(text), instant); + assertEquals(instant, Instant.parse(text)); } - @Test(dataProvider="toStringParse") + @ParameterizedTest + @MethodSource("data_toString") public void test_parseLowercase(Instant instant, String text) { - assertEquals(Instant.parse(text.toLowerCase(Locale.ENGLISH)), instant); + assertEquals(instant, Instant.parse(text.toLowerCase(Locale.ENGLISH))); } } diff --git a/test/jdk/java/time/tck/java/time/TCKLocalDate.java b/test/jdk/java/time/tck/java/time/TCKLocalDate.java index 2b5832465c9..132aa31ed97 100644 --- a/test/jdk/java/time/tck/java/time/TCKLocalDate.java +++ b/test/jdk/java/time/tck/java/time/TCKLocalDate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -80,11 +80,12 @@ import static java.time.temporal.ChronoUnit.MILLENNIA; import static java.time.temporal.ChronoUnit.MONTHS; import static java.time.temporal.ChronoUnit.WEEKS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Clock; import java.time.DateTimeException; @@ -122,16 +123,20 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.MockSimplePeriod; import test.java.time.temporal.MockFieldNoValue; /** * Test LocalDate. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKLocalDate extends AbstractDateTimeTest { private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); @@ -148,7 +153,7 @@ public class TCKLocalDate extends AbstractDateTimeTest { private Instant MAX_INSTANT; private Instant MIN_INSTANT; - @BeforeMethod + @BeforeEach public void setUp() { TEST_2007_07_15 = LocalDate.of(2007, 7, 15); @@ -165,7 +170,7 @@ public class TCKLocalDate extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Override protected List samples() { - TemporalAccessor[] array = {TEST_2007_07_15, LocalDate.MAX, LocalDate.MIN, }; + TemporalAccessor[] array = {LocalDate.of(2007, 7, 15), LocalDate.MAX, LocalDate.MIN, }; return Arrays.asList(array); } @@ -201,12 +206,12 @@ public class TCKLocalDate extends AbstractDateTimeTest { //----------------------------------------------------------------------- private void check(LocalDate test, int y, int m, int d) { - assertEquals(test.getYear(), y); - assertEquals(test.getMonth().getValue(), m); - assertEquals(test.getDayOfMonth(), d); + assertEquals(y, test.getYear()); + assertEquals(m, test.getMonth().getValue()); + assertEquals(d, test.getDayOfMonth()); assertEquals(test, test); assertEquals(test.hashCode(), test.hashCode()); - assertEquals(LocalDate.of(y, m, d), test); + assertEquals(test, LocalDate.of(y, m, d)); } //----------------------------------------------------------------------- @@ -236,15 +241,15 @@ public class TCKLocalDate extends AbstractDateTimeTest { expected = LocalDate.now(Clock.systemDefaultZone()); test = LocalDate.now(); } - assertEquals(test, expected); + assertEquals(expected, test); } //----------------------------------------------------------------------- // now(ZoneId) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_ZoneId_nullZoneId() { - LocalDate.now((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDate.now((ZoneId) null)); } @Test @@ -259,15 +264,15 @@ public class TCKLocalDate extends AbstractDateTimeTest { expected = LocalDate.now(Clock.system(zone)); test = LocalDate.now(zone); } - assertEquals(test, expected); + assertEquals(expected, test); } //----------------------------------------------------------------------- // now(Clock) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullClock() { - LocalDate.now((Clock) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDate.now((Clock) null)); } @Test @@ -276,9 +281,9 @@ public class TCKLocalDate extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); LocalDate test = LocalDate.now(clock); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60 ? 1 : 2)); + assertEquals(1970, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals((i < 24 * 60 * 60 ? 1 : 2), test.getDayOfMonth()); } } @@ -288,9 +293,9 @@ public class TCKLocalDate extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i); Clock clock = Clock.fixed(instant.minusSeconds(OFFSET_PONE.getTotalSeconds()), OFFSET_PONE); LocalDate test = LocalDate.now(clock); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60) ? 1 : 2); + assertEquals(1970, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals((i < 24 * 60 * 60) ? 1 : 2, test.getDayOfMonth()); } } @@ -300,9 +305,9 @@ public class TCKLocalDate extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); LocalDate test = LocalDate.now(clock); - assertEquals(test.getYear(), 1969); - assertEquals(test.getMonth(), Month.DECEMBER); - assertEquals(test.getDayOfMonth(), (i >= -24 * 60 * 60 ? 31 : 30)); + assertEquals(1969, test.getYear()); + assertEquals(Month.DECEMBER, test.getMonth()); + assertEquals((i >= -24 * 60 * 60 ? 31 : 30), test.getDayOfMonth()); } } @@ -311,26 +316,30 @@ public class TCKLocalDate extends AbstractDateTimeTest { public void now_Clock_maxYear() { Clock clock = Clock.fixed(MAX_INSTANT, ZoneOffset.UTC); LocalDate test = LocalDate.now(clock); - assertEquals(test, MAX_DATE); + assertEquals(MAX_DATE, test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void now_Clock_tooBig() { - Clock clock = Clock.fixed(MAX_INSTANT.plusSeconds(24 * 60 * 60), ZoneOffset.UTC); - LocalDate.now(clock); + Assertions.assertThrows(DateTimeException.class, () -> { + Clock clock = Clock.fixed(MAX_INSTANT.plusSeconds(24 * 60 * 60), ZoneOffset.UTC); + LocalDate.now(clock); + }); } @Test public void now_Clock_minYear() { Clock clock = Clock.fixed(MIN_INSTANT, ZoneOffset.UTC); LocalDate test = LocalDate.now(clock); - assertEquals(test, MIN_DATE); + assertEquals(MIN_DATE, test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void now_Clock_tooLow() { - Clock clock = Clock.fixed(MIN_INSTANT.minusNanos(1), ZoneOffset.UTC); - LocalDate.now(clock); + Assertions.assertThrows(DateTimeException.class, () -> { + Clock clock = Clock.fixed(MIN_INSTANT.minusNanos(1), ZoneOffset.UTC); + LocalDate.now(clock); + }); } //----------------------------------------------------------------------- @@ -338,37 +347,37 @@ public class TCKLocalDate extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void factory_of_intsMonth() { - assertEquals(TEST_2007_07_15, LocalDate.of(2007, Month.JULY, 15)); + assertEquals(LocalDate.of(2007, Month.JULY, 15), TEST_2007_07_15); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_intsMonth_29febNonLeap() { - LocalDate.of(2007, Month.FEBRUARY, 29); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, Month.FEBRUARY, 29)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_intsMonth_31apr() { - LocalDate.of(2007, Month.APRIL, 31); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, Month.APRIL, 31)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_intsMonth_dayTooLow() { - LocalDate.of(2007, Month.JANUARY, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, Month.JANUARY, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_intsMonth_dayTooHigh() { - LocalDate.of(2007, Month.JANUARY, 32); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, Month.JANUARY, 32)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_intsMonth_nullMonth() { - LocalDate.of(2007, null, 30); + Assertions.assertThrows(NullPointerException.class, () -> LocalDate.of(2007, null, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_intsMonth_yearTooLow() { - LocalDate.of(Integer.MIN_VALUE, Month.JANUARY, 1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Integer.MIN_VALUE, Month.JANUARY, 1)); } //----------------------------------------------------------------------- @@ -377,39 +386,39 @@ public class TCKLocalDate extends AbstractDateTimeTest { check(TEST_2007_07_15, 2007, 7, 15); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_ints_29febNonLeap() { - LocalDate.of(2007, 2, 29); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, 2, 29)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_ints_31apr() { - LocalDate.of(2007, 4, 31); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, 4, 31)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_ints_dayTooLow() { - LocalDate.of(2007, 1, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, 1, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_ints_dayTooHigh() { - LocalDate.of(2007, 1, 32); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, 1, 32)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_ints_monthTooLow() { - LocalDate.of(2007, 0, 1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, 0, 1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_ints_monthTooHigh() { - LocalDate.of(2007, 13, 1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, 13, 1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_ints_yearTooLow() { - LocalDate.of(Integer.MIN_VALUE, 1, 1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Integer.MIN_VALUE, 1, 1)); } //----------------------------------------------------------------------- @@ -417,7 +426,7 @@ public class TCKLocalDate extends AbstractDateTimeTest { public void factory_ofYearDay_ints_nonLeap() { LocalDate date = LocalDate.of(2007, 1, 1); for (int i = 1; i < 365; i++) { - assertEquals(LocalDate.ofYearDay(2007, i), date); + assertEquals(date, LocalDate.ofYearDay(2007, i)); date = next(date); } } @@ -426,29 +435,29 @@ public class TCKLocalDate extends AbstractDateTimeTest { public void factory_ofYearDay_ints_leap() { LocalDate date = LocalDate.of(2008, 1, 1); for (int i = 1; i < 366; i++) { - assertEquals(LocalDate.ofYearDay(2008, i), date); + assertEquals(date, LocalDate.ofYearDay(2008, i)); date = next(date); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofYearDay_ints_366nonLeap() { - LocalDate.ofYearDay(2007, 366); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.ofYearDay(2007, 366)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofYearDay_ints_dayTooLow() { - LocalDate.ofYearDay(2007, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.ofYearDay(2007, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofYearDay_ints_dayTooHigh() { - LocalDate.ofYearDay(2007, 367); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.ofYearDay(2007, 367)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofYearDay_ints_yearTooLow() { - LocalDate.ofYearDay(Integer.MIN_VALUE, 1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.ofYearDay(Integer.MIN_VALUE, 1)); } //----------------------------------------------------------------------- @@ -480,7 +489,6 @@ public class TCKLocalDate extends AbstractDateTimeTest { //----------------------------------------------------------------------- // ofInstant() //----------------------------------------------------------------------- - @DataProvider(name="instantFactory") Object[][] data_instantFactory() { return new Object[][] { {Instant.ofEpochSecond(86400 + 3600 + 120 + 4, 500), ZONE_PARIS, LocalDate.of(1970, 1, 2)}, @@ -493,30 +501,31 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider="instantFactory") + @ParameterizedTest + @MethodSource("data_instantFactory") public void factory_ofInstant(Instant instant, ZoneId zone, LocalDate expected) { LocalDate test = LocalDate.ofInstant(instant, zone); - assertEquals(test, expected); + assertEquals(expected, test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_instantTooBig() { - LocalDate.ofInstant(Instant.MAX, OFFSET_PONE); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.ofInstant(Instant.MAX, OFFSET_PONE)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_instantTooSmall() { - LocalDate.ofInstant(Instant.MIN, OFFSET_PONE); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.ofInstant(Instant.MIN, OFFSET_PONE)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_nullInstant() { - LocalDate.ofInstant((Instant) null, ZONE_GAZA); + Assertions.assertThrows(NullPointerException.class, () -> LocalDate.ofInstant((Instant) null, ZONE_GAZA)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_nullZone() { - LocalDate.ofInstant(Instant.EPOCH, (ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDate.ofInstant(Instant.EPOCH, (ZoneId) null)); } //----------------------------------------------------------------------- @@ -525,32 +534,32 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void factory_ofEpochDay() { long date_0000_01_01 = -678941 - 40587; - assertEquals(LocalDate.ofEpochDay(0), LocalDate.of(1970, 1, 1)); - assertEquals(LocalDate.ofEpochDay(date_0000_01_01), LocalDate.of(0, 1, 1)); - assertEquals(LocalDate.ofEpochDay(date_0000_01_01 - 1), LocalDate.of(-1, 12, 31)); - assertEquals(LocalDate.ofEpochDay(MAX_VALID_EPOCHDAYS), LocalDate.of(Year.MAX_VALUE, 12, 31)); - assertEquals(LocalDate.ofEpochDay(MIN_VALID_EPOCHDAYS), LocalDate.of(Year.MIN_VALUE, 1, 1)); + assertEquals(LocalDate.of(1970, 1, 1), LocalDate.ofEpochDay(0)); + assertEquals(LocalDate.of(0, 1, 1), LocalDate.ofEpochDay(date_0000_01_01)); + assertEquals(LocalDate.of(-1, 12, 31), LocalDate.ofEpochDay(date_0000_01_01 - 1)); + assertEquals(LocalDate.of(Year.MAX_VALUE, 12, 31), LocalDate.ofEpochDay(MAX_VALID_EPOCHDAYS)); + assertEquals(LocalDate.of(Year.MIN_VALUE, 1, 1), LocalDate.ofEpochDay(MIN_VALID_EPOCHDAYS)); LocalDate test = LocalDate.of(0, 1, 1); for (long i = date_0000_01_01; i < 700000; i++) { - assertEquals(LocalDate.ofEpochDay(i), test); + assertEquals(test, LocalDate.ofEpochDay(i)); test = next(test); } test = LocalDate.of(0, 1, 1); for (long i = date_0000_01_01; i > -2000000; i--) { - assertEquals(LocalDate.ofEpochDay(i), test); + assertEquals(test, LocalDate.ofEpochDay(i)); test = previous(test); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofEpochDay_aboveMax() { - LocalDate.ofEpochDay(MAX_VALID_EPOCHDAYS + 1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.ofEpochDay(MAX_VALID_EPOCHDAYS + 1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofEpochDay_belowMin() { - LocalDate.ofEpochDay(MIN_VALID_EPOCHDAYS - 1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.ofEpochDay(MIN_VALID_EPOCHDAYS - 1)); } //----------------------------------------------------------------------- @@ -558,33 +567,33 @@ public class TCKLocalDate extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_from_TemporalAccessor() { - assertEquals(LocalDate.from(LocalDate.of(2007, 7, 15)), LocalDate.of(2007, 7, 15)); - assertEquals(LocalDate.from(LocalDateTime.of(2007, 7, 15, 12, 30)), LocalDate.of(2007, 7, 15)); + assertEquals(LocalDate.of(2007, 7, 15), LocalDate.from(LocalDate.of(2007, 7, 15))); + assertEquals(LocalDate.of(2007, 7, 15), LocalDate.from(LocalDateTime.of(2007, 7, 15, 12, 30))); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_from_TemporalAccessor_invalid_noDerive() { - LocalDate.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_from_TemporalAccessor_null() { - LocalDate.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDate.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- // parse() //----------------------------------------------------------------------- - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void factory_parse_validText(int y, int m, int d, String parsable) { LocalDate t = LocalDate.parse(parsable); assertNotNull(t, parsable); - assertEquals(t.getYear(), y, parsable); - assertEquals(t.getMonth().getValue(), m, parsable); - assertEquals(t.getDayOfMonth(), d, parsable); + assertEquals(y, t.getYear(), parsable); + assertEquals(m, t.getMonth().getValue(), parsable); + assertEquals(d, t.getDayOfMonth(), parsable); } - @DataProvider(name="sampleBadParse") Object[][] provider_sampleBadParse() { return new Object[][]{ {"2008/07/05"}, @@ -601,24 +610,25 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleBadParse", expectedExceptions={DateTimeParseException.class}) + @ParameterizedTest + @MethodSource("provider_sampleBadParse") public void factory_parse_invalidText(String unparsable) { - LocalDate.parse(unparsable); + Assertions.assertThrows(DateTimeParseException.class, () -> LocalDate.parse(unparsable)); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_illegalValue() { - LocalDate.parse("2008-06-32"); + Assertions.assertThrows(DateTimeParseException.class, () -> LocalDate.parse("2008-06-32")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_invalidValue() { - LocalDate.parse("2008-06-31"); + Assertions.assertThrows(DateTimeParseException.class, () -> LocalDate.parse("2008-06-31")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_nullText() { - LocalDate.parse((String) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDate.parse((String) null)); } //----------------------------------------------------------------------- @@ -628,18 +638,20 @@ public class TCKLocalDate extends AbstractDateTimeTest { public void factory_parse_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d"); LocalDate test = LocalDate.parse("2010 12 3", f); - assertEquals(test, LocalDate.of(2010, 12, 3)); + assertEquals(LocalDate.of(2010, 12, 3), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullText() { - DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d"); - LocalDate.parse((String) null, f); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d"); + LocalDate.parse((String) null, f); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullFormatter() { - LocalDate.parse("ANY", null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDate.parse("ANY", null)); } //----------------------------------------------------------------------- @@ -647,37 +659,37 @@ public class TCKLocalDate extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(TEST_2007_07_15.isSupported((TemporalField) null), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.NANO_OF_SECOND), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.NANO_OF_DAY), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.MICRO_OF_SECOND), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.MICRO_OF_DAY), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.MILLI_OF_SECOND), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.MILLI_OF_DAY), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.SECOND_OF_MINUTE), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.SECOND_OF_DAY), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.MINUTE_OF_HOUR), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.MINUTE_OF_DAY), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.HOUR_OF_AMPM), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.HOUR_OF_DAY), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.AMPM_OF_DAY), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.DAY_OF_WEEK), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.DAY_OF_MONTH), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.DAY_OF_YEAR), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.EPOCH_DAY), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.MONTH_OF_YEAR), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.PROLEPTIC_MONTH), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.YEAR), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.YEAR_OF_ERA), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.ERA), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.INSTANT_SECONDS), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoField.OFFSET_SECONDS), false); + assertEquals(false, TEST_2007_07_15.isSupported((TemporalField) null)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.YEAR)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoField.ERA)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -685,23 +697,23 @@ public class TCKLocalDate extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalUnit() { - assertEquals(TEST_2007_07_15.isSupported((TemporalUnit) null), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.NANOS), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.MICROS), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.MILLIS), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.SECONDS), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.MINUTES), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.HOURS), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.HALF_DAYS), false); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.DAYS), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.WEEKS), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.MONTHS), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.YEARS), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.DECADES), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.CENTURIES), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.MILLENNIA), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.ERAS), true); - assertEquals(TEST_2007_07_15.isSupported(ChronoUnit.FOREVER), false); + assertEquals(false, TEST_2007_07_15.isSupported((TemporalUnit) null)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoUnit.NANOS)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoUnit.MICROS)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoUnit.MILLIS)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoUnit.SECONDS)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoUnit.MINUTES)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoUnit.HOURS)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoUnit.HALF_DAYS)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoUnit.DAYS)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoUnit.WEEKS)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoUnit.MONTHS)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoUnit.YEARS)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoUnit.DECADES)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoUnit.CENTURIES)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoUnit.MILLENNIA)); + assertEquals(true, TEST_2007_07_15.isSupported(ChronoUnit.ERAS)); + assertEquals(false, TEST_2007_07_15.isSupported(ChronoUnit.FOREVER)); } //----------------------------------------------------------------------- @@ -710,32 +722,31 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_get_TemporalField() { LocalDate test = LocalDate.of(2008, 6, 30); - assertEquals(test.get(YEAR), 2008); - assertEquals(test.get(MONTH_OF_YEAR), 6); - assertEquals(test.get(YEAR_OF_ERA), 2008); - assertEquals(test.get(ERA), 1); - assertEquals(test.get(DAY_OF_MONTH), 30); - assertEquals(test.get(DAY_OF_WEEK), 1); - assertEquals(test.get(DAY_OF_YEAR), 182); + assertEquals(2008, test.get(YEAR)); + assertEquals(6, test.get(MONTH_OF_YEAR)); + assertEquals(2008, test.get(YEAR_OF_ERA)); + assertEquals(1, test.get(ERA)); + assertEquals(30, test.get(DAY_OF_MONTH)); + assertEquals(1, test.get(DAY_OF_WEEK)); + assertEquals(182, test.get(DAY_OF_YEAR)); } @Test public void test_getLong_TemporalField() { LocalDate test = LocalDate.of(2008, 6, 30); - assertEquals(test.getLong(YEAR), 2008); - assertEquals(test.getLong(MONTH_OF_YEAR), 6); - assertEquals(test.getLong(YEAR_OF_ERA), 2008); - assertEquals(test.getLong(ERA), 1); - assertEquals(test.getLong(PROLEPTIC_MONTH), 2008 * 12 + 6 - 1); - assertEquals(test.getLong(DAY_OF_MONTH), 30); - assertEquals(test.getLong(DAY_OF_WEEK), 1); - assertEquals(test.getLong(DAY_OF_YEAR), 182); + assertEquals(2008, test.getLong(YEAR)); + assertEquals(6, test.getLong(MONTH_OF_YEAR)); + assertEquals(2008, test.getLong(YEAR_OF_ERA)); + assertEquals(1, test.getLong(ERA)); + assertEquals(2008 * 12 + 6 - 1, test.getLong(PROLEPTIC_MONTH)); + assertEquals(30, test.getLong(DAY_OF_MONTH)); + assertEquals(1, test.getLong(DAY_OF_WEEK)); + assertEquals(182, test.getLong(DAY_OF_YEAR)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {TEST_2007_07_15, TemporalQueries.chronology(), IsoChronology.INSTANCE}, @@ -748,25 +759,26 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - TEST_2007_07_15.query(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.query(null)); } //----------------------------------------------------------------------- // get*() //----------------------------------------------------------------------- - @DataProvider(name="sampleDates") Object[][] provider_sampleDates() { return new Object[][] { {2008, 7, 5}, @@ -779,15 +791,17 @@ public class TCKLocalDate extends AbstractDateTimeTest { } //----------------------------------------------------------------------- - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_get(int y, int m, int d) { LocalDate a = LocalDate.of(y, m, d); - assertEquals(a.getYear(), y); - assertEquals(a.getMonth(), Month.of(m)); - assertEquals(a.getDayOfMonth(), d); + assertEquals(y, a.getYear()); + assertEquals(Month.of(m), a.getMonth()); + assertEquals(d, a.getDayOfMonth()); } - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_getDOY(int y, int m, int d) { LocalDate a = LocalDate.of(y, m, d); int total = 0; @@ -795,7 +809,7 @@ public class TCKLocalDate extends AbstractDateTimeTest { total += Month.of(i).length(isIsoLeap(y)); } int doy = total + d; - assertEquals(a.getDayOfYear(), doy); + assertEquals(doy, a.getDayOfYear()); } @Test @@ -816,19 +830,19 @@ public class TCKLocalDate extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isLeapYear() { - assertEquals(LocalDate.of(1999, 1, 1).isLeapYear(), false); - assertEquals(LocalDate.of(2000, 1, 1).isLeapYear(), true); - assertEquals(LocalDate.of(2001, 1, 1).isLeapYear(), false); - assertEquals(LocalDate.of(2002, 1, 1).isLeapYear(), false); - assertEquals(LocalDate.of(2003, 1, 1).isLeapYear(), false); - assertEquals(LocalDate.of(2004, 1, 1).isLeapYear(), true); - assertEquals(LocalDate.of(2005, 1, 1).isLeapYear(), false); + assertEquals(false, LocalDate.of(1999, 1, 1).isLeapYear()); + assertEquals(true, LocalDate.of(2000, 1, 1).isLeapYear()); + assertEquals(false, LocalDate.of(2001, 1, 1).isLeapYear()); + assertEquals(false, LocalDate.of(2002, 1, 1).isLeapYear()); + assertEquals(false, LocalDate.of(2003, 1, 1).isLeapYear()); + assertEquals(true, LocalDate.of(2004, 1, 1).isLeapYear()); + assertEquals(false, LocalDate.of(2005, 1, 1).isLeapYear()); - assertEquals(LocalDate.of(1500, 1, 1).isLeapYear(), false); - assertEquals(LocalDate.of(1600, 1, 1).isLeapYear(), true); - assertEquals(LocalDate.of(1700, 1, 1).isLeapYear(), false); - assertEquals(LocalDate.of(1800, 1, 1).isLeapYear(), false); - assertEquals(LocalDate.of(1900, 1, 1).isLeapYear(), false); + assertEquals(false, LocalDate.of(1500, 1, 1).isLeapYear()); + assertEquals(true, LocalDate.of(1600, 1, 1).isLeapYear()); + assertEquals(false, LocalDate.of(1700, 1, 1).isLeapYear()); + assertEquals(false, LocalDate.of(1800, 1, 1).isLeapYear()); + assertEquals(false, LocalDate.of(1900, 1, 1).isLeapYear()); } //----------------------------------------------------------------------- @@ -836,34 +850,34 @@ public class TCKLocalDate extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_lengthOfMonth_notLeapYear() { - assertEquals(LocalDate.of(2007, 1, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2007, 2, 1).lengthOfMonth(), 28); - assertEquals(LocalDate.of(2007, 3, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2007, 4, 1).lengthOfMonth(), 30); - assertEquals(LocalDate.of(2007, 5, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2007, 6, 1).lengthOfMonth(), 30); - assertEquals(LocalDate.of(2007, 7, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2007, 8, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2007, 9, 1).lengthOfMonth(), 30); - assertEquals(LocalDate.of(2007, 10, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2007, 11, 1).lengthOfMonth(), 30); - assertEquals(LocalDate.of(2007, 12, 1).lengthOfMonth(), 31); + assertEquals(31, LocalDate.of(2007, 1, 1).lengthOfMonth()); + assertEquals(28, LocalDate.of(2007, 2, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2007, 3, 1).lengthOfMonth()); + assertEquals(30, LocalDate.of(2007, 4, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2007, 5, 1).lengthOfMonth()); + assertEquals(30, LocalDate.of(2007, 6, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2007, 7, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2007, 8, 1).lengthOfMonth()); + assertEquals(30, LocalDate.of(2007, 9, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2007, 10, 1).lengthOfMonth()); + assertEquals(30, LocalDate.of(2007, 11, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2007, 12, 1).lengthOfMonth()); } @Test public void test_lengthOfMonth_leapYear() { - assertEquals(LocalDate.of(2008, 1, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2008, 2, 1).lengthOfMonth(), 29); - assertEquals(LocalDate.of(2008, 3, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2008, 4, 1).lengthOfMonth(), 30); - assertEquals(LocalDate.of(2008, 5, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2008, 6, 1).lengthOfMonth(), 30); - assertEquals(LocalDate.of(2008, 7, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2008, 8, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2008, 9, 1).lengthOfMonth(), 30); - assertEquals(LocalDate.of(2008, 10, 1).lengthOfMonth(), 31); - assertEquals(LocalDate.of(2008, 11, 1).lengthOfMonth(), 30); - assertEquals(LocalDate.of(2008, 12, 1).lengthOfMonth(), 31); + assertEquals(31, LocalDate.of(2008, 1, 1).lengthOfMonth()); + assertEquals(29, LocalDate.of(2008, 2, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2008, 3, 1).lengthOfMonth()); + assertEquals(30, LocalDate.of(2008, 4, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2008, 5, 1).lengthOfMonth()); + assertEquals(30, LocalDate.of(2008, 6, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2008, 7, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2008, 8, 1).lengthOfMonth()); + assertEquals(30, LocalDate.of(2008, 9, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2008, 10, 1).lengthOfMonth()); + assertEquals(30, LocalDate.of(2008, 11, 1).lengthOfMonth()); + assertEquals(31, LocalDate.of(2008, 12, 1).lengthOfMonth()); } //----------------------------------------------------------------------- @@ -871,8 +885,8 @@ public class TCKLocalDate extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_lengthOfYear() { - assertEquals(LocalDate.of(2007, 1, 1).lengthOfYear(), 365); - assertEquals(LocalDate.of(2008, 1, 1).lengthOfYear(), 366); + assertEquals(365, LocalDate.of(2007, 1, 1).lengthOfYear()); + assertEquals(366, LocalDate.of(2008, 1, 1).lengthOfYear()); } //----------------------------------------------------------------------- @@ -887,12 +901,12 @@ public class TCKLocalDate extends AbstractDateTimeTest { return sample; } }; - assertEquals(TEST_2007_07_15.with(adjuster), sample); + assertEquals(sample, TEST_2007_07_15.with(adjuster)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_with_adjustment_null() { - TEST_2007_07_15.with((TemporalAdjuster) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.with((TemporalAdjuster) null)); } //----------------------------------------------------------------------- @@ -901,27 +915,27 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_with_TemporalField_long_normal() { LocalDate t = TEST_2007_07_15.with(YEAR, 2008); - assertEquals(t, LocalDate.of(2008, 7, 15)); + assertEquals(LocalDate.of(2008, 7, 15), t); } - @Test(expectedExceptions=NullPointerException.class ) + @Test public void test_with_TemporalField_long_null() { - TEST_2007_07_15.with((TemporalField) null, 1); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.with((TemporalField) null, 1)); } - @Test(expectedExceptions=DateTimeException.class ) + @Test public void test_with_TemporalField_long_invalidField() { - TEST_2007_07_15.with(MockFieldNoValue.INSTANCE, 1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15.with(MockFieldNoValue.INSTANCE, 1)); } - @Test(expectedExceptions=DateTimeException.class ) + @Test public void test_with_TemporalField_long_timeField() { - TEST_2007_07_15.with(ChronoField.AMPM_OF_DAY, 1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15.with(ChronoField.AMPM_OF_DAY, 1)); } - @Test(expectedExceptions=DateTimeException.class ) + @Test public void test_with_TemporalField_long_invalidValue() { - TEST_2007_07_15.with(ChronoField.DAY_OF_WEEK, -1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15.with(ChronoField.DAY_OF_WEEK, -1)); } //----------------------------------------------------------------------- @@ -930,19 +944,19 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_withYear_int_normal() { LocalDate t = TEST_2007_07_15.withYear(2008); - assertEquals(t, LocalDate.of(2008, 7, 15)); + assertEquals(LocalDate.of(2008, 7, 15), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withYear_int_invalid() { - TEST_2007_07_15.withYear(Year.MIN_VALUE - 1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15.withYear(Year.MIN_VALUE - 1)); } @Test public void test_withYear_int_adjustDay() { LocalDate t = LocalDate.of(2008, 2, 29).withYear(2007); LocalDate expected = LocalDate.of(2007, 2, 28); - assertEquals(t, expected); + assertEquals(expected, t); } //----------------------------------------------------------------------- @@ -951,19 +965,19 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_withMonth_int_normal() { LocalDate t = TEST_2007_07_15.withMonth(1); - assertEquals(t, LocalDate.of(2007, 1, 15)); + assertEquals(LocalDate.of(2007, 1, 15), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMonth_int_invalid() { - TEST_2007_07_15.withMonth(13); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15.withMonth(13)); } @Test public void test_withMonth_int_adjustDay() { LocalDate t = LocalDate.of(2007, 12, 31).withMonth(11); LocalDate expected = LocalDate.of(2007, 11, 30); - assertEquals(t, expected); + assertEquals(expected, t); } //----------------------------------------------------------------------- @@ -972,17 +986,17 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_withDayOfMonth_normal() { LocalDate t = TEST_2007_07_15.withDayOfMonth(1); - assertEquals(t, LocalDate.of(2007, 7, 1)); + assertEquals(LocalDate.of(2007, 7, 1), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfMonth_illegal() { - TEST_2007_07_15.withDayOfMonth(32); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15.withDayOfMonth(32)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfMonth_invalid() { - LocalDate.of(2007, 11, 30).withDayOfMonth(31); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(2007, 11, 30).withDayOfMonth(31)); } //----------------------------------------------------------------------- @@ -991,17 +1005,17 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_withDayOfYear_normal() { LocalDate t = TEST_2007_07_15.withDayOfYear(33); - assertEquals(t, LocalDate.of(2007, 2, 2)); + assertEquals(LocalDate.of(2007, 2, 2), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfYear_illegal() { - TEST_2007_07_15.withDayOfYear(367); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15.withDayOfYear(367)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfYear_invalid() { - TEST_2007_07_15.withDayOfYear(366); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15.withDayOfYear(366)); } //----------------------------------------------------------------------- @@ -1011,37 +1025,43 @@ public class TCKLocalDate extends AbstractDateTimeTest { public void test_plus_Period_positiveMonths() { MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.MONTHS); LocalDate t = TEST_2007_07_15.plus(period); - assertEquals(t, LocalDate.of(2008, 2, 15)); + assertEquals(LocalDate.of(2008, 2, 15), t); } @Test public void test_plus_Period_negativeDays() { MockSimplePeriod period = MockSimplePeriod.of(-25, ChronoUnit.DAYS); LocalDate t = TEST_2007_07_15.plus(period); - assertEquals(t, LocalDate.of(2007, 6, 20)); + assertEquals(LocalDate.of(2007, 6, 20), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_Period_timeNotAllowed() { - MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.HOURS); - TEST_2007_07_15.plus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.HOURS); + TEST_2007_07_15.plus(period); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_Period_null() { - TEST_2007_07_15.plus((MockSimplePeriod) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.plus((MockSimplePeriod) null)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_Period_invalidTooLarge() { - MockSimplePeriod period = MockSimplePeriod.of(1, ChronoUnit.YEARS); - LocalDate.of(Year.MAX_VALUE, 1, 1).plus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + MockSimplePeriod period = MockSimplePeriod.of(1, ChronoUnit.YEARS); + LocalDate.of(Year.MAX_VALUE, 1, 1).plus(period); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_Period_invalidTooSmall() { - MockSimplePeriod period = MockSimplePeriod.of(-1, ChronoUnit.YEARS); - LocalDate.of(Year.MIN_VALUE, 1, 1).plus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + MockSimplePeriod period = MockSimplePeriod.of(-1, ChronoUnit.YEARS); + LocalDate.of(Year.MIN_VALUE, 1, 1).plus(period); + }); } //----------------------------------------------------------------------- @@ -1050,33 +1070,33 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_plus_longTemporalUnit_positiveMonths() { LocalDate t = TEST_2007_07_15.plus(7, ChronoUnit.MONTHS); - assertEquals(t, LocalDate.of(2008, 2, 15)); + assertEquals(LocalDate.of(2008, 2, 15), t); } @Test public void test_plus_longTemporalUnit_negativeDays() { LocalDate t = TEST_2007_07_15.plus(-25, ChronoUnit.DAYS); - assertEquals(t, LocalDate.of(2007, 6, 20)); + assertEquals(LocalDate.of(2007, 6, 20), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_longTemporalUnit_timeNotAllowed() { - TEST_2007_07_15.plus(7, ChronoUnit.HOURS); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15.plus(7, ChronoUnit.HOURS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_longTemporalUnit_null() { - TEST_2007_07_15.plus(1, (TemporalUnit) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.plus(1, (TemporalUnit) null)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_longTemporalUnit_invalidTooLarge() { - LocalDate.of(Year.MAX_VALUE, 1, 1).plus(1, ChronoUnit.YEARS); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MAX_VALUE, 1, 1).plus(1, ChronoUnit.YEARS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_longTemporalUnit_invalidTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 1).plus(-1, ChronoUnit.YEARS); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).plus(-1, ChronoUnit.YEARS)); } //----------------------------------------------------------------------- @@ -1085,55 +1105,61 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_plusYears_long_normal() { LocalDate t = TEST_2007_07_15.plusYears(1); - assertEquals(t, LocalDate.of(2008, 7, 15)); + assertEquals(LocalDate.of(2008, 7, 15), t); } @Test public void test_plusYears_long_negative() { LocalDate t = TEST_2007_07_15.plusYears(-1); - assertEquals(t, LocalDate.of(2006, 7, 15)); + assertEquals(LocalDate.of(2006, 7, 15), t); } @Test public void test_plusYears_long_adjustDay() { LocalDate t = LocalDate.of(2008, 2, 29).plusYears(1); LocalDate expected = LocalDate.of(2009, 2, 28); - assertEquals(t, expected); + assertEquals(expected, t); } @Test public void test_plusYears_long_big() { long years = 20L + Year.MAX_VALUE; LocalDate test = LocalDate.of(-40, 6, 1).plusYears(years); - assertEquals(test, LocalDate.of((int) (-40L + years), 6, 1)); + assertEquals(LocalDate.of((int) (-40L + years), 6, 1), test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_long_invalidTooLarge() { - LocalDate test = LocalDate.of(Year.MAX_VALUE, 6, 1); - test.plusYears(1); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate test = LocalDate.of(Year.MAX_VALUE, 6, 1); + test.plusYears(1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_long_invalidTooLargeMaxAddMax() { - LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); - test.plusYears(Long.MAX_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); + test.plusYears(Long.MAX_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_long_invalidTooLargeMaxAddMin() { - LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); - test.plusYears(Long.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); + test.plusYears(Long.MIN_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_long_invalidTooSmall_validInt() { - LocalDate.of(Year.MIN_VALUE, 1, 1).plusYears(-1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).plusYears(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_long_invalidTooSmall_invalidInt() { - LocalDate.of(Year.MIN_VALUE, 1, 1).plusYears(-10); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).plusYears(-10)); } //----------------------------------------------------------------------- @@ -1142,153 +1168,156 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_plusMonths_long_normal() { LocalDate t = TEST_2007_07_15.plusMonths(1); - assertEquals(t, LocalDate.of(2007, 8, 15)); + assertEquals(LocalDate.of(2007, 8, 15), t); } @Test public void test_plusMonths_long_overYears() { LocalDate t = TEST_2007_07_15.plusMonths(25); - assertEquals(t, LocalDate.of(2009, 8, 15)); + assertEquals(LocalDate.of(2009, 8, 15), t); } @Test public void test_plusMonths_long_negative() { LocalDate t = TEST_2007_07_15.plusMonths(-1); - assertEquals(t, LocalDate.of(2007, 6, 15)); + assertEquals(LocalDate.of(2007, 6, 15), t); } @Test public void test_plusMonths_long_negativeAcrossYear() { LocalDate t = TEST_2007_07_15.plusMonths(-7); - assertEquals(t, LocalDate.of(2006, 12, 15)); + assertEquals(LocalDate.of(2006, 12, 15), t); } @Test public void test_plusMonths_long_negativeOverYears() { LocalDate t = TEST_2007_07_15.plusMonths(-31); - assertEquals(t, LocalDate.of(2004, 12, 15)); + assertEquals(LocalDate.of(2004, 12, 15), t); } @Test public void test_plusMonths_long_adjustDayFromLeapYear() { LocalDate t = LocalDate.of(2008, 2, 29).plusMonths(12); LocalDate expected = LocalDate.of(2009, 2, 28); - assertEquals(t, expected); + assertEquals(expected, t); } @Test public void test_plusMonths_long_adjustDayFromMonthLength() { LocalDate t = LocalDate.of(2007, 3, 31).plusMonths(1); LocalDate expected = LocalDate.of(2007, 4, 30); - assertEquals(t, expected); + assertEquals(expected, t); } @Test public void test_plusMonths_long_big() { long months = 20L + Integer.MAX_VALUE; LocalDate test = LocalDate.of(-40, 6, 1).plusMonths(months); - assertEquals(test, LocalDate.of((int) (-40L + months / 12), 6 + (int) (months % 12), 1)); + assertEquals(LocalDate.of((int) (-40L + months / 12), 6 + (int) (months % 12), 1), test); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_plusMonths_long_invalidTooLarge() { - LocalDate.of(Year.MAX_VALUE, 12, 1).plusMonths(1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 1).plusMonths(1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusMonths_long_invalidTooLargeMaxAddMax() { - LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); - test.plusMonths(Long.MAX_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); + test.plusMonths(Long.MAX_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusMonths_long_invalidTooLargeMaxAddMin() { - LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); - test.plusMonths(Long.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); + test.plusMonths(Long.MIN_VALUE); + }); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_plusMonths_long_invalidTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 1).plusMonths(-1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).plusMonths(-1)); } @Test public void test_plusWeeks_normal() { LocalDate t = TEST_2007_07_15.plusWeeks(1); - assertEquals(t, LocalDate.of(2007, 7, 22)); + assertEquals(LocalDate.of(2007, 7, 22), t); } @Test public void test_plusWeeks_overMonths() { LocalDate t = TEST_2007_07_15.plusWeeks(9); - assertEquals(t, LocalDate.of(2007, 9, 16)); + assertEquals(LocalDate.of(2007, 9, 16), t); } @Test public void test_plusWeeks_overYears() { LocalDate t = LocalDate.of(2006, 7, 16).plusWeeks(52); - assertEquals(t, TEST_2007_07_15); + assertEquals(TEST_2007_07_15, t); } @Test public void test_plusWeeks_overLeapYears() { LocalDate t = TEST_2007_07_15.plusYears(-1).plusWeeks(104); - assertEquals(t, LocalDate.of(2008, 7, 12)); + assertEquals(LocalDate.of(2008, 7, 12), t); } @Test public void test_plusWeeks_negative() { LocalDate t = TEST_2007_07_15.plusWeeks(-1); - assertEquals(t, LocalDate.of(2007, 7, 8)); + assertEquals(LocalDate.of(2007, 7, 8), t); } @Test public void test_plusWeeks_negativeAcrossYear() { LocalDate t = TEST_2007_07_15.plusWeeks(-28); - assertEquals(t, LocalDate.of(2006, 12, 31)); + assertEquals(LocalDate.of(2006, 12, 31), t); } @Test public void test_plusWeeks_negativeOverYears() { LocalDate t = TEST_2007_07_15.plusWeeks(-104); - assertEquals(t, LocalDate.of(2005, 7, 17)); + assertEquals(LocalDate.of(2005, 7, 17), t); } @Test public void test_plusWeeks_maximum() { LocalDate t = LocalDate.of(Year.MAX_VALUE, 12, 24).plusWeeks(1); LocalDate expected = LocalDate.of(Year.MAX_VALUE, 12, 31); - assertEquals(t, expected); + assertEquals(expected, t); } @Test public void test_plusWeeks_minimum() { LocalDate t = LocalDate.of(Year.MIN_VALUE, 1, 8).plusWeeks(-1); LocalDate expected = LocalDate.of(Year.MIN_VALUE, 1, 1); - assertEquals(t, expected); + assertEquals(expected, t); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_plusWeeks_invalidTooLarge() { - LocalDate.of(Year.MAX_VALUE, 12, 25).plusWeeks(1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 25).plusWeeks(1)); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_plusWeeks_invalidTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 7).plusWeeks(-1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 7).plusWeeks(-1)); } - @Test(expectedExceptions={ArithmeticException.class}) + @Test public void test_plusWeeks_invalidMaxMinusMax() { - LocalDate.of(Year.MAX_VALUE, 12, 25).plusWeeks(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 25).plusWeeks(Long.MAX_VALUE)); } - @Test(expectedExceptions={ArithmeticException.class}) + @Test public void test_plusWeeks_invalidMaxMinusMin() { - LocalDate.of(Year.MAX_VALUE, 12, 25).plusWeeks(Long.MIN_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 25).plusWeeks(Long.MIN_VALUE)); } //----------------------------------------------------------------------- - @DataProvider(name="PlusDays") Object[][] provider_plusDays() { return new Object[][] { {LocalDate.of(2007, 7, 15), 1, LocalDate.of(2007, 7, 16)}, @@ -1312,80 +1341,81 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider="PlusDays") + @ParameterizedTest + @MethodSource("provider_plusDays") public void test_plusDays_normal(LocalDate input, int amountsToAdd, LocalDate expected) { LocalDate actual = input.plusDays(amountsToAdd); - assertEquals(actual, expected); + assertEquals(expected, actual); } @Test public void test_plusDays_overMonths() { LocalDate t = TEST_2007_07_15.plusDays(62); - assertEquals(t, LocalDate.of(2007, 9, 15)); + assertEquals(LocalDate.of(2007, 9, 15), t); } @Test public void test_plusDays_overYears() { LocalDate t = LocalDate.of(2006, 7, 14).plusDays(366); - assertEquals(t, TEST_2007_07_15); + assertEquals(TEST_2007_07_15, t); } @Test public void test_plusDays_overLeapYears() { LocalDate t = TEST_2007_07_15.plusYears(-1).plusDays(365 + 366); - assertEquals(t, LocalDate.of(2008, 7, 15)); + assertEquals(LocalDate.of(2008, 7, 15), t); } @Test public void test_plusDays_negative() { LocalDate t = TEST_2007_07_15.plusDays(-1); - assertEquals(t, LocalDate.of(2007, 7, 14)); + assertEquals(LocalDate.of(2007, 7, 14), t); } @Test public void test_plusDays_negativeAcrossYear() { LocalDate t = TEST_2007_07_15.plusDays(-196); - assertEquals(t, LocalDate.of(2006, 12, 31)); + assertEquals(LocalDate.of(2006, 12, 31), t); } @Test public void test_plusDays_negativeOverYears() { LocalDate t = TEST_2007_07_15.plusDays(-730); - assertEquals(t, LocalDate.of(2005, 7, 15)); + assertEquals(LocalDate.of(2005, 7, 15), t); } @Test public void test_plusDays_maximum() { LocalDate t = LocalDate.of(Year.MAX_VALUE, 12, 30).plusDays(1); LocalDate expected = LocalDate.of(Year.MAX_VALUE, 12, 31); - assertEquals(t, expected); + assertEquals(expected, t); } @Test public void test_plusDays_minimum() { LocalDate t = LocalDate.of(Year.MIN_VALUE, 1, 2).plusDays(-1); LocalDate expected = LocalDate.of(Year.MIN_VALUE, 1, 1); - assertEquals(t, expected); + assertEquals(expected, t); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_plusDays_invalidTooLarge() { - LocalDate.of(Year.MAX_VALUE, 12, 31).plusDays(1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 31).plusDays(1)); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_plusDays_invalidTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 1).plusDays(-1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).plusDays(-1)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_plusDays_overflowTooLarge() { - LocalDate.of(Year.MAX_VALUE, 12, 31).plusDays(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 31).plusDays(Long.MAX_VALUE)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_plusDays_overflowTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 1).plusDays(Long.MIN_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).plusDays(Long.MIN_VALUE)); } //----------------------------------------------------------------------- @@ -1395,37 +1425,43 @@ public class TCKLocalDate extends AbstractDateTimeTest { public void test_minus_Period_positiveMonths() { MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.MONTHS); LocalDate t = TEST_2007_07_15.minus(period); - assertEquals(t, LocalDate.of(2006, 12, 15)); + assertEquals(LocalDate.of(2006, 12, 15), t); } @Test public void test_minus_Period_negativeDays() { MockSimplePeriod period = MockSimplePeriod.of(-25, ChronoUnit.DAYS); LocalDate t = TEST_2007_07_15.minus(period); - assertEquals(t, LocalDate.of(2007, 8, 9)); + assertEquals(LocalDate.of(2007, 8, 9), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_Period_timeNotAllowed() { - MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.HOURS); - TEST_2007_07_15.minus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.HOURS); + TEST_2007_07_15.minus(period); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_minus_Period_null() { - TEST_2007_07_15.minus((MockSimplePeriod) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.minus((MockSimplePeriod) null)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_Period_invalidTooLarge() { - MockSimplePeriod period = MockSimplePeriod.of(-1, ChronoUnit.YEARS); - LocalDate.of(Year.MAX_VALUE, 1, 1).minus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + MockSimplePeriod period = MockSimplePeriod.of(-1, ChronoUnit.YEARS); + LocalDate.of(Year.MAX_VALUE, 1, 1).minus(period); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_Period_invalidTooSmall() { - MockSimplePeriod period = MockSimplePeriod.of(1, ChronoUnit.YEARS); - LocalDate.of(Year.MIN_VALUE, 1, 1).minus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + MockSimplePeriod period = MockSimplePeriod.of(1, ChronoUnit.YEARS); + LocalDate.of(Year.MIN_VALUE, 1, 1).minus(period); + }); } //----------------------------------------------------------------------- @@ -1434,33 +1470,33 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_minus_longTemporalUnit_positiveMonths() { LocalDate t = TEST_2007_07_15.minus(7, ChronoUnit.MONTHS); - assertEquals(t, LocalDate.of(2006, 12, 15)); + assertEquals(LocalDate.of(2006, 12, 15), t); } @Test public void test_minus_longTemporalUnit_negativeDays() { LocalDate t = TEST_2007_07_15.minus(-25, ChronoUnit.DAYS); - assertEquals(t, LocalDate.of(2007, 8, 9)); + assertEquals(LocalDate.of(2007, 8, 9), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_longTemporalUnit_timeNotAllowed() { - TEST_2007_07_15.minus(7, ChronoUnit.HOURS); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15.minus(7, ChronoUnit.HOURS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_minus_longTemporalUnit_null() { - TEST_2007_07_15.minus(1, (TemporalUnit) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.minus(1, (TemporalUnit) null)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_longTemporalUnit_invalidTooLarge() { - LocalDate.of(Year.MAX_VALUE, 1, 1).minus(-1, ChronoUnit.YEARS); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MAX_VALUE, 1, 1).minus(-1, ChronoUnit.YEARS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_longTemporalUnit_invalidTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 1).minus(1, ChronoUnit.YEARS); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).minus(1, ChronoUnit.YEARS)); } //----------------------------------------------------------------------- @@ -1469,50 +1505,56 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_minusYears_long_normal() { LocalDate t = TEST_2007_07_15.minusYears(1); - assertEquals(t, LocalDate.of(2006, 7, 15)); + assertEquals(LocalDate.of(2006, 7, 15), t); } @Test public void test_minusYears_long_negative() { LocalDate t = TEST_2007_07_15.minusYears(-1); - assertEquals(t, LocalDate.of(2008, 7, 15)); + assertEquals(LocalDate.of(2008, 7, 15), t); } @Test public void test_minusYears_long_adjustDay() { LocalDate t = LocalDate.of(2008, 2, 29).minusYears(1); LocalDate expected = LocalDate.of(2007, 2, 28); - assertEquals(t, expected); + assertEquals(expected, t); } @Test public void test_minusYears_long_big() { long years = 20L + Year.MAX_VALUE; LocalDate test = LocalDate.of(40, 6, 1).minusYears(years); - assertEquals(test, LocalDate.of((int) (40L - years), 6, 1)); + assertEquals(LocalDate.of((int) (40L - years), 6, 1), test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_long_invalidTooLarge() { - LocalDate test = LocalDate.of(Year.MAX_VALUE, 6, 1); - test.minusYears(-1); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate test = LocalDate.of(Year.MAX_VALUE, 6, 1); + test.minusYears(-1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_long_invalidTooLargeMaxAddMax() { - LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); - test.minusYears(Long.MAX_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); + test.minusYears(Long.MAX_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_long_invalidTooLargeMaxAddMin() { - LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); - test.minusYears(Long.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); + test.minusYears(Long.MIN_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_long_invalidTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 1).minusYears(1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).minusYears(1)); } //----------------------------------------------------------------------- @@ -1521,232 +1563,235 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_minusMonths_long_normal() { LocalDate t = TEST_2007_07_15.minusMonths(1); - assertEquals(t, LocalDate.of(2007, 6, 15)); + assertEquals(LocalDate.of(2007, 6, 15), t); } @Test public void test_minusMonths_long_overYears() { LocalDate t = TEST_2007_07_15.minusMonths(25); - assertEquals(t, LocalDate.of(2005, 6, 15)); + assertEquals(LocalDate.of(2005, 6, 15), t); } @Test public void test_minusMonths_long_negative() { LocalDate t = TEST_2007_07_15.minusMonths(-1); - assertEquals(t, LocalDate.of(2007, 8, 15)); + assertEquals(LocalDate.of(2007, 8, 15), t); } @Test public void test_minusMonths_long_negativeAcrossYear() { LocalDate t = TEST_2007_07_15.minusMonths(-7); - assertEquals(t, LocalDate.of(2008, 2, 15)); + assertEquals(LocalDate.of(2008, 2, 15), t); } @Test public void test_minusMonths_long_negativeOverYears() { LocalDate t = TEST_2007_07_15.minusMonths(-31); - assertEquals(t, LocalDate.of(2010, 2, 15)); + assertEquals(LocalDate.of(2010, 2, 15), t); } @Test public void test_minusMonths_long_adjustDayFromLeapYear() { LocalDate t = LocalDate.of(2008, 2, 29).minusMonths(12); LocalDate expected = LocalDate.of(2007, 2, 28); - assertEquals(t, expected); + assertEquals(expected, t); } @Test public void test_minusMonths_long_adjustDayFromMonthLength() { LocalDate t = LocalDate.of(2007, 3, 31).minusMonths(1); LocalDate expected = LocalDate.of(2007, 2, 28); - assertEquals(t, expected); + assertEquals(expected, t); } @Test public void test_minusMonths_long_big() { long months = 20L + Integer.MAX_VALUE; LocalDate test = LocalDate.of(40, 6, 1).minusMonths(months); - assertEquals(test, LocalDate.of((int) (40L - months / 12), 6 - (int) (months % 12), 1)); + assertEquals(LocalDate.of((int) (40L - months / 12), 6 - (int) (months % 12), 1), test); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_minusMonths_long_invalidTooLarge() { - LocalDate.of(Year.MAX_VALUE, 12, 1).minusMonths(-1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 1).minusMonths(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusMonths_long_invalidTooLargeMaxAddMax() { - LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); - test.minusMonths(Long.MAX_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); + test.minusMonths(Long.MAX_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusMonths_long_invalidTooLargeMaxAddMin() { - LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); - test.minusMonths(Long.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate test = LocalDate.of(Year.MAX_VALUE, 12, 1); + test.minusMonths(Long.MIN_VALUE); + }); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_minusMonths_long_invalidTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 1).minusMonths(1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).minusMonths(1)); } @Test public void test_minusWeeks_normal() { LocalDate t = TEST_2007_07_15.minusWeeks(1); - assertEquals(t, LocalDate.of(2007, 7, 8)); + assertEquals(LocalDate.of(2007, 7, 8), t); } @Test public void test_minusWeeks_overMonths() { LocalDate t = TEST_2007_07_15.minusWeeks(9); - assertEquals(t, LocalDate.of(2007, 5, 13)); + assertEquals(LocalDate.of(2007, 5, 13), t); } @Test public void test_minusWeeks_overYears() { LocalDate t = LocalDate.of(2008, 7, 13).minusWeeks(52); - assertEquals(t, TEST_2007_07_15); + assertEquals(TEST_2007_07_15, t); } @Test public void test_minusWeeks_overLeapYears() { LocalDate t = TEST_2007_07_15.minusYears(-1).minusWeeks(104); - assertEquals(t, LocalDate.of(2006, 7, 18)); + assertEquals(LocalDate.of(2006, 7, 18), t); } @Test public void test_minusWeeks_negative() { LocalDate t = TEST_2007_07_15.minusWeeks(-1); - assertEquals(t, LocalDate.of(2007, 7, 22)); + assertEquals(LocalDate.of(2007, 7, 22), t); } @Test public void test_minusWeeks_negativeAcrossYear() { LocalDate t = TEST_2007_07_15.minusWeeks(-28); - assertEquals(t, LocalDate.of(2008, 1, 27)); + assertEquals(LocalDate.of(2008, 1, 27), t); } @Test public void test_minusWeeks_negativeOverYears() { LocalDate t = TEST_2007_07_15.minusWeeks(-104); - assertEquals(t, LocalDate.of(2009, 7, 12)); + assertEquals(LocalDate.of(2009, 7, 12), t); } @Test public void test_minusWeeks_maximum() { LocalDate t = LocalDate.of(Year.MAX_VALUE, 12, 24).minusWeeks(-1); LocalDate expected = LocalDate.of(Year.MAX_VALUE, 12, 31); - assertEquals(t, expected); + assertEquals(expected, t); } @Test public void test_minusWeeks_minimum() { LocalDate t = LocalDate.of(Year.MIN_VALUE, 1, 8).minusWeeks(1); LocalDate expected = LocalDate.of(Year.MIN_VALUE, 1, 1); - assertEquals(t, expected); + assertEquals(expected, t); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_minusWeeks_invalidTooLarge() { - LocalDate.of(Year.MAX_VALUE, 12, 25).minusWeeks(-1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 25).minusWeeks(-1)); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_minusWeeks_invalidTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 7).minusWeeks(1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 7).minusWeeks(1)); } - @Test(expectedExceptions={ArithmeticException.class}) + @Test public void test_minusWeeks_invalidMaxMinusMax() { - LocalDate.of(Year.MAX_VALUE, 12, 25).minusWeeks(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 25).minusWeeks(Long.MAX_VALUE)); } - @Test(expectedExceptions={ArithmeticException.class}) + @Test public void test_minusWeeks_invalidMaxMinusMin() { - LocalDate.of(Year.MAX_VALUE, 12, 25).minusWeeks(Long.MIN_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 25).minusWeeks(Long.MIN_VALUE)); } @Test public void test_minusDays_normal() { LocalDate t = TEST_2007_07_15.minusDays(1); - assertEquals(t, LocalDate.of(2007, 7, 14)); + assertEquals(LocalDate.of(2007, 7, 14), t); } @Test public void test_minusDays_overMonths() { LocalDate t = TEST_2007_07_15.minusDays(62); - assertEquals(t, LocalDate.of(2007, 5, 14)); + assertEquals(LocalDate.of(2007, 5, 14), t); } @Test public void test_minusDays_overYears() { LocalDate t = LocalDate.of(2008, 7, 16).minusDays(367); - assertEquals(t, TEST_2007_07_15); + assertEquals(TEST_2007_07_15, t); } @Test public void test_minusDays_overLeapYears() { LocalDate t = TEST_2007_07_15.plusYears(2).minusDays(365 + 366); - assertEquals(t, TEST_2007_07_15); + assertEquals(TEST_2007_07_15, t); } @Test public void test_minusDays_negative() { LocalDate t = TEST_2007_07_15.minusDays(-1); - assertEquals(t, LocalDate.of(2007, 7, 16)); + assertEquals(LocalDate.of(2007, 7, 16), t); } @Test public void test_minusDays_negativeAcrossYear() { LocalDate t = TEST_2007_07_15.minusDays(-169); - assertEquals(t, LocalDate.of(2007, 12, 31)); + assertEquals(LocalDate.of(2007, 12, 31), t); } @Test public void test_minusDays_negativeOverYears() { LocalDate t = TEST_2007_07_15.minusDays(-731); - assertEquals(t, LocalDate.of(2009, 7, 15)); + assertEquals(LocalDate.of(2009, 7, 15), t); } @Test public void test_minusDays_maximum() { LocalDate t = LocalDate.of(Year.MAX_VALUE, 12, 30).minusDays(-1); LocalDate expected = LocalDate.of(Year.MAX_VALUE, 12, 31); - assertEquals(t, expected); + assertEquals(expected, t); } @Test public void test_minusDays_minimum() { LocalDate t = LocalDate.of(Year.MIN_VALUE, 1, 2).minusDays(1); LocalDate expected = LocalDate.of(Year.MIN_VALUE, 1, 1); - assertEquals(t, expected); + assertEquals(expected, t); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_minusDays_invalidTooLarge() { - LocalDate.of(Year.MAX_VALUE, 12, 31).minusDays(-1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 31).minusDays(-1)); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_minusDays_invalidTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 1).minusDays(1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).minusDays(1)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_minusDays_overflowTooLarge() { - LocalDate.of(Year.MAX_VALUE, 12, 31).minusDays(Long.MIN_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> LocalDate.of(Year.MAX_VALUE, 12, 31).minusDays(Long.MIN_VALUE)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_minusDays_overflowTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 1).minusDays(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).minusDays(Long.MAX_VALUE)); } //----------------------------------------------------------------------- // until(Temporal, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="periodUntilUnit") Object[][] data_periodUntilUnit() { return new Object[][] { {date(2000, 1, 1), date(2000, 1, 1), DAYS, 0}, @@ -1791,56 +1836,60 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit(LocalDate date1, LocalDate date2, TemporalUnit unit, long expected) { long amount = date1.until(date2, unit); - assertEquals(amount, expected); + assertEquals(expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_negated(LocalDate date1, LocalDate date2, TemporalUnit unit, long expected) { long amount = date2.until(date1, unit); - assertEquals(amount, -expected); + assertEquals(-expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_between(LocalDate date1, LocalDate date2, TemporalUnit unit, long expected) { long amount = unit.between(date1, date2); - assertEquals(amount, expected); + assertEquals(expected, amount); } @Test public void test_until_convertedType() { LocalDate start = LocalDate.of(2010, 6, 30); OffsetDateTime end = start.plusDays(2).atStartOfDay().atOffset(OFFSET_PONE); - assertEquals(start.until(end, DAYS), 2); + assertEquals(2, start.until(end, DAYS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_invalidType() { - LocalDate start = LocalDate.of(2010, 6, 30); - start.until(LocalTime.of(11, 30), DAYS); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate start = LocalDate.of(2010, 6, 30); + start.until(LocalTime.of(11, 30), DAYS); + }); } - @Test(expectedExceptions = UnsupportedTemporalTypeException.class) + @Test public void test_until_TemporalUnit_unsupportedUnit() { - TEST_2007_07_15.until(TEST_2007_07_15, HOURS); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> TEST_2007_07_15.until(TEST_2007_07_15, HOURS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullEnd() { - TEST_2007_07_15.until(null, DAYS); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.until(null, DAYS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullUnit() { - TEST_2007_07_15.until(TEST_2007_07_15, null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.until(TEST_2007_07_15, null)); } //----------------------------------------------------------------------- // until(ChronoLocalDate) //----------------------------------------------------------------------- - @DataProvider(name="until") Object[][] data_periodUntil() { return new Object[][] { {2010, 1, 1, 2010, 1, 1, 0, 0, 0}, @@ -1927,25 +1976,26 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider="until") + @ParameterizedTest + @MethodSource("data_periodUntil") public void test_periodUntil_LocalDate(int y1, int m1, int d1, int y2, int m2, int d2, int ye, int me, int de) { LocalDate start = LocalDate.of(y1, m1, d1); LocalDate end = LocalDate.of(y2, m2, d2); Period test = start.until(end); - assertEquals(test.getYears(), ye); - assertEquals(test.getMonths(), me); - assertEquals(test.getDays(), de); + assertEquals(ye, test.getYears()); + assertEquals(me, test.getMonths()); + assertEquals(de, test.getDays()); } @Test public void test_periodUntil_LocalDate_max() { int years = Math.toIntExact((long) Year.MAX_VALUE - (long) Year.MIN_VALUE); - assertEquals(LocalDate.MIN.until(LocalDate.MAX), Period.of(years, 11, 30)); + assertEquals(Period.of(years, 11, 30), LocalDate.MIN.until(LocalDate.MAX)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_periodUntil_LocalDate_null() { - TEST_2007_07_15.until(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.until(null)); } //----------------------------------------------------------------------- @@ -1955,12 +2005,12 @@ public class TCKLocalDate extends AbstractDateTimeTest { public void test_format_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d"); String t = LocalDate.of(2010, 12, 3).format(f); - assertEquals(t, "2010 12 3"); + assertEquals("2010 12 3", t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_format_formatter_null() { - LocalDate.of(2010, 12, 3).format(null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDate.of(2010, 12, 3).format(null)); } //----------------------------------------------------------------------- @@ -1969,159 +2019,198 @@ public class TCKLocalDate extends AbstractDateTimeTest { @Test public void test_atTime_LocalTime() { LocalDate t = LocalDate.of(2008, 6, 30); - assertEquals(t.atTime(LocalTime.of(11, 30)), LocalDateTime.of(2008, 6, 30, 11, 30)); + assertEquals(LocalDateTime.of(2008, 6, 30, 11, 30), t.atTime(LocalTime.of(11, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atTime_LocalTime_null() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime((LocalTime) null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime((LocalTime) null); + }); } //------------------------------------------------------------------------- @Test public void test_atTime_int_int() { LocalDate t = LocalDate.of(2008, 6, 30); - assertEquals(t.atTime(11, 30), LocalDateTime.of(2008, 6, 30, 11, 30)); + assertEquals(LocalDateTime.of(2008, 6, 30, 11, 30), t.atTime(11, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_hourTooSmall() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(-1, 30); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(-1, 30); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_hourTooBig() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(24, 30); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(24, 30); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_minuteTooSmall() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, -1); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, -1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_minuteTooBig() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, 60); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, 60); + }); } @Test public void test_atTime_int_int_int() { LocalDate t = LocalDate.of(2008, 6, 30); - assertEquals(t.atTime(11, 30, 40), LocalDateTime.of(2008, 6, 30, 11, 30, 40)); + assertEquals(LocalDateTime.of(2008, 6, 30, 11, 30, 40), t.atTime(11, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_hourTooSmall() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(-1, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(-1, 30, 40); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_hourTooBig() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(24, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(24, 30, 40); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_minuteTooSmall() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, -1, 40); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, -1, 40); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_minuteTooBig() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, 60, 40); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, 60, 40); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_secondTooSmall() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, 30, -1); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, 30, -1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_secondTooBig() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, 30, 60); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, 30, 60); + }); } @Test public void test_atTime_int_int_int_int() { LocalDate t = LocalDate.of(2008, 6, 30); - assertEquals(t.atTime(11, 30, 40, 50), LocalDateTime.of(2008, 6, 30, 11, 30, 40, 50)); + assertEquals(LocalDateTime.of(2008, 6, 30, 11, 30, 40, 50), t.atTime(11, 30, 40, 50)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_int_hourTooSmall() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(-1, 30, 40, 50); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(-1, 30, 40, 50); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_int_hourTooBig() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(24, 30, 40, 50); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(24, 30, 40, 50); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_int_minuteTooSmall() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, -1, 40, 50); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, -1, 40, 50); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_int_minuteTooBig() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, 60, 40, 50); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, 60, 40, 50); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_int_secondTooSmall() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, 30, -1, 50); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, 30, -1, 50); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_int_secondTooBig() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, 30, 60, 50); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, 30, 60, 50); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_int_nanoTooSmall() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, 30, 40, -1); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, 30, 40, -1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atTime_int_int_int_int_nanoTooBig() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime(11, 30, 40, 1000000000); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime(11, 30, 40, 1000000000); + }); } //----------------------------------------------------------------------- @Test public void test_atTime_OffsetTime() { LocalDate t = LocalDate.of(2008, 6, 30); - assertEquals(t.atTime(OffsetTime.of(11, 30, 0, 0, OFFSET_PONE)), OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_PONE), t.atTime(OffsetTime.of(11, 30, 0, 0, OFFSET_PONE))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atTime_OffsetTime_null() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atTime((OffsetTime) null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atTime((OffsetTime) null); + }); } //----------------------------------------------------------------------- // atStartOfDay() //----------------------------------------------------------------------- - @DataProvider(name="atStartOfDay") Object[][] data_atStartOfDay() { return new Object[][] { {LocalDate.of(2008, 6, 30), LocalDateTime.of(2008, 6, 30, 0, 0)}, @@ -2129,15 +2218,15 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider="atStartOfDay") + @ParameterizedTest + @MethodSource("data_atStartOfDay") public void test_atStartOfDay(LocalDate test, LocalDateTime expected) { - assertEquals(test.atStartOfDay(), expected); + assertEquals(expected, test.atStartOfDay()); } //----------------------------------------------------------------------- // atStartOfDay(ZoneId) //----------------------------------------------------------------------- - @DataProvider(name="atStartOfDayZoneId") Object[][] data_atStartOfDayZoneId() { return new Object[][] { {LocalDate.of(2008, 6, 30), ZONE_PARIS, ZonedDateTime.of(LocalDateTime.of(2008, 6, 30, 0, 0), ZONE_PARIS)}, @@ -2146,15 +2235,18 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider="atStartOfDayZoneId") + @ParameterizedTest + @MethodSource("data_atStartOfDayZoneId") public void test_atStartOfDay_ZoneId(LocalDate test, ZoneId zone, ZonedDateTime expected) { - assertEquals(test.atStartOfDay(zone), expected); + assertEquals(expected, test.atStartOfDay(zone)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atStartOfDay_ZoneId_null() { - LocalDate t = LocalDate.of(2008, 6, 30); - t.atStartOfDay((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDate t = LocalDate.of(2008, 6, 30); + t.atStartOfDay((ZoneId) null); + }); } //----------------------------------------------------------------------- @@ -2166,26 +2258,25 @@ public class TCKLocalDate extends AbstractDateTimeTest { LocalDate test = LocalDate.of(0, 1, 1); for (long i = date_0000_01_01; i < 700000; i++) { - assertEquals(test.toEpochDay(), i); + assertEquals(i, test.toEpochDay()); test = next(test); } test = LocalDate.of(0, 1, 1); for (long i = date_0000_01_01; i > -2000000; i--) { - assertEquals(test.toEpochDay(), i); + assertEquals(i, test.toEpochDay()); test = previous(test); } - assertEquals(LocalDate.of(1858, 11, 17).toEpochDay(), -40587); - assertEquals(LocalDate.of(1, 1, 1).toEpochDay(), -678575 - 40587); - assertEquals(LocalDate.of(1995, 9, 27).toEpochDay(), 49987 - 40587); - assertEquals(LocalDate.of(1970, 1, 1).toEpochDay(), 0); - assertEquals(LocalDate.of(-1, 12, 31).toEpochDay(), -678942 - 40587); + assertEquals(-40587, LocalDate.of(1858, 11, 17).toEpochDay()); + assertEquals(-678575 - 40587, LocalDate.of(1, 1, 1).toEpochDay()); + assertEquals(49987 - 40587, LocalDate.of(1995, 9, 27).toEpochDay()); + assertEquals(0, LocalDate.of(1970, 1, 1).toEpochDay()); + assertEquals(-678942 - 40587, LocalDate.of(-1, 12, 31).toEpochDay()); } //----------------------------------------------------------------------- // toEpochSecond //----------------------------------------------------------------------- - @DataProvider(name="epochSecond") Object[][] provider_toEpochSecond() { return new Object[][] { {LocalDate.of(1858, 11, 17).toEpochSecond(LocalTime.MIDNIGHT, OFFSET_PONE), -3506720400L}, @@ -2202,9 +2293,10 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider="epochSecond") + @ParameterizedTest + @MethodSource("provider_toEpochSecond") public void test_toEpochSecond(long actual, long expected) { - assertEquals(actual, expected); + assertEquals(expected, actual); } //----------------------------------------------------------------------- @@ -2240,27 +2332,27 @@ public class TCKLocalDate extends AbstractDateTimeTest { LocalDate b = localDates[j]; if (i < j) { assertTrue(a.compareTo(b) < 0, a + " <=> " + b); - assertEquals(a.isBefore(b), true, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { assertTrue(a.compareTo(b) > 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(true, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_ObjectNull() { - TEST_2007_07_15.compareTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.compareTo(null)); } @Test @@ -2270,14 +2362,14 @@ public class TCKLocalDate extends AbstractDateTimeTest { assertFalse(TEST_2007_07_15.isBefore(TEST_2007_07_15)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isBefore_ObjectNull() { - TEST_2007_07_15.isBefore(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.isBefore(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isAfter_ObjectNull() { - TEST_2007_07_15.isAfter(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15.isAfter(null)); } @Test @@ -2287,71 +2379,77 @@ public class TCKLocalDate extends AbstractDateTimeTest { assertFalse(TEST_2007_07_15.isAfter(TEST_2007_07_15)); } - @Test(expectedExceptions=ClassCastException.class) @SuppressWarnings({"unchecked", "rawtypes"}) + @Test public void compareToNonLocalDate() { - Comparable c = TEST_2007_07_15; - c.compareTo(new Object()); + Assertions.assertThrows(ClassCastException.class, () -> { + Comparable c = TEST_2007_07_15; + c.compareTo(new Object()); + }); } //----------------------------------------------------------------------- // equals() //----------------------------------------------------------------------- - @Test(dataProvider="sampleDates" ) + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_equals_true(int y, int m, int d) { LocalDate a = LocalDate.of(y, m, d); LocalDate b = LocalDate.of(y, m, d); - assertEquals(a.equals(b), true); + assertEquals(true, a.equals(b)); } - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_equals_false_year_differs(int y, int m, int d) { LocalDate a = LocalDate.of(y, m, d); LocalDate b = LocalDate.of(y + 1, m, d); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_equals_false_month_differs(int y, int m, int d) { LocalDate a = LocalDate.of(y, m, d); LocalDate b = LocalDate.of(y, m + 1, d); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_equals_false_day_differs(int y, int m, int d) { LocalDate a = LocalDate.of(y, m, d); LocalDate b = LocalDate.of(y, m, d + 1); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } @Test public void test_equals_itself_true() { - assertEquals(TEST_2007_07_15.equals(TEST_2007_07_15), true); + assertEquals(true, TEST_2007_07_15.equals(TEST_2007_07_15)); } @Test public void test_equals_string_false() { - assertEquals(TEST_2007_07_15.equals("2007-07-15"), false); + assertEquals(false, TEST_2007_07_15.equals("2007-07-15")); } @Test public void test_equals_null_false() { - assertEquals(TEST_2007_07_15.equals(null), false); + assertEquals(false, TEST_2007_07_15.equals(null)); } //----------------------------------------------------------------------- // hashCode() //----------------------------------------------------------------------- - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_hashCode(int y, int m, int d) { LocalDate a = LocalDate.of(y, m, d); assertEquals(a.hashCode(), a.hashCode()); LocalDate b = LocalDate.of(y, m, d); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="sampleToString") Object[][] provider_sampleToString() { return new Object[][] { {2008, 7, 5, "2008-07-05"}, @@ -2367,11 +2465,12 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_toString(int y, int m, int d, String expected) { LocalDate t = LocalDate.of(y, m, d); String str = t.toString(); - assertEquals(str, expected); + assertEquals(expected, str); } private LocalDate date(int year, int month, int day) { @@ -2393,71 +2492,81 @@ public class TCKLocalDate extends AbstractDateTimeTest { // ---------------------------------------------------------------- @Test public void test_datesUntil() { - assertEquals( - date(2015, 9, 29).datesUntil(date(2015, 10, 3)).collect( - Collectors.toList()), Arrays.asList(date(2015, 9, 29), - date(2015, 9, 30), date(2015, 10, 1), date(2015, 10, 2))); - assertEquals(date(2015, 9, 29).datesUntil(date(2015, 10, 3), Period.ofDays(2)) - .collect(Collectors.toList()), Arrays.asList(date(2015, 9, 29), - date(2015, 10, 1))); - assertEquals(date(2015, 1, 31).datesUntil(date(2015, 6, 1), Period.ofMonths(1)) - .collect(Collectors.toList()), Arrays.asList(date(2015, 1, 31), + assertEquals(Arrays.asList(date(2015, 9, 29), + date(2015, 9, 30), date(2015, 10, 1), date(2015, 10, 2)), date(2015, 9, 29).datesUntil(date(2015, 10, 3)).collect( + Collectors.toList())); + assertEquals(Arrays.asList(date(2015, 9, 29), + date(2015, 10, 1)), date(2015, 9, 29).datesUntil(date(2015, 10, 3), Period.ofDays(2)) + .collect(Collectors.toList())); + assertEquals(Arrays.asList(date(2015, 1, 31), date(2015, 2, 28), date(2015, 3, 31), date(2015, 4, 30), - date(2015, 5, 31))); + date(2015, 5, 31)), date(2015, 1, 31).datesUntil(date(2015, 6, 1), Period.ofMonths(1)) + .collect(Collectors.toList())); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_datesUntil_nullEnd() { - LocalDate date = date(2015, 1, 31); - date.datesUntil(null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDate date = date(2015, 1, 31); + date.datesUntil(null); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_datesUntil_nullEndStep() { - LocalDate date = date(2015, 1, 31); - date.datesUntil(null, Period.ofDays(1)); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDate date = date(2015, 1, 31); + date.datesUntil(null, Period.ofDays(1)); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_datesUntil_nullStep() { - LocalDate date = date(2015, 1, 31); - date.datesUntil(date, null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDate date = date(2015, 1, 31); + date.datesUntil(date, null); + }); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_datesUntil_endBeforeStart() { - date(2015, 1, 31).datesUntil(date(2015, 1, 30)); + Assertions.assertThrows(IllegalArgumentException.class, () -> date(2015, 1, 31).datesUntil(date(2015, 1, 30))); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_datesUntil_endBeforeStartPositiveStep() { - date(2015, 1, 31).datesUntil(date(2015, 1, 30), Period.of(1, 0, 0)); + Assertions.assertThrows(IllegalArgumentException.class, () -> date(2015, 1, 31).datesUntil(date(2015, 1, 30), Period.of(1, 0, 0))); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_datesUntil_endAfterStartNegativeStep() { - date(2015, 1, 30).datesUntil(date(2015, 1, 31), Period.of(0, -1, -1)); + Assertions.assertThrows(IllegalArgumentException.class, () -> date(2015, 1, 30).datesUntil(date(2015, 1, 31), Period.of(0, -1, -1))); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_datesUntil_zeroStep() { - LocalDate date = date(2015, 1, 31); - date.datesUntil(date, Period.ZERO); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + LocalDate date = date(2015, 1, 31); + date.datesUntil(date, Period.ZERO); + }); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_datesUntil_oppositeSign() { - LocalDate date = date(2015, 1, 31); - date.datesUntil(date, Period.of(1, 0, -1)); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + LocalDate date = date(2015, 1, 31); + date.datesUntil(date, Period.of(1, 0, -1)); + }); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_datesUntil_oppositeSign2() { - LocalDate date = date(2015, 1, 31); - date.datesUntil(date, Period.of(0, -1, 1)); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + LocalDate date = date(2015, 1, 31); + date.datesUntil(date, Period.of(0, -1, 1)); + }); } - @DataProvider(name="datesUntil") public Object[][] provider_datesUntil() { return new Object[][] { {MIN_DATE, MIN_DATE}, @@ -2471,14 +2580,13 @@ public class TCKLocalDate extends AbstractDateTimeTest { }; } - @Test(dataProvider = "datesUntil") + @ParameterizedTest + @MethodSource("provider_datesUntil") public void test_datesUntil_count(LocalDate start, LocalDate end) { - assertEquals(start.datesUntil(end).count(), start.until(end, ChronoUnit.DAYS)); - assertEquals(start.datesUntil(end, Period.ofDays(1)).count(), - start.until(end, ChronoUnit.DAYS)); + assertEquals(start.until(end, ChronoUnit.DAYS), start.datesUntil(end).count()); + assertEquals(start.until(end, ChronoUnit.DAYS), start.datesUntil(end, Period.ofDays(1)).count()); } - @DataProvider(name="datesUntilSteps") public Object[][] provider_datesUntil_steps() { List data = new ArrayList<>(Arrays.asList(new Object[][] { {MIN_DATE, MAX_DATE, Period.ofYears(Year.MAX_VALUE)}, @@ -2536,9 +2644,10 @@ public class TCKLocalDate extends AbstractDateTimeTest { return data.toArray(new Object[data.size()][]); } - @Test(dataProvider="datesUntilSteps") + @ParameterizedTest + @MethodSource("provider_datesUntil_steps") public void test_datesUntil_step(LocalDate start, LocalDate end, Period step) { - assertEquals(start.datesUntil(start, step).count(), 0); + assertEquals(0, start.datesUntil(start, step).count()); long count = start.datesUntil(end, step).count(); assertTrue(count > 0); // the last value must be before the end date @@ -2555,7 +2664,7 @@ public class TCKLocalDate extends AbstractDateTimeTest { for(long i=0; i stream = date.datesUntil(date.plusDays(5)); long sum = stream.mapToInt(LocalDate::getDayOfMonth).sum(); - assertEquals(sum, 60, "sum of 10, 11, 12, 13, 14 is wrong"); + assertEquals(60, sum, "sum of 10, 11, 12, 13, 14 is wrong"); } } diff --git a/test/jdk/java/time/tck/java/time/TCKLocalDateTime.java b/test/jdk/java/time/tck/java/time/TCKLocalDateTime.java index 487cd806a2b..9cf2a777ec7 100644 --- a/test/jdk/java/time/tck/java/time/TCKLocalDateTime.java +++ b/test/jdk/java/time/tck/java/time/TCKLocalDateTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -101,11 +101,12 @@ import static java.time.temporal.ChronoUnit.NANOS; import static java.time.temporal.ChronoUnit.SECONDS; import static java.time.temporal.ChronoUnit.WEEKS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.Clock; import java.time.DateTimeException; @@ -141,14 +142,18 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test LocalDateTime. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKLocalDateTime extends AbstractDateTimeTest { private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); @@ -163,7 +168,7 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { private Instant MAX_INSTANT; private Instant MIN_INSTANT; - @BeforeMethod + @BeforeEach public void setUp() { MAX_DATE_TIME = LocalDateTime.MAX; MIN_DATE_TIME = LocalDateTime.MIN; @@ -225,16 +230,16 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- private void check(LocalDateTime test, int y, int m, int d, int h, int mi, int s, int n) { - assertEquals(test.getYear(), y); - assertEquals(test.getMonth().getValue(), m); - assertEquals(test.getDayOfMonth(), d); - assertEquals(test.getHour(), h); - assertEquals(test.getMinute(), mi); - assertEquals(test.getSecond(), s); - assertEquals(test.getNano(), n); + assertEquals(y, test.getYear()); + assertEquals(m, test.getMonth().getValue()); + assertEquals(d, test.getDayOfMonth()); + assertEquals(h, test.getHour()); + assertEquals(mi, test.getMinute()); + assertEquals(s, test.getSecond()); + assertEquals(n, test.getNano()); assertEquals(test, test); assertEquals(test.hashCode(), test.hashCode()); - assertEquals(LocalDateTime.of(y, m, d, h, mi, s, n), test); + assertEquals(test, LocalDateTime.of(y, m, d, h, mi, s, n)); } private LocalDateTime createDateMidnight(int year, int month, int day) { @@ -257,7 +262,8 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- // now() //----------------------------------------------------------------------- - @Test(timeOut=30000) // TODO: remove when time zone loading is faster + @Test // TODO: remove when time zone loading is faster + @Timeout(30) public void now() { final long DELTA = 20_000_000_000L; // 20 seconds of nanos leeway LocalDateTime expected = LocalDateTime.now(Clock.systemDefaultZone()); @@ -275,9 +281,9 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- // now(ZoneId) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_ZoneId_nullZoneId() { - LocalDateTime.now((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.now((ZoneId) null)); } @Test @@ -285,16 +291,15 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { ZoneId zone = ZoneId.of("UTC+01:02:03"); LocalDateTime expected = LocalDateTime.now(Clock.system(zone)); LocalDateTime test = LocalDateTime.now(zone); - assertEquals(Duration.between(expected, test).truncatedTo(ChronoUnit.SECONDS), - Duration.ZERO); + assertEquals(Duration.ZERO, Duration.between(expected, test).truncatedTo(ChronoUnit.SECONDS)); } //----------------------------------------------------------------------- // now(Clock) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullClock() { - LocalDateTime.now((Clock) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.now((Clock) null)); } @Test @@ -303,13 +308,13 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); LocalDateTime test = LocalDateTime.now(clock); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60 ? 1 : 2)); - assertEquals(test.getHour(), (i / (60 * 60)) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); - assertEquals(test.getNano(), 123456789); + assertEquals(1970, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals((i < 24 * 60 * 60 ? 1 : 2), test.getDayOfMonth()); + assertEquals((i / (60 * 60)) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); + assertEquals(123456789, test.getNano()); } } @@ -319,13 +324,13 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L); Clock clock = Clock.fixed(instant.minusSeconds(OFFSET_PONE.getTotalSeconds()), OFFSET_PONE); LocalDateTime test = LocalDateTime.now(clock); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60) ? 1 : 2); - assertEquals(test.getHour(), (i / (60 * 60)) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); - assertEquals(test.getNano(), 123456789); + assertEquals(1970, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals((i < 24 * 60 * 60) ? 1 : 2, test.getDayOfMonth()); + assertEquals((i / (60 * 60)) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); + assertEquals(123456789, test.getNano()); } } @@ -336,11 +341,11 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); LocalDateTime test = LocalDateTime.now(clock); - assertEquals(test.getYear(), 1969); - assertEquals(test.getMonth(), Month.DECEMBER); - assertEquals(test.getDayOfMonth(), 31); + assertEquals(1969, test.getYear()); + assertEquals(Month.DECEMBER, test.getMonth()); + assertEquals(31, test.getDayOfMonth()); expected = expected.minusSeconds(1); - assertEquals(test.toLocalTime(), expected); + assertEquals(expected, test.toLocalTime()); } } @@ -349,26 +354,30 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { public void now_Clock_maxYear() { Clock clock = Clock.fixed(MAX_INSTANT, ZoneOffset.UTC); LocalDateTime test = LocalDateTime.now(clock); - assertEquals(test, MAX_DATE_TIME); + assertEquals(MAX_DATE_TIME, test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void now_Clock_tooBig() { - Clock clock = Clock.fixed(MAX_INSTANT.plusSeconds(24 * 60 * 60), ZoneOffset.UTC); - LocalDateTime.now(clock); + Assertions.assertThrows(DateTimeException.class, () -> { + Clock clock = Clock.fixed(MAX_INSTANT.plusSeconds(24 * 60 * 60), ZoneOffset.UTC); + LocalDateTime.now(clock); + }); } @Test public void now_Clock_minYear() { Clock clock = Clock.fixed(MIN_INSTANT, ZoneOffset.UTC); LocalDateTime test = LocalDateTime.now(clock); - assertEquals(test, MIN_DATE_TIME); + assertEquals(MIN_DATE_TIME, test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void now_Clock_tooLow() { - Clock clock = Clock.fixed(MIN_INSTANT.minusNanos(1), ZoneOffset.UTC); - LocalDateTime.now(clock); + Assertions.assertThrows(DateTimeException.class, () -> { + Clock clock = Clock.fixed(MIN_INSTANT.minusNanos(1), ZoneOffset.UTC); + LocalDateTime.now(clock); + }); } //----------------------------------------------------------------------- @@ -381,44 +390,44 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(dateTime, 2007, 7, 15, 12, 30, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_4intsMonth_yearTooLow() { - LocalDateTime.of(Integer.MIN_VALUE, Month.JULY, 15, 12, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(Integer.MIN_VALUE, Month.JULY, 15, 12, 30)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_4intsMonth_nullMonth() { - LocalDateTime.of(2007, null, 15, 12, 30); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.of(2007, null, 15, 12, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_4intsMonth_dayTooLow() { - LocalDateTime.of(2007, Month.JULY, -1, 12, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, -1, 12, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_4intsMonth_dayTooHigh() { - LocalDateTime.of(2007, Month.JULY, 32, 12, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 32, 12, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_4intsMonth_hourTooLow() { - LocalDateTime.of(2007, Month.JULY, 15, -1, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, -1, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_4intsMonth_hourTooHigh() { - LocalDateTime.of(2007, Month.JULY, 15, 24, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 24, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_4intsMonth_minuteTooLow() { - LocalDateTime.of(2007, Month.JULY, 15, 12, -1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_4intsMonth_minuteTooHigh() { - LocalDateTime.of(2007, Month.JULY, 15, 12, 60); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, 60)); } //----------------------------------------------------------------------- @@ -428,54 +437,54 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(dateTime, 2007, 7, 15, 12, 30, 40, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5intsMonth_yearTooLow() { - LocalDateTime.of(Integer.MIN_VALUE, Month.JULY, 15, 12, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(Integer.MIN_VALUE, Month.JULY, 15, 12, 30, 40)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_5intsMonth_nullMonth() { - LocalDateTime.of(2007, null, 15, 12, 30, 40); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.of(2007, null, 15, 12, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5intsMonth_dayTooLow() { - LocalDateTime.of(2007, Month.JULY, -1, 12, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, -1, 12, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5intsMonth_dayTooHigh() { - LocalDateTime.of(2007, Month.JULY, 32, 12, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 32, 12, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5intsMonth_hourTooLow() { - LocalDateTime.of(2007, Month.JULY, 15, -1, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, -1, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5intsMonth_hourTooHigh() { - LocalDateTime.of(2007, Month.JULY, 15, 24, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 24, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5intsMonth_minuteTooLow() { - LocalDateTime.of(2007, Month.JULY, 15, 12, -1, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, -1, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5intsMonth_minuteTooHigh() { - LocalDateTime.of(2007, Month.JULY, 15, 12, 60, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, 60, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5intsMonth_secondTooLow() { - LocalDateTime.of(2007, Month.JULY, 15, 12, 30, -1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, 30, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5intsMonth_secondTooHigh() { - LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 60); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 60)); } //----------------------------------------------------------------------- @@ -485,64 +494,64 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(dateTime, 2007, 7, 15, 12, 30, 40, 987654321); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_yearTooLow() { - LocalDateTime.of(Integer.MIN_VALUE, Month.JULY, 15, 12, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(Integer.MIN_VALUE, Month.JULY, 15, 12, 30, 40, 987654321)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_6intsMonth_nullMonth() { - LocalDateTime.of(2007, null, 15, 12, 30, 40, 987654321); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.of(2007, null, 15, 12, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_dayTooLow() { - LocalDateTime.of(2007, Month.JULY, -1, 12, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, -1, 12, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_dayTooHigh() { - LocalDateTime.of(2007, Month.JULY, 32, 12, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 32, 12, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_hourTooLow() { - LocalDateTime.of(2007, Month.JULY, 15, -1, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, -1, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_hourTooHigh() { - LocalDateTime.of(2007, Month.JULY, 15, 24, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 24, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_minuteTooLow() { - LocalDateTime.of(2007, Month.JULY, 15, 12, -1, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, -1, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_minuteTooHigh() { - LocalDateTime.of(2007, Month.JULY, 15, 12, 60, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, 60, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_secondTooLow() { - LocalDateTime.of(2007, Month.JULY, 15, 12, 30, -1, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, 30, -1, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_secondTooHigh() { - LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 60, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 60, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_nanoTooLow() { - LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 40, -1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 40, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6intsMonth_nanoTooHigh() { - LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 40, 1000000000); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, Month.JULY, 15, 12, 30, 40, 1000000000)); } //----------------------------------------------------------------------- @@ -552,49 +561,49 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(dateTime, 2007, 7, 15, 12, 30, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5ints_yearTooLow() { - LocalDateTime.of(Integer.MIN_VALUE, 7, 15, 12, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(Integer.MIN_VALUE, 7, 15, 12, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5ints_monthTooLow() { - LocalDateTime.of(2007, 0, 15, 12, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 0, 15, 12, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5ints_monthTooHigh() { - LocalDateTime.of(2007, 13, 15, 12, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 13, 15, 12, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5ints_dayTooLow() { - LocalDateTime.of(2007, 7, -1, 12, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, -1, 12, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5ints_dayTooHigh() { - LocalDateTime.of(2007, 7, 32, 12, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 32, 12, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5ints_hourTooLow() { - LocalDateTime.of(2007, 7, 15, -1, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, -1, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5ints_hourTooHigh() { - LocalDateTime.of(2007, 7, 15, 24, 30); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 24, 30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5ints_minuteTooLow() { - LocalDateTime.of(2007, 7, 15, 12, -1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_5ints_minuteTooHigh() { - LocalDateTime.of(2007, 7, 15, 12, 60); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, 60)); } //----------------------------------------------------------------------- @@ -604,59 +613,59 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(dateTime, 2007, 7, 15, 12, 30, 40, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_yearTooLow() { - LocalDateTime.of(Integer.MIN_VALUE, 7, 15, 12, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(Integer.MIN_VALUE, 7, 15, 12, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_monthTooLow() { - LocalDateTime.of(2007, 0, 15, 12, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 0, 15, 12, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_monthTooHigh() { - LocalDateTime.of(2007, 13, 15, 12, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 13, 15, 12, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_dayTooLow() { - LocalDateTime.of(2007, 7, -1, 12, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, -1, 12, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_dayTooHigh() { - LocalDateTime.of(2007, 7, 32, 12, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 32, 12, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_hourTooLow() { - LocalDateTime.of(2007, 7, 15, -1, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, -1, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_hourTooHigh() { - LocalDateTime.of(2007, 7, 15, 24, 30, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 24, 30, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_minuteTooLow() { - LocalDateTime.of(2007, 7, 15, 12, -1, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, -1, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_minuteTooHigh() { - LocalDateTime.of(2007, 7, 15, 12, 60, 40); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, 60, 40)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_secondTooLow() { - LocalDateTime.of(2007, 7, 15, 12, 30, -1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, 30, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_6ints_secondTooHigh() { - LocalDateTime.of(2007, 7, 15, 12, 30, 60); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, 30, 60)); } //----------------------------------------------------------------------- @@ -666,69 +675,69 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(dateTime, 2007, 7, 15, 12, 30, 40, 987654321); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_yearTooLow() { - LocalDateTime.of(Integer.MIN_VALUE, 7, 15, 12, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(Integer.MIN_VALUE, 7, 15, 12, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_monthTooLow() { - LocalDateTime.of(2007, 0, 15, 12, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 0, 15, 12, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_monthTooHigh() { - LocalDateTime.of(2007, 13, 15, 12, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 13, 15, 12, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_dayTooLow() { - LocalDateTime.of(2007, 7, -1, 12, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, -1, 12, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_dayTooHigh() { - LocalDateTime.of(2007, 7, 32, 12, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 32, 12, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_hourTooLow() { - LocalDateTime.of(2007, 7, 15, -1, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, -1, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_hourTooHigh() { - LocalDateTime.of(2007, 7, 15, 24, 30, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 24, 30, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_minuteTooLow() { - LocalDateTime.of(2007, 7, 15, 12, -1, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, -1, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_minuteTooHigh() { - LocalDateTime.of(2007, 7, 15, 12, 60, 40, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, 60, 40, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_secondTooLow() { - LocalDateTime.of(2007, 7, 15, 12, 30, -1, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, 30, -1, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_secondTooHigh() { - LocalDateTime.of(2007, 7, 15, 12, 30, 60, 987654321); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, 30, 60, 987654321)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_nanoTooLow() { - LocalDateTime.of(2007, 7, 15, 12, 30, 40, -1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, 30, 40, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_7ints_nanoTooHigh() { - LocalDateTime.of(2007, 7, 15, 12, 30, 40, 1000000000); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 15, 12, 30, 40, 1000000000)); } //----------------------------------------------------------------------- @@ -738,20 +747,19 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(dateTime, 2007, 7, 15, 12, 30, 40, 987654321); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDate_LocalTime_nullLocalDate() { - LocalDateTime.of(null, LocalTime.of(12, 30, 40, 987654321)); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.of(null, LocalTime.of(12, 30, 40, 987654321))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDate_LocalTime_nullLocalTime() { - LocalDateTime.of(LocalDate.of(2007, 7, 15), null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.of(LocalDate.of(2007, 7, 15), null)); } //----------------------------------------------------------------------- // ofInstant() //----------------------------------------------------------------------- - @DataProvider(name="instantFactory") Object[][] data_instantFactory() { return new Object[][] { {Instant.ofEpochSecond(86400 + 3600 + 120 + 4, 500), ZONE_PARIS, LocalDateTime.of(1970, 1, 2, 2, 2, 4, 500)}, @@ -764,30 +772,31 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="instantFactory") + @ParameterizedTest + @MethodSource("data_instantFactory") public void factory_ofInstant(Instant instant, ZoneId zone, LocalDateTime expected) { LocalDateTime test = LocalDateTime.ofInstant(instant, zone); - assertEquals(test, expected); + assertEquals(expected, test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_instantTooBig() { - LocalDateTime.ofInstant(Instant.MAX, OFFSET_PONE) ; + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.ofInstant(Instant.MAX, OFFSET_PONE)) ; } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_instantTooSmall() { - LocalDateTime.ofInstant(Instant.MIN, OFFSET_PONE) ; + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.ofInstant(Instant.MIN, OFFSET_PONE)) ; } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_nullInstant() { - LocalDateTime.ofInstant((Instant) null, ZONE_GAZA); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.ofInstant((Instant) null, ZONE_GAZA)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_nullZone() { - LocalDateTime.ofInstant(Instant.EPOCH, (ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.ofInstant(Instant.EPOCH, (ZoneId) null)); } //----------------------------------------------------------------------- @@ -798,7 +807,7 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { LocalDateTime base = LocalDateTime.of(1970, 1, 1, 2, 0, 0, 500); for (int i = 0; i < 100000; i++) { LocalDateTime test = LocalDateTime.ofEpochSecond(i, 500, OFFSET_PTWO); - assertEquals(test, base.plusSeconds(i)); + assertEquals(base.plusSeconds(i), test); } } @@ -807,33 +816,37 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { LocalDateTime base = LocalDateTime.of(1970, 1, 1, 2, 0, 0, 500); for (int i = 0; i < 100000; i++) { LocalDateTime test = LocalDateTime.ofEpochSecond(-i, 500, OFFSET_PTWO); - assertEquals(test, base.minusSeconds(i)); + assertEquals(base.minusSeconds(i), test); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofEpochSecond_longOffset_tooBig() { - LocalDateTime.ofEpochSecond(Long.MAX_VALUE, 500, OFFSET_PONE); // TODO: better test + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDateTime.ofEpochSecond(Long.MAX_VALUE, 500, OFFSET_PONE); // TODO: better test + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofEpochSecond_longOffset_tooSmall() { - LocalDateTime.ofEpochSecond(Long.MIN_VALUE, 500, OFFSET_PONE); // TODO: better test + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDateTime.ofEpochSecond(Long.MIN_VALUE, 500, OFFSET_PONE); // TODO: better test + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofEpochSecond_badNanos_toBig() { - LocalDateTime.ofEpochSecond(0, 1_000_000_000, OFFSET_PONE); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.ofEpochSecond(0, 1_000_000_000, OFFSET_PONE)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofEpochSecond_badNanos_toSmall() { - LocalDateTime.ofEpochSecond(0, -1, OFFSET_PONE); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.ofEpochSecond(0, -1, OFFSET_PONE)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofEpochSecond_longOffset_nullOffset() { - LocalDateTime.ofEpochSecond(0L, 500, null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.ofEpochSecond(0L, 500, null)); } //----------------------------------------------------------------------- @@ -842,48 +855,49 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_from_TemporalAccessor() { LocalDateTime base = LocalDateTime.of(2007, 7, 15, 17, 30); - assertEquals(LocalDateTime.from(base), base); - assertEquals(LocalDateTime.from(ZonedDateTime.of(base, ZoneOffset.ofHours(2))), base); + assertEquals(base, LocalDateTime.from(base)); + assertEquals(base, LocalDateTime.from(ZonedDateTime.of(base, ZoneOffset.ofHours(2)))); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_from_TemporalAccessor_invalid_noDerive() { - LocalDateTime.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_from_TemporalAccessor_null() { - LocalDateTime.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- // parse() //----------------------------------------------------------------------- - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_parse(int y, int month, int d, int h, int m, int s, int n, String text) { LocalDateTime t = LocalDateTime.parse(text); - assertEquals(t.getYear(), y); - assertEquals(t.getMonth().getValue(), month); - assertEquals(t.getDayOfMonth(), d); - assertEquals(t.getHour(), h); - assertEquals(t.getMinute(), m); - assertEquals(t.getSecond(), s); - assertEquals(t.getNano(), n); + assertEquals(y, t.getYear()); + assertEquals(month, t.getMonth().getValue()); + assertEquals(d, t.getDayOfMonth()); + assertEquals(h, t.getHour()); + assertEquals(m, t.getMinute()); + assertEquals(s, t.getSecond()); + assertEquals(n, t.getNano()); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_illegalValue() { - LocalDateTime.parse("2008-06-32T11:15"); + Assertions.assertThrows(DateTimeParseException.class, () -> LocalDateTime.parse("2008-06-32T11:15")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_invalidValue() { - LocalDateTime.parse("2008-06-31T11:15"); + Assertions.assertThrows(DateTimeParseException.class, () -> LocalDateTime.parse("2008-06-31T11:15")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_nullText() { - LocalDateTime.parse((String) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.parse((String) null)); } //----------------------------------------------------------------------- @@ -893,18 +907,20 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { public void factory_parse_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); LocalDateTime test = LocalDateTime.parse("2010 12 3 11 30 45", f); - assertEquals(test, LocalDateTime.of(2010, 12, 3, 11, 30, 45)); + assertEquals(LocalDateTime.of(2010, 12, 3, 11, 30, 45), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullText() { - DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); - LocalDateTime.parse((String) null, f); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); + LocalDateTime.parse((String) null, f); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullFormatter() { - LocalDateTime.parse("ANY", null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.parse("ANY", null)); } //----------------------------------------------------------------------- @@ -912,37 +928,37 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported((TemporalField) null), false); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.NANO_OF_SECOND), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.NANO_OF_DAY), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MICRO_OF_SECOND), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MICRO_OF_DAY), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MILLI_OF_SECOND), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MILLI_OF_DAY), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.SECOND_OF_MINUTE), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.SECOND_OF_DAY), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MINUTE_OF_HOUR), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MINUTE_OF_DAY), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.HOUR_OF_AMPM), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.HOUR_OF_DAY), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.AMPM_OF_DAY), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.DAY_OF_WEEK), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.DAY_OF_MONTH), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.DAY_OF_YEAR), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.EPOCH_DAY), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MONTH_OF_YEAR), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.PROLEPTIC_MONTH), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.YEAR), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.YEAR_OF_ERA), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.ERA), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.INSTANT_SECONDS), false); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.OFFSET_SECONDS), false); + assertEquals(false, TEST_2007_07_15_12_30_40_987654321.isSupported((TemporalField) null)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.YEAR)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.ERA)); + assertEquals(false, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(false, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -950,23 +966,23 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalUnit() { - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported((TemporalUnit) null), false); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.NANOS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.MICROS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.MILLIS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.SECONDS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.MINUTES), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.HOURS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.HALF_DAYS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.DAYS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.WEEKS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.MONTHS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.YEARS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.DECADES), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.CENTURIES), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.MILLENNIA), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.ERAS), true); - assertEquals(TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.FOREVER), false); + assertEquals(false, TEST_2007_07_15_12_30_40_987654321.isSupported((TemporalUnit) null)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.NANOS)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.MICROS)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.MILLIS)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.SECONDS)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.MINUTES)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.HOURS)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.HALF_DAYS)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.DAYS)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.WEEKS)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.MONTHS)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.YEARS)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.DECADES)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.CENTURIES)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.MILLENNIA)); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.ERAS)); + assertEquals(false, TEST_2007_07_15_12_30_40_987654321.isSupported(ChronoUnit.FOREVER)); } //----------------------------------------------------------------------- @@ -975,41 +991,40 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_get_TemporalField() { LocalDateTime test = LocalDateTime.of(2008, 6, 30, 12, 30, 40, 987654321); - assertEquals(test.get(ChronoField.YEAR), 2008); - assertEquals(test.get(ChronoField.MONTH_OF_YEAR), 6); - assertEquals(test.get(ChronoField.DAY_OF_MONTH), 30); - assertEquals(test.get(ChronoField.DAY_OF_WEEK), 1); - assertEquals(test.get(ChronoField.DAY_OF_YEAR), 182); + assertEquals(2008, test.get(ChronoField.YEAR)); + assertEquals(6, test.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(30, test.get(ChronoField.DAY_OF_MONTH)); + assertEquals(1, test.get(ChronoField.DAY_OF_WEEK)); + assertEquals(182, test.get(ChronoField.DAY_OF_YEAR)); - assertEquals(test.get(ChronoField.HOUR_OF_DAY), 12); - assertEquals(test.get(ChronoField.MINUTE_OF_HOUR), 30); - assertEquals(test.get(ChronoField.SECOND_OF_MINUTE), 40); - assertEquals(test.get(ChronoField.NANO_OF_SECOND), 987654321); - assertEquals(test.get(ChronoField.HOUR_OF_AMPM), 0); - assertEquals(test.get(ChronoField.AMPM_OF_DAY), 1); + assertEquals(12, test.get(ChronoField.HOUR_OF_DAY)); + assertEquals(30, test.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(40, test.get(ChronoField.SECOND_OF_MINUTE)); + assertEquals(987654321, test.get(ChronoField.NANO_OF_SECOND)); + assertEquals(0, test.get(ChronoField.HOUR_OF_AMPM)); + assertEquals(1, test.get(ChronoField.AMPM_OF_DAY)); } @Test public void test_getLong_TemporalField() { LocalDateTime test = LocalDateTime.of(2008, 6, 30, 12, 30, 40, 987654321); - assertEquals(test.getLong(ChronoField.YEAR), 2008); - assertEquals(test.getLong(ChronoField.MONTH_OF_YEAR), 6); - assertEquals(test.getLong(ChronoField.DAY_OF_MONTH), 30); - assertEquals(test.getLong(ChronoField.DAY_OF_WEEK), 1); - assertEquals(test.getLong(ChronoField.DAY_OF_YEAR), 182); + assertEquals(2008, test.getLong(ChronoField.YEAR)); + assertEquals(6, test.getLong(ChronoField.MONTH_OF_YEAR)); + assertEquals(30, test.getLong(ChronoField.DAY_OF_MONTH)); + assertEquals(1, test.getLong(ChronoField.DAY_OF_WEEK)); + assertEquals(182, test.getLong(ChronoField.DAY_OF_YEAR)); - assertEquals(test.getLong(ChronoField.HOUR_OF_DAY), 12); - assertEquals(test.getLong(ChronoField.MINUTE_OF_HOUR), 30); - assertEquals(test.getLong(ChronoField.SECOND_OF_MINUTE), 40); - assertEquals(test.getLong(ChronoField.NANO_OF_SECOND), 987654321); - assertEquals(test.getLong(ChronoField.HOUR_OF_AMPM), 0); - assertEquals(test.getLong(ChronoField.AMPM_OF_DAY), 1); + assertEquals(12, test.getLong(ChronoField.HOUR_OF_DAY)); + assertEquals(30, test.getLong(ChronoField.MINUTE_OF_HOUR)); + assertEquals(40, test.getLong(ChronoField.SECOND_OF_MINUTE)); + assertEquals(987654321, test.getLong(ChronoField.NANO_OF_SECOND)); + assertEquals(0, test.getLong(ChronoField.HOUR_OF_AMPM)); + assertEquals(1, test.getLong(ChronoField.AMPM_OF_DAY)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.chronology(), IsoChronology.INSTANCE}, @@ -1022,23 +1037,24 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - TEST_2007_07_15_12_30_40_987654321.query(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.query(null)); } //----------------------------------------------------------------------- - @DataProvider(name="sampleDates") Object[][] provider_sampleDates() { return new Object[][] { {2008, 7, 5}, @@ -1050,7 +1066,6 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @DataProvider(name="sampleTimes") Object[][] provider_sampleTimes() { return new Object[][] { {0, 0, 0, 0}, @@ -1075,15 +1090,17 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- // get*() //----------------------------------------------------------------------- - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_get_dates(int y, int m, int d) { LocalDateTime a = LocalDateTime.of(y, m, d, 12, 30); - assertEquals(a.getYear(), y); - assertEquals(a.getMonth(), Month.of(m)); - assertEquals(a.getDayOfMonth(), d); + assertEquals(y, a.getYear()); + assertEquals(Month.of(m), a.getMonth()); + assertEquals(d, a.getDayOfMonth()); } - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_getDOY(int y, int m, int d) { LocalDateTime a = LocalDateTime.of(y, m, d, 12 ,30); int total = 0; @@ -1091,16 +1108,17 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { total += Month.of(i).length(isIsoLeap(y)); } int doy = total + d; - assertEquals(a.getDayOfYear(), doy); + assertEquals(doy, a.getDayOfYear()); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_get_times(int h, int m, int s, int ns) { LocalDateTime a = LocalDateTime.of(TEST_2007_07_15_12_30_40_987654321.toLocalDate(), LocalTime.of(h, m, s, ns)); - assertEquals(a.getHour(), h); - assertEquals(a.getMinute(), m); - assertEquals(a.getSecond(), s); - assertEquals(a.getNano(), ns); + assertEquals(h, a.getHour()); + assertEquals(m, a.getMinute()); + assertEquals(s, a.getSecond()); + assertEquals(ns, a.getNano()); } //----------------------------------------------------------------------- @@ -1123,7 +1141,6 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- // adjustInto(Temporal) //----------------------------------------------------------------------- - @DataProvider(name="adjustInto") Object[][] data_adjustInto() { return new Object[][]{ {LocalDateTime.of(2012, 3, 4, 23, 5), LocalDateTime.of(2012, 3, 4, 1, 1, 1, 100), LocalDateTime.of(2012, 3, 4, 23, 5, 0, 0), null}, @@ -1145,11 +1162,12 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="adjustInto") + @ParameterizedTest + @MethodSource("data_adjustInto") public void test_adjustInto(LocalDateTime test, Temporal temporal, Temporal expected, Class expectedEx) { if (expectedEx == null) { Temporal result = test.adjustInto(temporal); - assertEquals(result, expected); + assertEquals(expected, result); } else { try { Temporal result = test.adjustInto(temporal); @@ -1172,12 +1190,12 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { return sample; } }; - assertEquals(TEST_2007_07_15_12_30_40_987654321.with(adjuster), sample); + assertEquals(sample, TEST_2007_07_15_12_30_40_987654321.with(adjuster)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_with_adjustment_null() { - TEST_2007_07_15_12_30_40_987654321.with((TemporalAdjuster) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.with((TemporalAdjuster) null)); } //----------------------------------------------------------------------- @@ -1189,16 +1207,16 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, 2008, 7, 15, 12, 30, 40, 987654321); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withYear_int_invalid() { - TEST_2007_07_15_12_30_40_987654321.withYear(Year.MIN_VALUE - 1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withYear(Year.MIN_VALUE - 1)); } @Test public void test_withYear_int_adjustDay() { LocalDateTime t = LocalDateTime.of(2008, 2, 29, 12, 30).withYear(2007); LocalDateTime expected = LocalDateTime.of(2007, 2, 28, 12, 30); - assertEquals(t, expected); + assertEquals(expected, t); } //----------------------------------------------------------------------- @@ -1210,16 +1228,16 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, 2007, 1, 15, 12, 30, 40, 987654321); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMonth_int_invalid() { - TEST_2007_07_15_12_30_40_987654321.withMonth(13); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withMonth(13)); } @Test public void test_withMonth_int_adjustDay() { LocalDateTime t = LocalDateTime.of(2007, 12, 31, 12, 30).withMonth(11); LocalDateTime expected = LocalDateTime.of(2007, 11, 30, 12, 30); - assertEquals(t, expected); + assertEquals(expected, t); } //----------------------------------------------------------------------- @@ -1231,14 +1249,14 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, 2007, 7, 1, 12, 30, 40, 987654321); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfMonth_invalid() { - LocalDateTime.of(2007, 11, 30, 12, 30).withDayOfMonth(32); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 11, 30, 12, 30).withDayOfMonth(32)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfMonth_invalidCombination() { - LocalDateTime.of(2007, 11, 30, 12, 30).withDayOfMonth(31); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 11, 30, 12, 30).withDayOfMonth(31)); } //----------------------------------------------------------------------- @@ -1247,17 +1265,17 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_withDayOfYear_normal() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.withDayOfYear(33); - assertEquals(t, LocalDateTime.of(2007, 2, 2, 12, 30, 40, 987654321)); + assertEquals(LocalDateTime.of(2007, 2, 2, 12, 30, 40, 987654321), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfYear_illegal() { - TEST_2007_07_15_12_30_40_987654321.withDayOfYear(367); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withDayOfYear(367)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfYear_invalid() { - TEST_2007_07_15_12_30_40_987654321.withDayOfYear(366); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withDayOfYear(366)); } //----------------------------------------------------------------------- @@ -1268,18 +1286,18 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321; for (int i = 0; i < 24; i++) { t = t.withHour(i); - assertEquals(t.getHour(), i); + assertEquals(i, t.getHour()); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withHour_hourTooLow() { - TEST_2007_07_15_12_30_40_987654321.withHour(-1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withHour(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withHour_hourTooHigh() { - TEST_2007_07_15_12_30_40_987654321.withHour(24); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withHour(24)); } //----------------------------------------------------------------------- @@ -1290,18 +1308,18 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321; for (int i = 0; i < 60; i++) { t = t.withMinute(i); - assertEquals(t.getMinute(), i); + assertEquals(i, t.getMinute()); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMinute_minuteTooLow() { - TEST_2007_07_15_12_30_40_987654321.withMinute(-1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withMinute(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMinute_minuteTooHigh() { - TEST_2007_07_15_12_30_40_987654321.withMinute(60); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withMinute(60)); } //----------------------------------------------------------------------- @@ -1312,18 +1330,18 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321; for (int i = 0; i < 60; i++) { t = t.withSecond(i); - assertEquals(t.getSecond(), i); + assertEquals(i, t.getSecond()); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withSecond_secondTooLow() { - TEST_2007_07_15_12_30_40_987654321.withSecond(-1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withSecond(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withSecond_secondTooHigh() { - TEST_2007_07_15_12_30_40_987654321.withSecond(60); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withSecond(60)); } //----------------------------------------------------------------------- @@ -1333,23 +1351,23 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { public void test_withNanoOfSecond_normal() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321; t = t.withNano(1); - assertEquals(t.getNano(), 1); + assertEquals(1, t.getNano()); t = t.withNano(10); - assertEquals(t.getNano(), 10); + assertEquals(10, t.getNano()); t = t.withNano(100); - assertEquals(t.getNano(), 100); + assertEquals(100, t.getNano()); t = t.withNano(999999999); - assertEquals(t.getNano(), 999999999); + assertEquals(999999999, t.getNano()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withNanoOfSecond_nanoTooLow() { - TEST_2007_07_15_12_30_40_987654321.withNano(-1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withNano(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withNanoOfSecond_nanoTooHigh() { - TEST_2007_07_15_12_30_40_987654321.withNano(1000000000); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2007_07_15_12_30_40_987654321.withNano(1000000000)); } //----------------------------------------------------------------------- @@ -1357,14 +1375,14 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_truncatedTo_normal() { - assertEquals(TEST_2007_07_15_12_30_40_987654321.truncatedTo(NANOS), TEST_2007_07_15_12_30_40_987654321); - assertEquals(TEST_2007_07_15_12_30_40_987654321.truncatedTo(SECONDS), TEST_2007_07_15_12_30_40_987654321.withNano(0)); - assertEquals(TEST_2007_07_15_12_30_40_987654321.truncatedTo(DAYS), TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT)); + assertEquals(TEST_2007_07_15_12_30_40_987654321, TEST_2007_07_15_12_30_40_987654321.truncatedTo(NANOS)); + assertEquals(TEST_2007_07_15_12_30_40_987654321.withNano(0), TEST_2007_07_15_12_30_40_987654321.truncatedTo(SECONDS)); + assertEquals(TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT), TEST_2007_07_15_12_30_40_987654321.truncatedTo(DAYS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_truncatedTo_null() { - TEST_2007_07_15_12_30_40_987654321.truncatedTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.truncatedTo(null)); } //----------------------------------------------------------------------- @@ -1374,31 +1392,35 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { public void test_plus_TemporalAmount_positiveMonths() { MockSimplePeriod period = MockSimplePeriod.of(7, MONTHS); LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.plus(period); - assertEquals(t, LocalDateTime.of(2008, 2, 15, 12, 30, 40, 987654321)); + assertEquals(LocalDateTime.of(2008, 2, 15, 12, 30, 40, 987654321), t); } @Test public void test_plus_TemporalAmount_negativeDays() { MockSimplePeriod period = MockSimplePeriod.of(-25, DAYS); LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.plus(period); - assertEquals(t, LocalDateTime.of(2007, 6, 20, 12, 30, 40, 987654321)); + assertEquals(LocalDateTime.of(2007, 6, 20, 12, 30, 40, 987654321), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_TemporalAmount_invalidTooLarge() { - MockSimplePeriod period = MockSimplePeriod.of(1, YEARS); - LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).plus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + MockSimplePeriod period = MockSimplePeriod.of(1, YEARS); + LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).plus(period); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_TemporalAmount_invalidTooSmall() { - MockSimplePeriod period = MockSimplePeriod.of(-1, YEARS); - LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).plus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + MockSimplePeriod period = MockSimplePeriod.of(-1, YEARS); + LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).plus(period); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_TemporalAmount_null() { - TEST_2007_07_15_12_30_40_987654321.plus((TemporalAmount) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.plus((TemporalAmount) null)); } //----------------------------------------------------------------------- @@ -1407,28 +1429,28 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_plus_longTemporalUnit_positiveMonths() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.plus(7, ChronoUnit.MONTHS); - assertEquals(t, LocalDateTime.of(2008, 2, 15, 12, 30, 40, 987654321)); + assertEquals(LocalDateTime.of(2008, 2, 15, 12, 30, 40, 987654321), t); } @Test public void test_plus_longTemporalUnit_negativeDays() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.plus(-25, ChronoUnit.DAYS); - assertEquals(t, LocalDateTime.of(2007, 6, 20, 12, 30, 40, 987654321)); + assertEquals(LocalDateTime.of(2007, 6, 20, 12, 30, 40, 987654321), t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_longTemporalUnit_null() { - TEST_2007_07_15_12_30_40_987654321.plus(1, (TemporalUnit) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.plus(1, (TemporalUnit) null)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_longTemporalUnit_invalidTooLarge() { - LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).plus(1, ChronoUnit.YEARS); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).plus(1, ChronoUnit.YEARS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_longTemporalUnit_invalidTooSmall() { - LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).plus(-1, ChronoUnit.YEARS); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).plus(-1, ChronoUnit.YEARS)); } //----------------------------------------------------------------------- @@ -1452,14 +1474,14 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, 2009, 2, 28, 0, 0, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_int_invalidTooLarge() { - createDateMidnight(Year.MAX_VALUE, 1, 1).plusYears(1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MAX_VALUE, 1, 1).plusYears(1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_int_invalidTooSmall() { - LocalDate.of(Year.MIN_VALUE, 1, 1).plusYears(-1); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.of(Year.MIN_VALUE, 1, 1).plusYears(-1)); } //----------------------------------------------------------------------- @@ -1507,20 +1529,19 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, 2007, 4, 30, 0, 0, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusMonths_int_invalidTooLarge() { - createDateMidnight(Year.MAX_VALUE, 12, 1).plusMonths(1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MAX_VALUE, 12, 1).plusMonths(1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusMonths_int_invalidTooSmall() { - createDateMidnight(Year.MIN_VALUE, 1, 1).plusMonths(-1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MIN_VALUE, 1, 1).plusMonths(-1)); } //----------------------------------------------------------------------- // plusWeeks() //----------------------------------------------------------------------- - @DataProvider(name="samplePlusWeeksSymmetry") Object[][] provider_samplePlusWeeksSymmetry() { return new Object[][] { {createDateMidnight(-1, 1, 1)}, @@ -1552,14 +1573,15 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="samplePlusWeeksSymmetry") + @ParameterizedTest + @MethodSource("provider_samplePlusWeeksSymmetry") public void test_plusWeeks_symmetry(LocalDateTime reference) { for (int weeks = 0; weeks < 365 * 8; weeks++) { LocalDateTime t = reference.plusWeeks(weeks).plusWeeks(-weeks); - assertEquals(t, reference); + assertEquals(reference, t); t = reference.plusWeeks(-weeks).plusWeeks(weeks); - assertEquals(t, reference); + assertEquals(reference, t); } } @@ -1578,7 +1600,7 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_plusWeeks_overYears() { LocalDateTime t = LocalDateTime.of(2006, 7, 16, 12, 30, 40, 987654321).plusWeeks(52); - assertEquals(t, TEST_2007_07_15_12_30_40_987654321); + assertEquals(TEST_2007_07_15_12_30_40_987654321, t); } @Test @@ -1617,20 +1639,19 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, Year.MIN_VALUE, 1, 1, 0, 0, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusWeeks_invalidTooLarge() { - createDateMidnight(Year.MAX_VALUE, 12, 25).plusWeeks(1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MAX_VALUE, 12, 25).plusWeeks(1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusWeeks_invalidTooSmall() { - createDateMidnight(Year.MIN_VALUE, 1, 7).plusWeeks(-1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MIN_VALUE, 1, 7).plusWeeks(-1)); } //----------------------------------------------------------------------- // plusDays() //----------------------------------------------------------------------- - @DataProvider(name="samplePlusDaysSymmetry") Object[][] provider_samplePlusDaysSymmetry() { return new Object[][] { {createDateMidnight(-1, 1, 1)}, @@ -1662,14 +1683,15 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="samplePlusDaysSymmetry") + @ParameterizedTest + @MethodSource("provider_samplePlusDaysSymmetry") public void test_plusDays_symmetry(LocalDateTime reference) { for (int days = 0; days < 365 * 8; days++) { LocalDateTime t = reference.plusDays(days).plusDays(-days); - assertEquals(t, reference); + assertEquals(reference, t); t = reference.plusDays(-days).plusDays(days); - assertEquals(t, reference); + assertEquals(reference, t); } } @@ -1688,7 +1710,7 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_plusDays_overYears() { LocalDateTime t = LocalDateTime.of(2006, 7, 14, 12, 30, 40, 987654321).plusDays(366); - assertEquals(t, TEST_2007_07_15_12_30_40_987654321); + assertEquals(TEST_2007_07_15_12_30_40_987654321, t); } @Test @@ -1727,24 +1749,24 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, Year.MIN_VALUE, 1, 1, 0, 0, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusDays_invalidTooLarge() { - createDateMidnight(Year.MAX_VALUE, 12, 31).plusDays(1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MAX_VALUE, 12, 31).plusDays(1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusDays_invalidTooSmall() { - createDateMidnight(Year.MIN_VALUE, 1, 1).plusDays(-1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MIN_VALUE, 1, 1).plusDays(-1)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_plusDays_overflowTooLarge() { - createDateMidnight(Year.MAX_VALUE, 12, 31).plusDays(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> createDateMidnight(Year.MAX_VALUE, 12, 31).plusDays(Long.MAX_VALUE)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_plusDays_overflowTooSmall() { - createDateMidnight(Year.MIN_VALUE, 1, 1).plusDays(Long.MIN_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> createDateMidnight(Year.MIN_VALUE, 1, 1).plusDays(Long.MIN_VALUE)); } //----------------------------------------------------------------------- @@ -1762,8 +1784,8 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { d = d.plusDays(1); } - assertEquals(t.toLocalDate(), d); - assertEquals(t.getHour(), (i + 1) % 24); + assertEquals(d, t.toLocalDate()); + assertEquals((i + 1) % 24, t.getHour()); } } @@ -1781,8 +1803,8 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { d = d.plusDays(1); } - assertEquals(dt.toLocalDate(), d); - assertEquals(dt.toLocalTime(), t); + assertEquals(d, dt.toLocalDate()); + assertEquals(t, dt.toLocalTime()); } } @@ -1801,8 +1823,8 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { d = d.plusDays(1); } - assertEquals(dt.toLocalDate(), d); - assertEquals(dt.toLocalTime(), t); + assertEquals(d, dt.toLocalDate()); + assertEquals(t, dt.toLocalTime()); } } @@ -1825,9 +1847,9 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { min = 0; } - assertEquals(t.toLocalDate(), d); - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); + assertEquals(d, t.toLocalDate()); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); } } @@ -1845,15 +1867,15 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { d = d.plusDays(1); } - assertEquals(dt.toLocalDate(), d, String.valueOf(i)); - assertEquals(dt.toLocalTime(), t, String.valueOf(i)); + assertEquals(d, dt.toLocalDate(), String.valueOf(i)); + assertEquals(t, dt.toLocalTime(), String.valueOf(i)); } } @Test public void test_plusMinutes_noChange_oneDay() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.plusMinutes(24 * 60); - assertEquals(t.toLocalDate(), TEST_2007_07_15_12_30_40_987654321.toLocalDate().plusDays(1)); + assertEquals(TEST_2007_07_15_12_30_40_987654321.toLocalDate().plusDays(1), t.toLocalDate()); } //----------------------------------------------------------------------- @@ -1880,14 +1902,13 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { min = 0; } - assertEquals(t.toLocalDate(), d); - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); - assertEquals(t.getSecond(), sec); + assertEquals(d, t.toLocalDate()); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); + assertEquals(sec, t.getSecond()); } } - @DataProvider(name="plusSeconds_fromZero") Iterator plusSeconds_fromZero() { return new Iterator() { int delta = 30; @@ -1934,21 +1955,22 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="plusSeconds_fromZero") + @ParameterizedTest + @MethodSource("plusSeconds_fromZero") public void test_plusSeconds_fromZero(int seconds, LocalDate date, int hour, int min, int sec) { LocalDateTime base = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT); LocalDateTime t = base.plusSeconds(seconds); - assertEquals(date, t.toLocalDate()); - assertEquals(hour, t.getHour()); - assertEquals(min, t.getMinute()); - assertEquals(sec, t.getSecond()); + assertEquals(t.toLocalDate(), date); + assertEquals(t.getHour(), hour); + assertEquals(t.getMinute(), min); + assertEquals(t.getSecond(), sec); } @Test public void test_plusSeconds_noChange_oneDay() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.plusSeconds(24 * 60 * 60); - assertEquals(t.toLocalDate(), TEST_2007_07_15_12_30_40_987654321.toLocalDate().plusDays(1)); + assertEquals(TEST_2007_07_15_12_30_40_987654321.toLocalDate().plusDays(1), t.toLocalDate()); } //----------------------------------------------------------------------- @@ -1980,15 +2002,14 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { min = 0; } - assertEquals(t.toLocalDate(), d, String.valueOf(i)); - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); - assertEquals(t.getSecond(), sec); - assertEquals(t.getNano(), nanos); + assertEquals(d, t.toLocalDate(), String.valueOf(i)); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); + assertEquals(sec, t.getSecond()); + assertEquals(nanos, t.getNano()); } } - @DataProvider(name="plusNanos_fromZero") Iterator plusNanos_fromZero() { return new Iterator() { long delta = 7500000000L; @@ -2038,22 +2059,23 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="plusNanos_fromZero") + @ParameterizedTest + @MethodSource("plusNanos_fromZero") public void test_plusNanos_fromZero(long nanoseconds, LocalDate date, int hour, int min, int sec, int nanos) { LocalDateTime base = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT); LocalDateTime t = base.plusNanos(nanoseconds); - assertEquals(date, t.toLocalDate()); - assertEquals(hour, t.getHour()); - assertEquals(min, t.getMinute()); - assertEquals(sec, t.getSecond()); - assertEquals(nanos, t.getNano()); + assertEquals(t.toLocalDate(), date); + assertEquals(t.getHour(), hour); + assertEquals(t.getMinute(), min); + assertEquals(t.getSecond(), sec); + assertEquals(t.getNano(), nanos); } @Test public void test_plusNanos_noChange_oneDay() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.plusNanos(24 * 60 * 60 * 1000000000L); - assertEquals(t.toLocalDate(), TEST_2007_07_15_12_30_40_987654321.toLocalDate().plusDays(1)); + assertEquals(TEST_2007_07_15_12_30_40_987654321.toLocalDate().plusDays(1), t.toLocalDate()); } //----------------------------------------------------------------------- @@ -2063,31 +2085,35 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { public void test_minus_TemporalAmount_positiveMonths() { MockSimplePeriod period = MockSimplePeriod.of(7, MONTHS); LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.minus(period); - assertEquals(t, LocalDateTime.of(2006, 12, 15, 12, 30, 40, 987654321)); + assertEquals(LocalDateTime.of(2006, 12, 15, 12, 30, 40, 987654321), t); } @Test public void test_minus_TemporalAmount_negativeDays() { MockSimplePeriod period = MockSimplePeriod.of(-25, DAYS); LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.minus(period); - assertEquals(t, LocalDateTime.of(2007, 8, 9, 12, 30, 40, 987654321)); + assertEquals(LocalDateTime.of(2007, 8, 9, 12, 30, 40, 987654321), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_TemporalAmount_invalidTooLarge() { - MockSimplePeriod period = MockSimplePeriod.of(-1, YEARS); - LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).minus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + MockSimplePeriod period = MockSimplePeriod.of(-1, YEARS); + LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).minus(period); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_TemporalAmount_invalidTooSmall() { - MockSimplePeriod period = MockSimplePeriod.of(1, YEARS); - LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).minus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + MockSimplePeriod period = MockSimplePeriod.of(1, YEARS); + LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).minus(period); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_minus_TemporalAmount_null() { - TEST_2007_07_15_12_30_40_987654321.minus((TemporalAmount) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.minus((TemporalAmount) null)); } //----------------------------------------------------------------------- @@ -2096,28 +2122,28 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_minus_longTemporalUnit_positiveMonths() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.minus(7, ChronoUnit.MONTHS); - assertEquals(t, LocalDateTime.of(2006, 12, 15, 12, 30, 40, 987654321)); + assertEquals(LocalDateTime.of(2006, 12, 15, 12, 30, 40, 987654321), t); } @Test public void test_minus_longTemporalUnit_negativeDays() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.minus(-25, ChronoUnit.DAYS); - assertEquals(t, LocalDateTime.of(2007, 8, 9, 12, 30, 40, 987654321)); + assertEquals(LocalDateTime.of(2007, 8, 9, 12, 30, 40, 987654321), t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_minus_longTemporalUnit_null() { - TEST_2007_07_15_12_30_40_987654321.minus(1, (TemporalUnit) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.minus(1, (TemporalUnit) null)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_longTemporalUnit_invalidTooLarge() { - LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).minus(-1, ChronoUnit.YEARS); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).minus(-1, ChronoUnit.YEARS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_longTemporalUnit_invalidTooSmall() { - LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).minus(1, ChronoUnit.YEARS); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0).minus(1, ChronoUnit.YEARS)); } //----------------------------------------------------------------------- @@ -2141,14 +2167,14 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, 2007, 2, 28, 0, 0, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_int_invalidTooLarge() { - createDateMidnight(Year.MAX_VALUE, 1, 1).minusYears(-1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MAX_VALUE, 1, 1).minusYears(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_int_invalidTooSmall() { - createDateMidnight(Year.MIN_VALUE, 1, 1).minusYears(1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MIN_VALUE, 1, 1).minusYears(1)); } //----------------------------------------------------------------------- @@ -2196,20 +2222,19 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, 2007, 2, 28, 0, 0, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusMonths_int_invalidTooLarge() { - createDateMidnight(Year.MAX_VALUE, 12, 1).minusMonths(-1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MAX_VALUE, 12, 1).minusMonths(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusMonths_int_invalidTooSmall() { - createDateMidnight(Year.MIN_VALUE, 1, 1).minusMonths(1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MIN_VALUE, 1, 1).minusMonths(1)); } //----------------------------------------------------------------------- // minusWeeks() //----------------------------------------------------------------------- - @DataProvider(name="sampleMinusWeeksSymmetry") Object[][] provider_sampleMinusWeeksSymmetry() { return new Object[][] { {createDateMidnight(-1, 1, 1)}, @@ -2241,14 +2266,15 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleMinusWeeksSymmetry") + @ParameterizedTest + @MethodSource("provider_sampleMinusWeeksSymmetry") public void test_minusWeeks_symmetry(LocalDateTime reference) { for (int weeks = 0; weeks < 365 * 8; weeks++) { LocalDateTime t = reference.minusWeeks(weeks).minusWeeks(-weeks); - assertEquals(t, reference); + assertEquals(reference, t); t = reference.minusWeeks(-weeks).minusWeeks(weeks); - assertEquals(t, reference); + assertEquals(reference, t); } } @@ -2267,7 +2293,7 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_minusWeeks_overYears() { LocalDateTime t = LocalDateTime.of(2008, 7, 13, 12, 30, 40, 987654321).minusWeeks(52); - assertEquals(t, TEST_2007_07_15_12_30_40_987654321); + assertEquals(TEST_2007_07_15_12_30_40_987654321, t); } @Test @@ -2306,20 +2332,19 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, Year.MIN_VALUE, 1, 1, 0, 0, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusWeeks_invalidTooLarge() { - createDateMidnight(Year.MAX_VALUE, 12, 25).minusWeeks(-1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MAX_VALUE, 12, 25).minusWeeks(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusWeeks_invalidTooSmall() { - createDateMidnight(Year.MIN_VALUE, 1, 7).minusWeeks(1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MIN_VALUE, 1, 7).minusWeeks(1)); } //----------------------------------------------------------------------- // minusDays() //----------------------------------------------------------------------- - @DataProvider(name="sampleMinusDaysSymmetry") Object[][] provider_sampleMinusDaysSymmetry() { return new Object[][] { {createDateMidnight(-1, 1, 1)}, @@ -2351,14 +2376,15 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleMinusDaysSymmetry") + @ParameterizedTest + @MethodSource("provider_sampleMinusDaysSymmetry") public void test_minusDays_symmetry(LocalDateTime reference) { for (int days = 0; days < 365 * 8; days++) { LocalDateTime t = reference.minusDays(days).minusDays(-days); - assertEquals(t, reference); + assertEquals(reference, t); t = reference.minusDays(-days).minusDays(days); - assertEquals(t, reference); + assertEquals(reference, t); } } @@ -2377,13 +2403,13 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_minusDays_overYears() { LocalDateTime t = LocalDateTime.of(2008, 7, 16, 12, 30, 40, 987654321).minusDays(367); - assertEquals(t, TEST_2007_07_15_12_30_40_987654321); + assertEquals(TEST_2007_07_15_12_30_40_987654321, t); } @Test public void test_minusDays_overLeapYears() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.plusYears(2).minusDays(365 + 366); - assertEquals(t, TEST_2007_07_15_12_30_40_987654321); + assertEquals(TEST_2007_07_15_12_30_40_987654321, t); } @Test @@ -2416,24 +2442,24 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { check(t, Year.MIN_VALUE, 1, 1, 0, 0, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusDays_invalidTooLarge() { - createDateMidnight(Year.MAX_VALUE, 12, 31).minusDays(-1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MAX_VALUE, 12, 31).minusDays(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusDays_invalidTooSmall() { - createDateMidnight(Year.MIN_VALUE, 1, 1).minusDays(1); + Assertions.assertThrows(DateTimeException.class, () -> createDateMidnight(Year.MIN_VALUE, 1, 1).minusDays(1)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_minusDays_overflowTooLarge() { - createDateMidnight(Year.MAX_VALUE, 12, 31).minusDays(Long.MIN_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> createDateMidnight(Year.MAX_VALUE, 12, 31).minusDays(Long.MIN_VALUE)); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_minusDays_overflowTooSmall() { - createDateMidnight(Year.MIN_VALUE, 1, 1).minusDays(Long.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> createDateMidnight(Year.MIN_VALUE, 1, 1).minusDays(Long.MAX_VALUE)); } //----------------------------------------------------------------------- @@ -2451,8 +2477,8 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { d = d.minusDays(1); } - assertEquals(t.toLocalDate(), d); - assertEquals(t.getHour(), (((-i + 23) % 24) + 24) % 24); + assertEquals(d, t.toLocalDate()); + assertEquals((((-i + 23) % 24) + 24) % 24, t.getHour()); } } @@ -2470,8 +2496,8 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { d = d.minusDays(1); } - assertEquals(dt.toLocalDate(), d, String.valueOf(i)); - assertEquals(dt.toLocalTime(), t); + assertEquals(d, dt.toLocalDate(), String.valueOf(i)); + assertEquals(t, dt.toLocalTime()); } } @@ -2490,8 +2516,8 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { d = d.minusDays(1); } - assertEquals(dt.toLocalDate(), d, String.valueOf(i)); - assertEquals(dt.toLocalTime(), t); + assertEquals(d, dt.toLocalDate(), String.valueOf(i)); + assertEquals(t, dt.toLocalTime()); } } @@ -2517,9 +2543,9 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { hour = 23; } } - assertEquals(t.toLocalDate(), d); - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); + assertEquals(d, t.toLocalDate()); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); } } @@ -2537,15 +2563,15 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { d = d.plusDays(1); } - assertEquals(dt.toLocalDate(), d); - assertEquals(dt.toLocalTime(), t); + assertEquals(d, dt.toLocalDate()); + assertEquals(t, dt.toLocalTime()); } } @Test public void test_minusMinutes_noChange_oneDay() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.minusMinutes(24 * 60); - assertEquals(t.toLocalDate(), TEST_2007_07_15_12_30_40_987654321.toLocalDate().minusDays(1)); + assertEquals(TEST_2007_07_15_12_30_40_987654321.toLocalDate().minusDays(1), t.toLocalDate()); } //----------------------------------------------------------------------- @@ -2577,14 +2603,13 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { } } - assertEquals(t.toLocalDate(), d); - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); - assertEquals(t.getSecond(), sec); + assertEquals(d, t.toLocalDate()); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); + assertEquals(sec, t.getSecond()); } } - @DataProvider(name="minusSeconds_fromZero") Iterator minusSeconds_fromZero() { return new Iterator() { int delta = 30; @@ -2631,15 +2656,16 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="minusSeconds_fromZero") + @ParameterizedTest + @MethodSource("minusSeconds_fromZero") public void test_minusSeconds_fromZero(int seconds, LocalDate date, int hour, int min, int sec) { LocalDateTime base = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT); LocalDateTime t = base.minusSeconds(seconds); - assertEquals(date, t.toLocalDate()); - assertEquals(hour, t.getHour()); - assertEquals(min, t.getMinute()); - assertEquals(sec, t.getSecond()); + assertEquals(t.toLocalDate(), date); + assertEquals(t.getHour(), hour); + assertEquals(t.getMinute(), min); + assertEquals(t.getSecond(), sec); } //----------------------------------------------------------------------- @@ -2678,15 +2704,14 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { } } - assertEquals(t.toLocalDate(), d); - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); - assertEquals(t.getSecond(), sec); - assertEquals(t.getNano(), nanos); + assertEquals(d, t.toLocalDate()); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); + assertEquals(sec, t.getSecond()); + assertEquals(nanos, t.getNano()); } } - @DataProvider(name="minusNanos_fromZero") Iterator minusNanos_fromZero() { return new Iterator() { long delta = 7500000000L; @@ -2736,22 +2761,22 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="minusNanos_fromZero") + @ParameterizedTest + @MethodSource("minusNanos_fromZero") public void test_minusNanos_fromZero(long nanoseconds, LocalDate date, int hour, int min, int sec, int nanos) { LocalDateTime base = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT); LocalDateTime t = base.minusNanos(nanoseconds); - assertEquals(date, t.toLocalDate()); - assertEquals(hour, t.getHour()); - assertEquals(min, t.getMinute()); - assertEquals(sec, t.getSecond()); - assertEquals(nanos, t.getNano()); + assertEquals(t.toLocalDate(), date); + assertEquals(t.getHour(), hour); + assertEquals(t.getMinute(), min); + assertEquals(t.getSecond(), sec); + assertEquals(t.getNano(), nanos); } //----------------------------------------------------------------------- // until(Temporal, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="periodUntilUnit") Object[][] data_periodUntilUnit() { return new Object[][] { // date only @@ -2889,45 +2914,50 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit(LocalDateTime dt1, LocalDateTime dt2, TemporalUnit unit, long expected) { long amount = dt1.until(dt2, unit); - assertEquals(amount, expected); + assertEquals(expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_negated(LocalDateTime dt1, LocalDateTime dt2, TemporalUnit unit, long expected) { long amount = dt2.until(dt1, unit); - assertEquals(amount, -expected); + assertEquals(-expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_between(LocalDateTime dt1, LocalDateTime dt2, TemporalUnit unit, long expected) { long amount = unit.between(dt1, dt2); - assertEquals(amount, expected); + assertEquals(expected, amount); } @Test public void test_until_convertedType() { LocalDateTime start = LocalDateTime.of(2010, 6, 30, 2, 30); OffsetDateTime end = start.plusDays(2).atOffset(OFFSET_PONE); - assertEquals(start.until(end, DAYS), 2); + assertEquals(2, start.until(end, DAYS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_invalidType() { - LocalDateTime start = LocalDateTime.of(2010, 6, 30, 2, 30); - start.until(LocalTime.of(11, 30), DAYS); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalDateTime start = LocalDateTime.of(2010, 6, 30, 2, 30); + start.until(LocalTime.of(11, 30), DAYS); + }); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullEnd() { - TEST_2007_07_15_12_30_40_987654321.until(null, HOURS); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.until(null, HOURS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullUnit() { - TEST_2007_07_15_12_30_40_987654321.until(TEST_2007_07_15_12_30_40_987654321, null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.until(TEST_2007_07_15_12_30_40_987654321, null)); } //----------------------------------------------------------------------- @@ -2937,12 +2967,12 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { public void test_format_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); String t = LocalDateTime.of(2010, 12, 3, 11, 30, 45).format(f); - assertEquals(t, "2010 12 3 11 30 45"); + assertEquals("2010 12 3 11 30 45", t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_format_formatter_null() { - LocalDateTime.of(2010, 12, 3, 11, 30, 45).format(null); + Assertions.assertThrows(NullPointerException.class, () -> LocalDateTime.of(2010, 12, 3, 11, 30, 45).format(null)); } //----------------------------------------------------------------------- @@ -2951,13 +2981,15 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_atOffset() { LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30); - assertEquals(t.atOffset(OFFSET_PTWO), OffsetDateTime.of(LocalDateTime.of(2008, 6, 30, 11, 30), OFFSET_PTWO)); + assertEquals(OffsetDateTime.of(LocalDateTime.of(2008, 6, 30, 11, 30), OFFSET_PTWO), t.atOffset(OFFSET_PTWO)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atOffset_nullZoneOffset() { - LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30); - t.atOffset((ZoneOffset) null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30); + t.atOffset((ZoneOffset) null); + }); } //----------------------------------------------------------------------- @@ -2966,34 +2998,33 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_atZone() { LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30); - assertEquals(t.atZone(ZONE_PARIS), - ZonedDateTime.of(LocalDateTime.of(2008, 6, 30, 11, 30), ZONE_PARIS)); + assertEquals(ZonedDateTime.of(LocalDateTime.of(2008, 6, 30, 11, 30), ZONE_PARIS), t.atZone(ZONE_PARIS)); } @Test public void test_atZone_Offset() { LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30); - assertEquals(t.atZone(OFFSET_PTWO), ZonedDateTime.of(LocalDateTime.of(2008, 6, 30, 11, 30), OFFSET_PTWO)); + assertEquals(ZonedDateTime.of(LocalDateTime.of(2008, 6, 30, 11, 30), OFFSET_PTWO), t.atZone(OFFSET_PTWO)); } @Test public void test_atZone_dstGap() { LocalDateTime t = LocalDateTime.of(2007, 4, 1, 0, 0); - assertEquals(t.atZone(ZONE_GAZA), - ZonedDateTime.of(LocalDateTime.of(2007, 4, 1, 1, 0), ZONE_GAZA)); + assertEquals(ZonedDateTime.of(LocalDateTime.of(2007, 4, 1, 1, 0), ZONE_GAZA), t.atZone(ZONE_GAZA)); } @Test public void test_atZone_dstOverlap() { LocalDateTime t = LocalDateTime.of(2007, 10, 28, 2, 30); - assertEquals(t.atZone(ZONE_PARIS), - ZonedDateTime.ofStrict(LocalDateTime.of(2007, 10, 28, 2, 30), OFFSET_PTWO, ZONE_PARIS)); + assertEquals(ZonedDateTime.ofStrict(LocalDateTime.of(2007, 10, 28, 2, 30), OFFSET_PTWO, ZONE_PARIS), t.atZone(ZONE_PARIS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atZone_nullTimeZone() { - LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30); - t.atZone((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30); + t.atZone((ZoneId) null); + }); } //----------------------------------------------------------------------- @@ -3005,7 +3036,7 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { ZoneOffset offset = ZoneOffset.ofHours(i); for (int j = 0; j < 100000; j++) { LocalDateTime a = LocalDateTime.of(1970, 1, 1, 0, 0).plusSeconds(j); - assertEquals(a.toEpochSecond(offset), j - i * 3600); + assertEquals(j - i * 3600, a.toEpochSecond(offset)); } } } @@ -3014,7 +3045,7 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { public void test_toEpochSecond_beforeEpoch() { for (int i = 0; i < 100000; i++) { LocalDateTime a = LocalDateTime.of(1970, 1, 1, 0, 0).minusSeconds(i); - assertEquals(a.toEpochSecond(ZoneOffset.UTC), -i); + assertEquals(-i, a.toEpochSecond(ZoneOffset.UTC)); } } @@ -3084,50 +3115,51 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { LocalDateTime b = localDateTimes[j]; if (i < j) { assertTrue(a.compareTo(b) < 0, a + " <=> " + b); - assertEquals(a.isBefore(b), true, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { assertTrue(a.compareTo(b) > 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(true, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_ObjectNull() { - TEST_2007_07_15_12_30_40_987654321.compareTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.compareTo(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isBefore_ObjectNull() { - TEST_2007_07_15_12_30_40_987654321.isBefore(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.isBefore(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isAfter_ObjectNull() { - TEST_2007_07_15_12_30_40_987654321.isAfter(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2007_07_15_12_30_40_987654321.isAfter(null)); } - @Test(expectedExceptions=ClassCastException.class) @SuppressWarnings({"unchecked", "rawtypes"}) + @Test public void compareToNonLocalDateTime() { - Comparable c = TEST_2007_07_15_12_30_40_987654321; - c.compareTo(new Object()); + Assertions.assertThrows(ClassCastException.class, () -> { + Comparable c = TEST_2007_07_15_12_30_40_987654321; + c.compareTo(new Object()); + }); } //----------------------------------------------------------------------- // equals() //----------------------------------------------------------------------- - @DataProvider(name="sampleDateTimes") Iterator provider_sampleDateTimes() { return new Iterator() { Object[][] sampleDates = provider_sampleDates(); @@ -3162,56 +3194,64 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleDateTimes") + @ParameterizedTest + @MethodSource("provider_sampleDateTimes") public void test_equals_true(int y, int m, int d, int h, int mi, int s, int n) { LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n); LocalDateTime b = LocalDateTime.of(y, m, d, h, mi, s, n); assertTrue(a.equals(b)); } - @Test(dataProvider="sampleDateTimes") + @ParameterizedTest + @MethodSource("provider_sampleDateTimes") public void test_equals_false_year_differs(int y, int m, int d, int h, int mi, int s, int n) { LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n); LocalDateTime b = LocalDateTime.of(y + 1, m, d, h, mi, s, n); assertFalse(a.equals(b)); } - @Test(dataProvider="sampleDateTimes") + @ParameterizedTest + @MethodSource("provider_sampleDateTimes") public void test_equals_false_month_differs(int y, int m, int d, int h, int mi, int s, int n) { LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n); LocalDateTime b = LocalDateTime.of(y, m + 1, d, h, mi, s, n); assertFalse(a.equals(b)); } - @Test(dataProvider="sampleDateTimes") + @ParameterizedTest + @MethodSource("provider_sampleDateTimes") public void test_equals_false_day_differs(int y, int m, int d, int h, int mi, int s, int n) { LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n); LocalDateTime b = LocalDateTime.of(y, m, d + 1, h, mi, s, n); assertFalse(a.equals(b)); } - @Test(dataProvider="sampleDateTimes") + @ParameterizedTest + @MethodSource("provider_sampleDateTimes") public void test_equals_false_hour_differs(int y, int m, int d, int h, int mi, int s, int n) { LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n); LocalDateTime b = LocalDateTime.of(y, m, d, h + 1, mi, s, n); assertFalse(a.equals(b)); } - @Test(dataProvider="sampleDateTimes") + @ParameterizedTest + @MethodSource("provider_sampleDateTimes") public void test_equals_false_minute_differs(int y, int m, int d, int h, int mi, int s, int n) { LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n); LocalDateTime b = LocalDateTime.of(y, m, d, h, mi + 1, s, n); assertFalse(a.equals(b)); } - @Test(dataProvider="sampleDateTimes") + @ParameterizedTest + @MethodSource("provider_sampleDateTimes") public void test_equals_false_second_differs(int y, int m, int d, int h, int mi, int s, int n) { LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n); LocalDateTime b = LocalDateTime.of(y, m, d, h, mi, s + 1, n); assertFalse(a.equals(b)); } - @Test(dataProvider="sampleDateTimes") + @ParameterizedTest + @MethodSource("provider_sampleDateTimes") public void test_equals_false_nano_differs(int y, int m, int d, int h, int mi, int s, int n) { LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n); LocalDateTime b = LocalDateTime.of(y, m, d, h, mi, s, n + 1); @@ -3220,34 +3260,34 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { @Test public void test_equals_itself_true() { - assertEquals(TEST_2007_07_15_12_30_40_987654321.equals(TEST_2007_07_15_12_30_40_987654321), true); + assertEquals(true, TEST_2007_07_15_12_30_40_987654321.equals(TEST_2007_07_15_12_30_40_987654321)); } @Test public void test_equals_string_false() { - assertEquals(TEST_2007_07_15_12_30_40_987654321.equals("2007-07-15T12:30:40.987654321"), false); + assertEquals(false, TEST_2007_07_15_12_30_40_987654321.equals("2007-07-15T12:30:40.987654321")); } @Test public void test_equals_null_false() { - assertEquals(TEST_2007_07_15_12_30_40_987654321.equals(null), false); + assertEquals(false, TEST_2007_07_15_12_30_40_987654321.equals(null)); } //----------------------------------------------------------------------- // hashCode() //----------------------------------------------------------------------- - @Test(dataProvider="sampleDateTimes") + @ParameterizedTest + @MethodSource("provider_sampleDateTimes") public void test_hashCode(int y, int m, int d, int h, int mi, int s, int n) { LocalDateTime a = LocalDateTime.of(y, m, d, h, mi, s, n); assertEquals(a.hashCode(), a.hashCode()); LocalDateTime b = LocalDateTime.of(y, m, d, h, mi, s, n); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="sampleToString") Object[][] provider_sampleToString() { return new Object[][] { {2008, 7, 5, 2, 1, 0, 0, "2008-07-05T02:01"}, @@ -3258,11 +3298,12 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_toString(int y, int m, int d, int h, int mi, int s, int n, String expected) { LocalDateTime t = LocalDateTime.of(y, m, d, h, mi, s, n); String str = t.toString(); - assertEquals(str, expected); + assertEquals(expected, str); } private LocalDateTime dtNoon(int year, int month, int day) { diff --git a/test/jdk/java/time/tck/java/time/TCKLocalTime.java b/test/jdk/java/time/tck/java/time/TCKLocalTime.java index 06f21613b04..e2fc4ea2ca7 100644 --- a/test/jdk/java/time/tck/java/time/TCKLocalTime.java +++ b/test/jdk/java/time/tck/java/time/TCKLocalTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -86,11 +86,12 @@ import static java.time.temporal.ChronoUnit.NANOS; import static java.time.temporal.ChronoUnit.SECONDS; import static java.time.temporal.ChronoUnit.WEEKS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.Clock; import java.time.DateTimeException; @@ -127,14 +128,17 @@ import java.util.EnumSet; import java.util.Iterator; import java.util.List; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test LocalTime. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKLocalTime extends AbstractDateTimeTest { private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2); @@ -149,7 +153,7 @@ public class TCKLocalTime extends AbstractDateTimeTest { INVALID_UNITS = set.toArray(new TemporalUnit[set.size()]); } - @BeforeMethod + @BeforeEach public void setUp() { TEST_12_30_40_987654321 = LocalTime.of(12, 30, 40, 987654321); } @@ -157,7 +161,8 @@ public class TCKLocalTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Override protected List samples() { - TemporalAccessor[] array = {TEST_12_30_40_987654321, LocalTime.MIN, LocalTime.MAX, LocalTime.MIDNIGHT, LocalTime.NOON}; + TemporalAccessor[] array = {LocalTime.of(12, 30, 40, 987654321), + LocalTime.MIN, LocalTime.MAX, LocalTime.MIDNIGHT, LocalTime.NOON}; return Arrays.asList(array); } @@ -196,13 +201,13 @@ public class TCKLocalTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- private void check(LocalTime test, int h, int m, int s, int n) { - assertEquals(test.getHour(), h); - assertEquals(test.getMinute(), m); - assertEquals(test.getSecond(), s); - assertEquals(test.getNano(), n); + assertEquals(h, test.getHour()); + assertEquals(m, test.getMinute()); + assertEquals(s, test.getSecond()); + assertEquals(n, test.getNano()); assertEquals(test, test); assertEquals(test.hashCode(), test.hashCode()); - assertEquals(LocalTime.of(h, m, s, n), test); + assertEquals(test, LocalTime.of(h, m, s, n)); } //----------------------------------------------------------------------- @@ -231,9 +236,9 @@ public class TCKLocalTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- // now(ZoneId) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_ZoneId_nullZoneId() { - LocalTime.now((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalTime.now((ZoneId) null)); } @Test @@ -241,16 +246,15 @@ public class TCKLocalTime extends AbstractDateTimeTest { ZoneId zone = ZoneId.of("UTC+01:02:03"); LocalTime expected = LocalTime.now(Clock.system(zone)); LocalTime test = LocalTime.now(zone); - assertEquals(Duration.between(expected, test).truncatedTo(ChronoUnit.SECONDS), - Duration.ZERO); + assertEquals(Duration.ZERO, Duration.between(expected, test).truncatedTo(ChronoUnit.SECONDS)); } //----------------------------------------------------------------------- // now(Clock) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullClock() { - LocalTime.now((Clock) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalTime.now((Clock) null)); } @Test @@ -259,10 +263,10 @@ public class TCKLocalTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i, 8); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); LocalTime test = LocalTime.now(clock); - assertEquals(test.getHour(), (i / (60 * 60)) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); - assertEquals(test.getNano(), 8); + assertEquals((i / (60 * 60)) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); + assertEquals(8, test.getNano()); } } @@ -272,10 +276,10 @@ public class TCKLocalTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i, 8); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); LocalTime test = LocalTime.now(clock); - assertEquals(test.getHour(), ((i + 24 * 60 * 60) / (60 * 60)) % 24); - assertEquals(test.getMinute(), ((i + 24 * 60 * 60) / 60) % 60); - assertEquals(test.getSecond(), (i + 24 * 60 * 60) % 60); - assertEquals(test.getNano(), 8); + assertEquals(((i + 24 * 60 * 60) / (60 * 60)) % 24, test.getHour()); + assertEquals(((i + 24 * 60 * 60) / 60) % 60, test.getMinute()); + assertEquals((i + 24 * 60 * 60) % 60, test.getSecond()); + assertEquals(8, test.getNano()); } } @@ -284,20 +288,20 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void now_Clock_max() { Clock clock = Clock.fixed(Instant.MAX, ZoneOffset.UTC); LocalTime test = LocalTime.now(clock); - assertEquals(test.getHour(), 23); - assertEquals(test.getMinute(), 59); - assertEquals(test.getSecond(), 59); - assertEquals(test.getNano(), 999_999_999); + assertEquals(23, test.getHour()); + assertEquals(59, test.getMinute()); + assertEquals(59, test.getSecond()); + assertEquals(999_999_999, test.getNano()); } @Test public void now_Clock_min() { Clock clock = Clock.fixed(Instant.MIN, ZoneOffset.UTC); LocalTime test = LocalTime.now(clock); - assertEquals(test.getHour(), 0); - assertEquals(test.getMinute(), 0); - assertEquals(test.getSecond(), 0); - assertEquals(test.getNano(), 0); + assertEquals(0, test.getHour()); + assertEquals(0, test.getMinute()); + assertEquals(0, test.getSecond()); + assertEquals(0, test.getNano()); } //----------------------------------------------------------------------- @@ -309,24 +313,24 @@ public class TCKLocalTime extends AbstractDateTimeTest { check(test, 12, 30, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_2ints_hourTooLow() { - LocalTime.of(-1, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(-1, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_2ints_hourTooHigh() { - LocalTime.of(24, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(24, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_2ints_minuteTooLow() { - LocalTime.of(0, -1); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_2ints_minuteTooHigh() { - LocalTime.of(0, 60); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, 60)); } //----------------------------------------------------------------------- @@ -336,34 +340,34 @@ public class TCKLocalTime extends AbstractDateTimeTest { check(test, 12, 30, 40, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_3ints_hourTooLow() { - LocalTime.of(-1, 0, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(-1, 0, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_3ints_hourTooHigh() { - LocalTime.of(24, 0, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(24, 0, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_3ints_minuteTooLow() { - LocalTime.of(0, -1, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, -1, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_3ints_minuteTooHigh() { - LocalTime.of(0, 60, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, 60, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_3ints_secondTooLow() { - LocalTime.of(0, 0, -1); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, 0, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_3ints_secondTooHigh() { - LocalTime.of(0, 0, 60); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, 0, 60)); } //----------------------------------------------------------------------- @@ -375,50 +379,49 @@ public class TCKLocalTime extends AbstractDateTimeTest { check(test, 12, 0, 40, 987654321); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_4ints_hourTooLow() { - LocalTime.of(-1, 0, 0, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(-1, 0, 0, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_4ints_hourTooHigh() { - LocalTime.of(24, 0, 0, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(24, 0, 0, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_4ints_minuteTooLow() { - LocalTime.of(0, -1, 0, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, -1, 0, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_4ints_minuteTooHigh() { - LocalTime.of(0, 60, 0, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, 60, 0, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_4ints_secondTooLow() { - LocalTime.of(0, 0, -1, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, 0, -1, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_4ints_secondTooHigh() { - LocalTime.of(0, 0, 60, 0); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, 0, 60, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_4ints_nanoTooLow() { - LocalTime.of(0, 0, 0, -1); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, 0, 0, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_time_4ints_nanoTooHigh() { - LocalTime.of(0, 0, 0, 1000000000); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.of(0, 0, 0, 1000000000)); } //----------------------------------------------------------------------- // ofInstant() //----------------------------------------------------------------------- - @DataProvider(name="instantFactory") Object[][] data_instantFactory() { return new Object[][] { {Instant.ofEpochSecond(86400 + 3600 + 120 + 4, 500), ZONE_PARIS, LocalTime.of(2, 2, 4, 500)}, @@ -431,20 +434,21 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="instantFactory") + @ParameterizedTest + @MethodSource("data_instantFactory") public void factory_ofInstant(Instant instant, ZoneId zone, LocalTime expected) { LocalTime test = LocalTime.ofInstant(instant, zone); - assertEquals(test, expected); + assertEquals(expected, test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_nullInstant() { - LocalTime.ofInstant((Instant) null, ZONE_PARIS); + Assertions.assertThrows(NullPointerException.class, () -> LocalTime.ofInstant((Instant) null, ZONE_PARIS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_nullZone() { - LocalTime.ofInstant(Instant.EPOCH, (ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalTime.ofInstant(Instant.EPOCH, (ZoneId) null)); } //----------------------------------------------------------------------- @@ -456,14 +460,14 @@ public class TCKLocalTime extends AbstractDateTimeTest { check(localTime, 2, 17, 23, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofSecondOfDay_tooLow() { - LocalTime.ofSecondOfDay(-1); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.ofSecondOfDay(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofSecondOfDay_tooHigh() { - LocalTime.ofSecondOfDay(24 * 60 * 60); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.ofSecondOfDay(24 * 60 * 60)); } //----------------------------------------------------------------------- @@ -475,14 +479,14 @@ public class TCKLocalTime extends AbstractDateTimeTest { check(localTime, 1, 0, 0, 17); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofNanoOfDay_tooLow() { - LocalTime.ofNanoOfDay(-1); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.ofNanoOfDay(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofNanoOfDay_tooHigh() { - LocalTime.ofNanoOfDay(24 * 60 * 60 * 1000000000L); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.ofNanoOfDay(24 * 60 * 60 * 1000000000L)); } //----------------------------------------------------------------------- @@ -490,34 +494,34 @@ public class TCKLocalTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void factory_from_TemporalAccessor() { - assertEquals(LocalTime.from(LocalTime.of(17, 30)), LocalTime.of(17, 30)); - assertEquals(LocalTime.from(LocalDateTime.of(2012, 5, 1, 17, 30)), LocalTime.of(17, 30)); + assertEquals(LocalTime.of(17, 30), LocalTime.from(LocalTime.of(17, 30))); + assertEquals(LocalTime.of(17, 30), LocalTime.from(LocalDateTime.of(2012, 5, 1, 17, 30))); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_from_TemporalAccessor_invalid_noDerive() { - LocalTime.from(LocalDate.of(2007, 7, 15)); + Assertions.assertThrows(DateTimeException.class, () -> LocalTime.from(LocalDate.of(2007, 7, 15))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_from_TemporalAccessor_null() { - LocalTime.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalTime.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- // parse() //----------------------------------------------------------------------- - @Test(dataProvider = "sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void factory_parse_validText(int h, int m, int s, int n, String parsable) { LocalTime t = LocalTime.parse(parsable); assertNotNull(t, parsable); - assertEquals(t.getHour(), h); - assertEquals(t.getMinute(), m); - assertEquals(t.getSecond(), s); - assertEquals(t.getNano(), n); + assertEquals(h, t.getHour()); + assertEquals(m, t.getMinute()); + assertEquals(s, t.getSecond()); + assertEquals(n, t.getNano()); } - @DataProvider(name="sampleBadParse") Object[][] provider_sampleBadParse() { return new Object[][]{ {"00;00"}, @@ -532,31 +536,32 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider = "sampleBadParse", expectedExceptions={DateTimeParseException.class}) + @ParameterizedTest + @MethodSource("provider_sampleBadParse") public void factory_parse_invalidText(String unparsable) { - LocalTime.parse(unparsable); + Assertions.assertThrows(DateTimeParseException.class, () -> LocalTime.parse(unparsable)); } //-----------------------------------------------------------------------s - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_illegalHour() { - LocalTime.parse("25:00"); + Assertions.assertThrows(DateTimeParseException.class, () -> LocalTime.parse("25:00")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_illegalMinute() { - LocalTime.parse("12:60"); + Assertions.assertThrows(DateTimeParseException.class, () -> LocalTime.parse("12:60")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_illegalSecond() { - LocalTime.parse("12:12:60"); + Assertions.assertThrows(DateTimeParseException.class, () -> LocalTime.parse("12:12:60")); } //-----------------------------------------------------------------------s - @Test(expectedExceptions = {NullPointerException.class}) + @Test public void factory_parse_nullTest() { - LocalTime.parse((String) null); + Assertions.assertThrows(NullPointerException.class, () -> LocalTime.parse((String) null)); } //----------------------------------------------------------------------- @@ -566,18 +571,20 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void factory_parse_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("H m s"); LocalTime test = LocalTime.parse("14 30 40", f); - assertEquals(test, LocalTime.of(14, 30, 40)); + assertEquals(LocalTime.of(14, 30, 40), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullText() { - DateTimeFormatter f = DateTimeFormatter.ofPattern("H m s"); - LocalTime.parse((String) null, f); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter f = DateTimeFormatter.ofPattern("H m s"); + LocalTime.parse((String) null, f); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullFormatter() { - LocalTime.parse("ANY", null); + Assertions.assertThrows(NullPointerException.class, () -> LocalTime.parse("ANY", null)); } //----------------------------------------------------------------------- @@ -585,37 +592,37 @@ public class TCKLocalTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(TEST_12_30_40_987654321.isSupported((TemporalField) null), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.NANO_OF_SECOND), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.NANO_OF_DAY), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.MICRO_OF_SECOND), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.MICRO_OF_DAY), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.MILLI_OF_SECOND), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.MILLI_OF_DAY), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.SECOND_OF_MINUTE), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.SECOND_OF_DAY), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.MINUTE_OF_HOUR), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.MINUTE_OF_DAY), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.HOUR_OF_AMPM), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.HOUR_OF_DAY), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.AMPM_OF_DAY), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.DAY_OF_WEEK), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.DAY_OF_MONTH), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.DAY_OF_YEAR), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.EPOCH_DAY), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.MONTH_OF_YEAR), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.PROLEPTIC_MONTH), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.YEAR), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.YEAR_OF_ERA), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.ERA), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.INSTANT_SECONDS), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoField.OFFSET_SECONDS), false); + assertEquals(false, TEST_12_30_40_987654321.isSupported((TemporalField) null)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.YEAR)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.ERA)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -623,23 +630,23 @@ public class TCKLocalTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalUnit() { - assertEquals(TEST_12_30_40_987654321.isSupported((TemporalUnit) null), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.NANOS), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.MICROS), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.MILLIS), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.SECONDS), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.MINUTES), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.HOURS), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.HALF_DAYS), true); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.DAYS), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.WEEKS), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.MONTHS), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.YEARS), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.DECADES), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.CENTURIES), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.MILLENNIA), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.ERAS), false); - assertEquals(TEST_12_30_40_987654321.isSupported(ChronoUnit.FOREVER), false); + assertEquals(false, TEST_12_30_40_987654321.isSupported((TemporalUnit) null)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoUnit.NANOS)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoUnit.MICROS)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoUnit.MILLIS)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoUnit.SECONDS)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoUnit.MINUTES)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoUnit.HOURS)); + assertEquals(true, TEST_12_30_40_987654321.isSupported(ChronoUnit.HALF_DAYS)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoUnit.DAYS)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoUnit.WEEKS)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoUnit.MONTHS)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoUnit.YEARS)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoUnit.DECADES)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoUnit.CENTURIES)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoUnit.MILLENNIA)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoUnit.ERAS)); + assertEquals(false, TEST_12_30_40_987654321.isSupported(ChronoUnit.FOREVER)); } //----------------------------------------------------------------------- @@ -648,39 +655,38 @@ public class TCKLocalTime extends AbstractDateTimeTest { @Test public void test_get_TemporalField() { LocalTime test = TEST_12_30_40_987654321; - assertEquals(test.get(ChronoField.HOUR_OF_DAY), 12); - assertEquals(test.get(ChronoField.MINUTE_OF_HOUR), 30); - assertEquals(test.get(ChronoField.SECOND_OF_MINUTE), 40); - assertEquals(test.get(ChronoField.NANO_OF_SECOND), 987654321); + assertEquals(12, test.get(ChronoField.HOUR_OF_DAY)); + assertEquals(30, test.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(40, test.get(ChronoField.SECOND_OF_MINUTE)); + assertEquals(987654321, test.get(ChronoField.NANO_OF_SECOND)); - assertEquals(test.get(ChronoField.SECOND_OF_DAY), 12 * 3600 + 30 * 60 + 40); - assertEquals(test.get(ChronoField.MINUTE_OF_DAY), 12 * 60 + 30); - assertEquals(test.get(ChronoField.HOUR_OF_AMPM), 0); - assertEquals(test.get(ChronoField.CLOCK_HOUR_OF_AMPM), 12); - assertEquals(test.get(ChronoField.CLOCK_HOUR_OF_DAY), 12); - assertEquals(test.get(ChronoField.AMPM_OF_DAY), 1); + assertEquals(12 * 3600 + 30 * 60 + 40, test.get(ChronoField.SECOND_OF_DAY)); + assertEquals(12 * 60 + 30, test.get(ChronoField.MINUTE_OF_DAY)); + assertEquals(0, test.get(ChronoField.HOUR_OF_AMPM)); + assertEquals(12, test.get(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(12, test.get(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(1, test.get(ChronoField.AMPM_OF_DAY)); } @Test public void test_getLong_TemporalField() { LocalTime test = TEST_12_30_40_987654321; - assertEquals(test.getLong(ChronoField.HOUR_OF_DAY), 12); - assertEquals(test.getLong(ChronoField.MINUTE_OF_HOUR), 30); - assertEquals(test.getLong(ChronoField.SECOND_OF_MINUTE), 40); - assertEquals(test.getLong(ChronoField.NANO_OF_SECOND), 987654321); + assertEquals(12, test.getLong(ChronoField.HOUR_OF_DAY)); + assertEquals(30, test.getLong(ChronoField.MINUTE_OF_HOUR)); + assertEquals(40, test.getLong(ChronoField.SECOND_OF_MINUTE)); + assertEquals(987654321, test.getLong(ChronoField.NANO_OF_SECOND)); - assertEquals(test.getLong(ChronoField.SECOND_OF_DAY), 12 * 3600 + 30 * 60 + 40); - assertEquals(test.getLong(ChronoField.MINUTE_OF_DAY), 12 * 60 + 30); - assertEquals(test.getLong(ChronoField.HOUR_OF_AMPM), 0); - assertEquals(test.getLong(ChronoField.CLOCK_HOUR_OF_AMPM), 12); - assertEquals(test.getLong(ChronoField.CLOCK_HOUR_OF_DAY), 12); - assertEquals(test.getLong(ChronoField.AMPM_OF_DAY), 1); + assertEquals(12 * 3600 + 30 * 60 + 40, test.getLong(ChronoField.SECOND_OF_DAY)); + assertEquals(12 * 60 + 30, test.getLong(ChronoField.MINUTE_OF_DAY)); + assertEquals(0, test.getLong(ChronoField.HOUR_OF_AMPM)); + assertEquals(12, test.getLong(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(12, test.getLong(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(1, test.getLong(ChronoField.AMPM_OF_DAY)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {TEST_12_30_40_987654321, TemporalQueries.chronology(), null}, @@ -693,25 +699,26 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - TEST_12_30_40_987654321.query(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.query(null)); } //----------------------------------------------------------------------- // get*() //----------------------------------------------------------------------- - @DataProvider(name="sampleTimes") Object[][] provider_sampleTimes() { return new Object[][] { {0, 0, 0, 0}, @@ -734,19 +741,19 @@ public class TCKLocalTime extends AbstractDateTimeTest { } //----------------------------------------------------------------------- - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_get(int h, int m, int s, int ns) { LocalTime a = LocalTime.of(h, m, s, ns); - assertEquals(a.getHour(), h); - assertEquals(a.getMinute(), m); - assertEquals(a.getSecond(), s); - assertEquals(a.getNano(), ns); + assertEquals(h, a.getHour()); + assertEquals(m, a.getMinute()); + assertEquals(s, a.getSecond()); + assertEquals(ns, a.getNano()); } //----------------------------------------------------------------------- // adjustInto(Temporal) //----------------------------------------------------------------------- - @DataProvider(name="adjustInto") Object[][] data_adjustInto() { return new Object[][]{ {LocalTime.of(23, 5), LocalTime.of(4, 1, 1, 100), LocalTime.of(23, 5, 0, 0), null}, @@ -772,11 +779,12 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="adjustInto") + @ParameterizedTest + @MethodSource("data_adjustInto") public void test_adjustInto(LocalTime test, Temporal temporal, Temporal expected, Class expectedEx) { if (expectedEx == null) { Temporal result = test.adjustInto(temporal); - assertEquals(result, expected); + assertEquals(expected, result); } else { try { Temporal result = test.adjustInto(temporal); @@ -799,12 +807,12 @@ public class TCKLocalTime extends AbstractDateTimeTest { return sample; } }; - assertEquals(TEST_12_30_40_987654321.with(adjuster), sample); + assertEquals(sample, TEST_12_30_40_987654321.with(adjuster)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_with_adjustment_null() { - TEST_12_30_40_987654321.with((TemporalAdjuster) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.with((TemporalAdjuster) null)); } //----------------------------------------------------------------------- @@ -830,10 +838,10 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_nanoOfSecond() { for (long i : testPoints(1_000_000_000L)) { LocalTime test = TEST_12_30_40_987654321.with(NANO_OF_SECOND, i); - assertEquals(test.get(NANO_OF_SECOND), i); - assertEquals(test.get(HOUR_OF_DAY), TEST_12_30_40_987654321.get(HOUR_OF_DAY)); - assertEquals(test.get(MINUTE_OF_HOUR), TEST_12_30_40_987654321.get(MINUTE_OF_HOUR)); - assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE)); + assertEquals(i, test.get(NANO_OF_SECOND)); + assertEquals(TEST_12_30_40_987654321.get(HOUR_OF_DAY), test.get(HOUR_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(MINUTE_OF_HOUR), test.get(MINUTE_OF_HOUR)); + assertEquals(TEST_12_30_40_987654321.get(SECOND_OF_MINUTE), test.get(SECOND_OF_MINUTE)); } } @@ -843,7 +851,7 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_nanoOfDay() { for (long i : testPoints(86_400_000_000_000L)) { LocalTime test = TEST_12_30_40_987654321.with(NANO_OF_DAY, i); - assertEquals(test, LocalTime.ofNanoOfDay(i)); + assertEquals(LocalTime.ofNanoOfDay(i), test); } } @@ -854,10 +862,10 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_microOfSecond() { for (long i : testPoints(1_000_000L)) { LocalTime test = TEST_12_30_40_987654321.with(MICRO_OF_SECOND, i); - assertEquals(test.get(NANO_OF_SECOND), i * 1_000); - assertEquals(test.get(HOUR_OF_DAY), TEST_12_30_40_987654321.get(HOUR_OF_DAY)); - assertEquals(test.get(MINUTE_OF_HOUR), TEST_12_30_40_987654321.get(MINUTE_OF_HOUR)); - assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE)); + assertEquals(i * 1_000, test.get(NANO_OF_SECOND)); + assertEquals(TEST_12_30_40_987654321.get(HOUR_OF_DAY), test.get(HOUR_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(MINUTE_OF_HOUR), test.get(MINUTE_OF_HOUR)); + assertEquals(TEST_12_30_40_987654321.get(SECOND_OF_MINUTE), test.get(SECOND_OF_MINUTE)); } } @@ -868,7 +876,7 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_microOfDay() { for (long i : testPoints(86_400_000_000L)) { LocalTime test = TEST_12_30_40_987654321.with(MICRO_OF_DAY, i); - assertEquals(test, LocalTime.ofNanoOfDay(i * 1000)); + assertEquals(LocalTime.ofNanoOfDay(i * 1000), test); } } @@ -879,10 +887,10 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_milliOfSecond() { for (long i : testPoints(1_000L)) { LocalTime test = TEST_12_30_40_987654321.with(MILLI_OF_SECOND, i); - assertEquals(test.get(NANO_OF_SECOND), i * 1_000_000); - assertEquals(test.get(HOUR_OF_DAY), TEST_12_30_40_987654321.get(HOUR_OF_DAY)); - assertEquals(test.get(MINUTE_OF_HOUR), TEST_12_30_40_987654321.get(MINUTE_OF_HOUR)); - assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE)); + assertEquals(i * 1_000_000, test.get(NANO_OF_SECOND)); + assertEquals(TEST_12_30_40_987654321.get(HOUR_OF_DAY), test.get(HOUR_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(MINUTE_OF_HOUR), test.get(MINUTE_OF_HOUR)); + assertEquals(TEST_12_30_40_987654321.get(SECOND_OF_MINUTE), test.get(SECOND_OF_MINUTE)); } } @@ -893,7 +901,7 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_milliOfDay() { for (long i : testPoints(86_400_000L)) { LocalTime test = TEST_12_30_40_987654321.with(MILLI_OF_DAY, i); - assertEquals(test, LocalTime.ofNanoOfDay(i * 1_000_000)); + assertEquals(LocalTime.ofNanoOfDay(i * 1_000_000), test); } } @@ -903,10 +911,10 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_secondOfMinute() { for (long i : testPoints(60L)) { LocalTime test = TEST_12_30_40_987654321.with(SECOND_OF_MINUTE, i); - assertEquals(test.get(SECOND_OF_MINUTE), i); - assertEquals(test.get(HOUR_OF_DAY), TEST_12_30_40_987654321.get(HOUR_OF_DAY)); - assertEquals(test.get(MINUTE_OF_HOUR), TEST_12_30_40_987654321.get(MINUTE_OF_HOUR)); - assertEquals(test.get(NANO_OF_SECOND), TEST_12_30_40_987654321.get(NANO_OF_SECOND)); + assertEquals(i, test.get(SECOND_OF_MINUTE)); + assertEquals(TEST_12_30_40_987654321.get(HOUR_OF_DAY), test.get(HOUR_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(MINUTE_OF_HOUR), test.get(MINUTE_OF_HOUR)); + assertEquals(TEST_12_30_40_987654321.get(NANO_OF_SECOND), test.get(NANO_OF_SECOND)); } } @@ -916,8 +924,8 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_secondOfDay() { for (long i : testPoints(24 * 60 * 60)) { LocalTime test = TEST_12_30_40_987654321.with(SECOND_OF_DAY, i); - assertEquals(test.get(SECOND_OF_DAY), i); - assertEquals(test.get(NANO_OF_SECOND), TEST_12_30_40_987654321.get(NANO_OF_SECOND)); + assertEquals(i, test.get(SECOND_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(NANO_OF_SECOND), test.get(NANO_OF_SECOND)); } } @@ -927,10 +935,10 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_minuteOfHour() { for (long i : testPoints(60)) { LocalTime test = TEST_12_30_40_987654321.with(MINUTE_OF_HOUR, i); - assertEquals(test.get(MINUTE_OF_HOUR), i); - assertEquals(test.get(HOUR_OF_DAY), TEST_12_30_40_987654321.get(HOUR_OF_DAY)); - assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE)); - assertEquals(test.get(NANO_OF_SECOND), TEST_12_30_40_987654321.get(NANO_OF_SECOND)); + assertEquals(i, test.get(MINUTE_OF_HOUR)); + assertEquals(TEST_12_30_40_987654321.get(HOUR_OF_DAY), test.get(HOUR_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(SECOND_OF_MINUTE), test.get(SECOND_OF_MINUTE)); + assertEquals(TEST_12_30_40_987654321.get(NANO_OF_SECOND), test.get(NANO_OF_SECOND)); } } @@ -940,9 +948,9 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_minuteOfDay() { for (long i : testPoints(24 * 60)) { LocalTime test = TEST_12_30_40_987654321.with(MINUTE_OF_DAY, i); - assertEquals(test.get(MINUTE_OF_DAY), i); - assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE)); - assertEquals(test.get(NANO_OF_SECOND), TEST_12_30_40_987654321.get(NANO_OF_SECOND)); + assertEquals(i, test.get(MINUTE_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(SECOND_OF_MINUTE), test.get(SECOND_OF_MINUTE)); + assertEquals(TEST_12_30_40_987654321.get(NANO_OF_SECOND), test.get(NANO_OF_SECOND)); } } @@ -952,11 +960,11 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_hourOfAmPm() { for (int i = 0; i < 12; i++) { LocalTime test = TEST_12_30_40_987654321.with(HOUR_OF_AMPM, i); - assertEquals(test.get(HOUR_OF_AMPM), i); - assertEquals(test.get(AMPM_OF_DAY), TEST_12_30_40_987654321.get(AMPM_OF_DAY)); - assertEquals(test.get(MINUTE_OF_HOUR), TEST_12_30_40_987654321.get(MINUTE_OF_HOUR)); - assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE)); - assertEquals(test.get(NANO_OF_SECOND), TEST_12_30_40_987654321.get(NANO_OF_SECOND)); + assertEquals(i, test.get(HOUR_OF_AMPM)); + assertEquals(TEST_12_30_40_987654321.get(AMPM_OF_DAY), test.get(AMPM_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(MINUTE_OF_HOUR), test.get(MINUTE_OF_HOUR)); + assertEquals(TEST_12_30_40_987654321.get(SECOND_OF_MINUTE), test.get(SECOND_OF_MINUTE)); + assertEquals(TEST_12_30_40_987654321.get(NANO_OF_SECOND), test.get(NANO_OF_SECOND)); } } @@ -966,11 +974,11 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_clockHourOfAmPm() { for (int i = 1; i <= 12; i++) { LocalTime test = TEST_12_30_40_987654321.with(CLOCK_HOUR_OF_AMPM, i); - assertEquals(test.get(CLOCK_HOUR_OF_AMPM), i); - assertEquals(test.get(AMPM_OF_DAY), TEST_12_30_40_987654321.get(AMPM_OF_DAY)); - assertEquals(test.get(MINUTE_OF_HOUR), TEST_12_30_40_987654321.get(MINUTE_OF_HOUR)); - assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE)); - assertEquals(test.get(NANO_OF_SECOND), TEST_12_30_40_987654321.get(NANO_OF_SECOND)); + assertEquals(i, test.get(CLOCK_HOUR_OF_AMPM)); + assertEquals(TEST_12_30_40_987654321.get(AMPM_OF_DAY), test.get(AMPM_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(MINUTE_OF_HOUR), test.get(MINUTE_OF_HOUR)); + assertEquals(TEST_12_30_40_987654321.get(SECOND_OF_MINUTE), test.get(SECOND_OF_MINUTE)); + assertEquals(TEST_12_30_40_987654321.get(NANO_OF_SECOND), test.get(NANO_OF_SECOND)); } } @@ -980,10 +988,10 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_hourOfDay() { for (int i = 0; i < 24; i++) { LocalTime test = TEST_12_30_40_987654321.with(HOUR_OF_DAY, i); - assertEquals(test.get(HOUR_OF_DAY), i); - assertEquals(test.get(MINUTE_OF_HOUR), TEST_12_30_40_987654321.get(MINUTE_OF_HOUR)); - assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE)); - assertEquals(test.get(NANO_OF_SECOND), TEST_12_30_40_987654321.get(NANO_OF_SECOND)); + assertEquals(i, test.get(HOUR_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(MINUTE_OF_HOUR), test.get(MINUTE_OF_HOUR)); + assertEquals(TEST_12_30_40_987654321.get(SECOND_OF_MINUTE), test.get(SECOND_OF_MINUTE)); + assertEquals(TEST_12_30_40_987654321.get(NANO_OF_SECOND), test.get(NANO_OF_SECOND)); } } @@ -993,10 +1001,10 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_clockHourOfDay() { for (int i = 1; i <= 24; i++) { LocalTime test = TEST_12_30_40_987654321.with(CLOCK_HOUR_OF_DAY, i); - assertEquals(test.get(CLOCK_HOUR_OF_DAY), i); - assertEquals(test.get(MINUTE_OF_HOUR), TEST_12_30_40_987654321.get(MINUTE_OF_HOUR)); - assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE)); - assertEquals(test.get(NANO_OF_SECOND), TEST_12_30_40_987654321.get(NANO_OF_SECOND)); + assertEquals(i, test.get(CLOCK_HOUR_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(MINUTE_OF_HOUR), test.get(MINUTE_OF_HOUR)); + assertEquals(TEST_12_30_40_987654321.get(SECOND_OF_MINUTE), test.get(SECOND_OF_MINUTE)); + assertEquals(TEST_12_30_40_987654321.get(NANO_OF_SECOND), test.get(NANO_OF_SECOND)); } } @@ -1006,18 +1014,17 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_with_longTemporalField_amPmOfDay() { for (int i = 0; i <= 1; i++) { LocalTime test = TEST_12_30_40_987654321.with(AMPM_OF_DAY, i); - assertEquals(test.get(AMPM_OF_DAY), i); - assertEquals(test.get(HOUR_OF_AMPM), TEST_12_30_40_987654321.get(HOUR_OF_AMPM)); - assertEquals(test.get(MINUTE_OF_HOUR), TEST_12_30_40_987654321.get(MINUTE_OF_HOUR)); - assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE)); - assertEquals(test.get(NANO_OF_SECOND), TEST_12_30_40_987654321.get(NANO_OF_SECOND)); + assertEquals(i, test.get(AMPM_OF_DAY)); + assertEquals(TEST_12_30_40_987654321.get(HOUR_OF_AMPM), test.get(HOUR_OF_AMPM)); + assertEquals(TEST_12_30_40_987654321.get(MINUTE_OF_HOUR), test.get(MINUTE_OF_HOUR)); + assertEquals(TEST_12_30_40_987654321.get(SECOND_OF_MINUTE), test.get(SECOND_OF_MINUTE)); + assertEquals(TEST_12_30_40_987654321.get(NANO_OF_SECOND), test.get(NANO_OF_SECOND)); } } // The supported fields behave as follows... // In all cases, if the new value is outside the valid range of values for the field // then a {@code DateTimeException} will be thrown. - @DataProvider(name = "withTemporalField_outOfRange") Object[][] data_withTemporalField_outOfRange() { return new Object[][] { {NANO_OF_SECOND, time(0, 0, 0, 0), NANO_OF_SECOND.range().getMinimum() - 1}, @@ -1067,7 +1074,8 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider = "withTemporalField_outOfRange") + @ParameterizedTest + @MethodSource("data_withTemporalField_outOfRange") public void test_with_longTemporalField_invalid(TemporalField field, LocalTime base, long newValue) { try { base.with(field, newValue); @@ -1078,9 +1086,9 @@ public class TCKLocalTime extends AbstractDateTimeTest { } // All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. - @Test(expectedExceptions=UnsupportedTemporalTypeException.class) + @Test public void test_with_longTemporalField_otherChronoField() { - TEST_12_30_40_987654321.with(ChronoField.DAY_OF_MONTH, 1); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> TEST_12_30_40_987654321.with(ChronoField.DAY_OF_MONTH, 1)); } // If the field is not a {@code ChronoField}, then the result of this method @@ -1116,8 +1124,8 @@ public class TCKLocalTime extends AbstractDateTimeTest { throw new UnsupportedOperationException(); } public R adjustInto(R temporal, long newValue) { - assertEquals(temporal, base); - assertEquals(newValue, 12L); + assertEquals(base, temporal); + assertEquals(12L, newValue); @SuppressWarnings("unchecked") R r = (R) result; return r; @@ -1127,9 +1135,9 @@ public class TCKLocalTime extends AbstractDateTimeTest { assertSame(test, result); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_with_longTemporalField_null() { - TEST_12_30_40_987654321.with((TemporalField) null, 1); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.with((TemporalField) null, 1)); } //----------------------------------------------------------------------- @@ -1140,36 +1148,36 @@ public class TCKLocalTime extends AbstractDateTimeTest { LocalTime t = TEST_12_30_40_987654321; for (int i = 0; i < 24; i++) { t = t.withHour(i); - assertEquals(t.getHour(), i); + assertEquals(i, t.getHour()); } } @Test public void test_withHour_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.withHour(12); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_withHour_toMidnight_equal() { LocalTime t = LocalTime.of(1, 0).withHour(0); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_withHour_toMidday_equal() { LocalTime t = LocalTime.of(1, 0).withHour(12); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withHour_hourTooLow() { - TEST_12_30_40_987654321.withHour(-1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_12_30_40_987654321.withHour(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withHour_hourTooHigh() { - TEST_12_30_40_987654321.withHour(24); + Assertions.assertThrows(DateTimeException.class, () -> TEST_12_30_40_987654321.withHour(24)); } //----------------------------------------------------------------------- @@ -1180,36 +1188,36 @@ public class TCKLocalTime extends AbstractDateTimeTest { LocalTime t = TEST_12_30_40_987654321; for (int i = 0; i < 60; i++) { t = t.withMinute(i); - assertEquals(t.getMinute(), i); + assertEquals(i, t.getMinute()); } } @Test public void test_withMinute_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.withMinute(30); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_withMinute_toMidnight_equal() { LocalTime t = LocalTime.of(0, 1).withMinute(0); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_withMinute_toMidday_equals() { LocalTime t = LocalTime.of(12, 1).withMinute(0); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMinute_minuteTooLow() { - TEST_12_30_40_987654321.withMinute(-1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_12_30_40_987654321.withMinute(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMinute_minuteTooHigh() { - TEST_12_30_40_987654321.withMinute(60); + Assertions.assertThrows(DateTimeException.class, () -> TEST_12_30_40_987654321.withMinute(60)); } //----------------------------------------------------------------------- @@ -1220,36 +1228,36 @@ public class TCKLocalTime extends AbstractDateTimeTest { LocalTime t = TEST_12_30_40_987654321; for (int i = 0; i < 60; i++) { t = t.withSecond(i); - assertEquals(t.getSecond(), i); + assertEquals(i, t.getSecond()); } } @Test public void test_withSecond_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.withSecond(40); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_withSecond_toMidnight_equal() { LocalTime t = LocalTime.of(0, 0, 1).withSecond(0); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_withSecond_toMidday_equal() { LocalTime t = LocalTime.of(12, 0, 1).withSecond(0); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withSecond_secondTooLow() { - TEST_12_30_40_987654321.withSecond(-1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_12_30_40_987654321.withSecond(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withSecond_secondTooHigh() { - TEST_12_30_40_987654321.withSecond(60); + Assertions.assertThrows(DateTimeException.class, () -> TEST_12_30_40_987654321.withSecond(60)); } //----------------------------------------------------------------------- @@ -1259,41 +1267,41 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_withNanoOfSecond_normal() { LocalTime t = TEST_12_30_40_987654321; t = t.withNano(1); - assertEquals(t.getNano(), 1); + assertEquals(1, t.getNano()); t = t.withNano(10); - assertEquals(t.getNano(), 10); + assertEquals(10, t.getNano()); t = t.withNano(100); - assertEquals(t.getNano(), 100); + assertEquals(100, t.getNano()); t = t.withNano(999999999); - assertEquals(t.getNano(), 999999999); + assertEquals(999999999, t.getNano()); } @Test public void test_withNanoOfSecond_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.withNano(987654321); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_withNanoOfSecond_toMidnight_equal() { LocalTime t = LocalTime.of(0, 0, 0, 1).withNano(0); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_withNanoOfSecond_toMidday_equal() { LocalTime t = LocalTime.of(12, 0, 0, 1).withNano(0); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withNanoOfSecond_nanoTooLow() { - TEST_12_30_40_987654321.withNano(-1); + Assertions.assertThrows(DateTimeException.class, () -> TEST_12_30_40_987654321.withNano(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withNanoOfSecond_nanoTooHigh() { - TEST_12_30_40_987654321.withNano(1000000000); + Assertions.assertThrows(DateTimeException.class, () -> TEST_12_30_40_987654321.withNano(1000000000)); } //----------------------------------------------------------------------- @@ -1369,7 +1377,6 @@ public class TCKLocalTime extends AbstractDateTimeTest { } }; - @DataProvider(name="truncatedToValid") Object[][] data_truncatedToValid() { return new Object[][] { {LocalTime.of(1, 2, 3, 123_456_789), NANOS, LocalTime.of(1, 2, 3, 123_456_789)}, @@ -1386,12 +1393,12 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="truncatedToValid") + @ParameterizedTest + @MethodSource("data_truncatedToValid") public void test_truncatedTo_valid(LocalTime input, TemporalUnit unit, LocalTime expected) { - assertEquals(input.truncatedTo(unit), expected); + assertEquals(expected, input.truncatedTo(unit)); } - @DataProvider(name="truncatedToInvalid") Object[][] data_truncatedToInvalid() { return new Object[][] { {LocalTime.of(1, 2, 3, 123_456_789), NINETY_FIVE_MINS}, @@ -1401,14 +1408,15 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="truncatedToInvalid", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_truncatedToInvalid") public void test_truncatedTo_invalid(LocalTime input, TemporalUnit unit) { - input.truncatedTo(unit); + Assertions.assertThrows(DateTimeException.class, () -> input.truncatedTo(unit)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_truncatedTo_null() { - TEST_12_30_40_987654321.truncatedTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.truncatedTo(null)); } //----------------------------------------------------------------------- @@ -1418,39 +1426,41 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_plus_TemporalAmount_positiveHours() { TemporalAmount period = MockSimplePeriod.of(7, ChronoUnit.HOURS); LocalTime t = TEST_12_30_40_987654321.plus(period); - assertEquals(t, LocalTime.of(19, 30, 40, 987654321)); + assertEquals(LocalTime.of(19, 30, 40, 987654321), t); } @Test public void test_plus_TemporalAmount_negativeMinutes() { TemporalAmount period = MockSimplePeriod.of(-25, ChronoUnit.MINUTES); LocalTime t = TEST_12_30_40_987654321.plus(period); - assertEquals(t, LocalTime.of(12, 5, 40, 987654321)); + assertEquals(LocalTime.of(12, 5, 40, 987654321), t); } @Test public void test_plus_TemporalAmount_zero() { TemporalAmount period = Period.ZERO; LocalTime t = TEST_12_30_40_987654321.plus(period); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_plus_TemporalAmount_wrap() { TemporalAmount p = MockSimplePeriod.of(1, HOURS); LocalTime t = LocalTime.of(23, 30).plus(p); - assertEquals(t, LocalTime.of(0, 30)); + assertEquals(LocalTime.of(0, 30), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plus_TemporalAmount_dateNotAllowed() { - TemporalAmount period = MockSimplePeriod.of(7, ChronoUnit.MONTHS); - TEST_12_30_40_987654321.plus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAmount period = MockSimplePeriod.of(7, ChronoUnit.MONTHS); + TEST_12_30_40_987654321.plus(period); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_TemporalAmount_null() { - TEST_12_30_40_987654321.plus((TemporalAmount) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.plus((TemporalAmount) null)); } //----------------------------------------------------------------------- @@ -1459,19 +1469,19 @@ public class TCKLocalTime extends AbstractDateTimeTest { @Test public void test_plus_longTemporalUnit_positiveHours() { LocalTime t = TEST_12_30_40_987654321.plus(7, ChronoUnit.HOURS); - assertEquals(t, LocalTime.of(19, 30, 40, 987654321)); + assertEquals(LocalTime.of(19, 30, 40, 987654321), t); } @Test public void test_plus_longTemporalUnit_negativeMinutes() { LocalTime t = TEST_12_30_40_987654321.plus(-25, ChronoUnit.MINUTES); - assertEquals(t, LocalTime.of(12, 5, 40, 987654321)); + assertEquals(LocalTime.of(12, 5, 40, 987654321), t); } @Test public void test_plus_longTemporalUnit_zero() { LocalTime t = TEST_12_30_40_987654321.plus(0, ChronoUnit.MINUTES); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test @@ -1486,9 +1496,9 @@ public class TCKLocalTime extends AbstractDateTimeTest { } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_longTemporalUnit_null() { - TEST_12_30_40_987654321.plus(1, (TemporalUnit) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.plus(1, (TemporalUnit) null)); } //----------------------------------------------------------------------- @@ -1499,7 +1509,7 @@ public class TCKLocalTime extends AbstractDateTimeTest { LocalTime t = LocalTime.MIDNIGHT; for (int i = 0; i < 50; i++) { t = t.plusHours(1); - assertEquals(t.getHour(), (i + 1) % 24); + assertEquals((i + 1) % 24, t.getHour()); } } @@ -1508,7 +1518,7 @@ public class TCKLocalTime extends AbstractDateTimeTest { LocalTime base = LocalTime.MIDNIGHT; for (int i = -50; i < 50; i++) { LocalTime t = base.plusHours(i); - assertEquals(t.getHour(), (i + 72) % 24); + assertEquals((i + 72) % 24, t.getHour()); } } @@ -1517,33 +1527,33 @@ public class TCKLocalTime extends AbstractDateTimeTest { LocalTime base = LocalTime.of(1, 0); for (int i = -50; i < 50; i++) { LocalTime t = base.plusHours(i); - assertEquals(t.getHour(), (1 + i + 72) % 24); + assertEquals((1 + i + 72) % 24, t.getHour()); } } @Test public void test_plusHours_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.plusHours(0); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_plusHours_toMidnight_equal() { LocalTime t = LocalTime.of(23, 0).plusHours(1); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_plusHours_toMidday_equal() { LocalTime t = LocalTime.of(11, 0).plusHours(1); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } @Test public void test_plusHours_big() { LocalTime t = LocalTime.of(2, 30).plusHours(Long.MAX_VALUE); int hours = (int) (Long.MAX_VALUE % 24L); - assertEquals(t, LocalTime.of(2, 30).plusHours(hours)); + assertEquals(LocalTime.of(2, 30).plusHours(hours), t); } //----------------------------------------------------------------------- @@ -1561,8 +1571,8 @@ public class TCKLocalTime extends AbstractDateTimeTest { hour++; min = 0; } - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); } } @@ -1586,40 +1596,40 @@ public class TCKLocalTime extends AbstractDateTimeTest { hour = 0; min = i; } - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); } } @Test public void test_plusMinutes_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.plusMinutes(0); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_plusMinutes_noChange_oneDay_equal() { LocalTime t = TEST_12_30_40_987654321.plusMinutes(24 * 60); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_plusMinutes_toMidnight_equal() { LocalTime t = LocalTime.of(23, 59).plusMinutes(1); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_plusMinutes_toMidday_equal() { LocalTime t = LocalTime.of(11, 59).plusMinutes(1); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } @Test public void test_plusMinutes_big() { LocalTime t = LocalTime.of(2, 30).plusMinutes(Long.MAX_VALUE); int mins = (int) (Long.MAX_VALUE % (24L * 60L)); - assertEquals(t, LocalTime.of(2, 30).plusMinutes(mins)); + assertEquals(LocalTime.of(2, 30).plusMinutes(mins), t); } //----------------------------------------------------------------------- @@ -1642,13 +1652,12 @@ public class TCKLocalTime extends AbstractDateTimeTest { hour++; min = 0; } - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); - assertEquals(t.getSecond(), sec); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); + assertEquals(sec, t.getSecond()); } } - @DataProvider(name="plusSeconds_fromZero") Iterator plusSeconds_fromZero() { return new Iterator() { int delta = 30; @@ -1689,38 +1698,39 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="plusSeconds_fromZero") + @ParameterizedTest + @MethodSource("plusSeconds_fromZero") public void test_plusSeconds_fromZero(int seconds, int hour, int min, int sec) { LocalTime base = LocalTime.MIDNIGHT; LocalTime t = base.plusSeconds(seconds); - assertEquals(hour, t.getHour()); - assertEquals(min, t.getMinute()); - assertEquals(sec, t.getSecond()); + assertEquals(t.getHour(), hour); + assertEquals(t.getMinute(), min); + assertEquals(t.getSecond(), sec); } @Test public void test_plusSeconds_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.plusSeconds(0); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_plusSeconds_noChange_oneDay_equal() { LocalTime t = TEST_12_30_40_987654321.plusSeconds(24 * 60 * 60); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_plusSeconds_toMidnight_equal() { LocalTime t = LocalTime.of(23, 59, 59).plusSeconds(1); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_plusSeconds_toMidday_equal() { LocalTime t = LocalTime.of(11, 59, 59).plusSeconds(1); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } //----------------------------------------------------------------------- @@ -1748,14 +1758,13 @@ public class TCKLocalTime extends AbstractDateTimeTest { hour++; min = 0; } - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); - assertEquals(t.getSecond(), sec); - assertEquals(t.getNano(), nanos); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); + assertEquals(sec, t.getSecond()); + assertEquals(nanos, t.getNano()); } } - @DataProvider(name="plusNanos_fromZero") Iterator plusNanos_fromZero() { return new Iterator() { long delta = 7500000000L; @@ -1802,39 +1811,40 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="plusNanos_fromZero") + @ParameterizedTest + @MethodSource("plusNanos_fromZero") public void test_plusNanos_fromZero(long nanoseconds, int hour, int min, int sec, int nanos) { LocalTime base = LocalTime.MIDNIGHT; LocalTime t = base.plusNanos(nanoseconds); - assertEquals(hour, t.getHour()); - assertEquals(min, t.getMinute()); - assertEquals(sec, t.getSecond()); - assertEquals(nanos, t.getNano()); + assertEquals(t.getHour(), hour); + assertEquals(t.getMinute(), min); + assertEquals(t.getSecond(), sec); + assertEquals(t.getNano(), nanos); } @Test public void test_plusNanos_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.plusNanos(0); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_plusNanos_noChange_oneDay_equal() { LocalTime t = TEST_12_30_40_987654321.plusNanos(24 * 60 * 60 * 1000000000L); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_plusNanos_toMidnight_equal() { LocalTime t = LocalTime.of(23, 59, 59, 999999999).plusNanos(1); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_plusNanos_toMidday_equal() { LocalTime t = LocalTime.of(11, 59, 59, 999999999).plusNanos(1); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } //----------------------------------------------------------------------- @@ -1844,39 +1854,41 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_minus_TemporalAmount_positiveHours() { TemporalAmount period = MockSimplePeriod.of(7, ChronoUnit.HOURS); LocalTime t = TEST_12_30_40_987654321.minus(period); - assertEquals(t, LocalTime.of(5, 30, 40, 987654321)); + assertEquals(LocalTime.of(5, 30, 40, 987654321), t); } @Test public void test_minus_TemporalAmount_negativeMinutes() { TemporalAmount period = MockSimplePeriod.of(-25, ChronoUnit.MINUTES); LocalTime t = TEST_12_30_40_987654321.minus(period); - assertEquals(t, LocalTime.of(12, 55, 40, 987654321)); + assertEquals(LocalTime.of(12, 55, 40, 987654321), t); } @Test public void test_minus_TemporalAmount_zero() { TemporalAmount period = Period.ZERO; LocalTime t = TEST_12_30_40_987654321.minus(period); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_minus_TemporalAmount_wrap() { TemporalAmount p = MockSimplePeriod.of(1, HOURS); LocalTime t = LocalTime.of(0, 30).minus(p); - assertEquals(t, LocalTime.of(23, 30)); + assertEquals(LocalTime.of(23, 30), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minus_TemporalAmount_dateNotAllowed() { - TemporalAmount period = MockSimplePeriod.of(7, ChronoUnit.MONTHS); - TEST_12_30_40_987654321.minus(period); + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAmount period = MockSimplePeriod.of(7, ChronoUnit.MONTHS); + TEST_12_30_40_987654321.minus(period); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_minus_TemporalAmount_null() { - TEST_12_30_40_987654321.minus((TemporalAmount) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.minus((TemporalAmount) null)); } //----------------------------------------------------------------------- @@ -1885,19 +1897,19 @@ public class TCKLocalTime extends AbstractDateTimeTest { @Test public void test_minus_longTemporalUnit_positiveHours() { LocalTime t = TEST_12_30_40_987654321.minus(7, ChronoUnit.HOURS); - assertEquals(t, LocalTime.of(5, 30, 40, 987654321)); + assertEquals(LocalTime.of(5, 30, 40, 987654321), t); } @Test public void test_minus_longTemporalUnit_negativeMinutes() { LocalTime t = TEST_12_30_40_987654321.minus(-25, ChronoUnit.MINUTES); - assertEquals(t, LocalTime.of(12, 55, 40, 987654321)); + assertEquals(LocalTime.of(12, 55, 40, 987654321), t); } @Test public void test_minus_longTemporalUnit_zero() { LocalTime t = TEST_12_30_40_987654321.minus(0, ChronoUnit.MINUTES); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test @@ -1912,9 +1924,9 @@ public class TCKLocalTime extends AbstractDateTimeTest { } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_minus_longTemporalUnit_null() { - TEST_12_30_40_987654321.minus(1, (TemporalUnit) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.minus(1, (TemporalUnit) null)); } //----------------------------------------------------------------------- @@ -1925,7 +1937,7 @@ public class TCKLocalTime extends AbstractDateTimeTest { LocalTime t = LocalTime.MIDNIGHT; for (int i = 0; i < 50; i++) { t = t.minusHours(1); - assertEquals(t.getHour(), (((-i + 23) % 24) + 24) % 24, String.valueOf(i)); + assertEquals((((-i + 23) % 24) + 24) % 24, t.getHour(), String.valueOf(i)); } } @@ -1934,7 +1946,7 @@ public class TCKLocalTime extends AbstractDateTimeTest { LocalTime base = LocalTime.MIDNIGHT; for (int i = -50; i < 50; i++) { LocalTime t = base.minusHours(i); - assertEquals(t.getHour(), ((-i % 24) + 24) % 24); + assertEquals(((-i % 24) + 24) % 24, t.getHour()); } } @@ -1943,33 +1955,33 @@ public class TCKLocalTime extends AbstractDateTimeTest { LocalTime base = LocalTime.of(1, 0); for (int i = -50; i < 50; i++) { LocalTime t = base.minusHours(i); - assertEquals(t.getHour(), (1 + (-i % 24) + 24) % 24); + assertEquals((1 + (-i % 24) + 24) % 24, t.getHour()); } } @Test public void test_minusHours_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.minusHours(0); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_minusHours_toMidnight_equal() { LocalTime t = LocalTime.of(1, 0).minusHours(1); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_minusHours_toMidday_equal() { LocalTime t = LocalTime.of(13, 0).minusHours(1); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } @Test public void test_minusHours_big() { LocalTime t = LocalTime.of(2, 30).minusHours(Long.MAX_VALUE); int hours = (int) (Long.MAX_VALUE % 24L); - assertEquals(t, LocalTime.of(2, 30).minusHours(hours)); + assertEquals(LocalTime.of(2, 30).minusHours(hours), t); } //----------------------------------------------------------------------- @@ -1991,8 +2003,8 @@ public class TCKLocalTime extends AbstractDateTimeTest { hour = 23; } } - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); } } @@ -2014,40 +2026,40 @@ public class TCKLocalTime extends AbstractDateTimeTest { } } - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); } } @Test public void test_minusMinutes_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.minusMinutes(0); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_minusMinutes_noChange_oneDay_equal() { LocalTime t = TEST_12_30_40_987654321.minusMinutes(24 * 60); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_minusMinutes_toMidnight_equal() { LocalTime t = LocalTime.of(0, 1).minusMinutes(1); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_minusMinutes_toMidday_equals() { LocalTime t = LocalTime.of(12, 1).minusMinutes(1); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } @Test public void test_minusMinutes_big() { LocalTime t = LocalTime.of(2, 30).minusMinutes(Long.MAX_VALUE); int mins = (int) (Long.MAX_VALUE % (24L * 60L)); - assertEquals(t, LocalTime.of(2, 30).minusMinutes(mins)); + assertEquals(LocalTime.of(2, 30).minusMinutes(mins), t); } //----------------------------------------------------------------------- @@ -2075,13 +2087,12 @@ public class TCKLocalTime extends AbstractDateTimeTest { } } } - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); - assertEquals(t.getSecond(), sec); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); + assertEquals(sec, t.getSecond()); } } - @DataProvider(name="minusSeconds_fromZero") Iterator minusSeconds_fromZero() { return new Iterator() { int delta = 30; @@ -2122,45 +2133,46 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="minusSeconds_fromZero") + @ParameterizedTest + @MethodSource("minusSeconds_fromZero") public void test_minusSeconds_fromZero(int seconds, int hour, int min, int sec) { LocalTime base = LocalTime.MIDNIGHT; LocalTime t = base.minusSeconds(seconds); - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); - assertEquals(t.getSecond(), sec); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); + assertEquals(sec, t.getSecond()); } @Test public void test_minusSeconds_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.minusSeconds(0); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_minusSeconds_noChange_oneDay_equal() { LocalTime t = TEST_12_30_40_987654321.minusSeconds(24 * 60 * 60); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_minusSeconds_toMidnight_equal() { LocalTime t = LocalTime.of(0, 0, 1).minusSeconds(1); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_minusSeconds_toMidday_equal() { LocalTime t = LocalTime.of(12, 0, 1).minusSeconds(1); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } @Test public void test_minusSeconds_big() { LocalTime t = LocalTime.of(2, 30).minusSeconds(Long.MAX_VALUE); int secs = (int) (Long.MAX_VALUE % (24L * 60L * 60L)); - assertEquals(t, LocalTime.of(2, 30).minusSeconds(secs)); + assertEquals(LocalTime.of(2, 30).minusSeconds(secs), t); } //----------------------------------------------------------------------- @@ -2196,14 +2208,13 @@ public class TCKLocalTime extends AbstractDateTimeTest { } } - assertEquals(t.getHour(), hour); - assertEquals(t.getMinute(), min); - assertEquals(t.getSecond(), sec); - assertEquals(t.getNano(), nanos); + assertEquals(hour, t.getHour()); + assertEquals(min, t.getMinute()); + assertEquals(sec, t.getSecond()); + assertEquals(nanos, t.getNano()); } } - @DataProvider(name="minusNanos_fromZero") Iterator minusNanos_fromZero() { return new Iterator() { long delta = 7500000000L; @@ -2250,45 +2261,45 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="minusNanos_fromZero") + @ParameterizedTest + @MethodSource("minusNanos_fromZero") public void test_minusNanos_fromZero(long nanoseconds, int hour, int min, int sec, int nanos) { LocalTime base = LocalTime.MIDNIGHT; LocalTime t = base.minusNanos(nanoseconds); - assertEquals(hour, t.getHour()); - assertEquals(min, t.getMinute()); - assertEquals(sec, t.getSecond()); - assertEquals(nanos, t.getNano()); + assertEquals(t.getHour(), hour); + assertEquals(t.getMinute(), min); + assertEquals(t.getSecond(), sec); + assertEquals(t.getNano(), nanos); } @Test public void test_minusNanos_noChange_equal() { LocalTime t = TEST_12_30_40_987654321.minusNanos(0); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_minusNanos_noChange_oneDay_equal() { LocalTime t = TEST_12_30_40_987654321.minusNanos(24 * 60 * 60 * 1000000000L); - assertEquals(t, TEST_12_30_40_987654321); + assertEquals(TEST_12_30_40_987654321, t); } @Test public void test_minusNanos_toMidnight_equal() { LocalTime t = LocalTime.of(0, 0, 0, 1).minusNanos(1); - assertEquals(t, LocalTime.MIDNIGHT); + assertEquals(LocalTime.MIDNIGHT, t); } @Test public void test_minusNanos_toMidday_equal() { LocalTime t = LocalTime.of(12, 0, 0, 1).minusNanos(1); - assertEquals(t, LocalTime.NOON); + assertEquals(LocalTime.NOON, t); } //----------------------------------------------------------------------- // until(Temporal, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="periodUntilUnit") Object[][] data_periodUntilUnit() { return new Object[][] { {time(0, 0, 0, 0), time(0, 0, 0, 0), NANOS, 0}, @@ -2324,50 +2335,55 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit(LocalTime time1, LocalTime time2, TemporalUnit unit, long expected) { long amount = time1.until(time2, unit); - assertEquals(amount, expected); + assertEquals(expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_negated(LocalTime time1, LocalTime time2, TemporalUnit unit, long expected) { long amount = time2.until(time1, unit); - assertEquals(amount, -expected); + assertEquals(-expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_between(LocalTime time1, LocalTime time2, TemporalUnit unit, long expected) { long amount = unit.between(time1, time2); - assertEquals(amount, expected); + assertEquals(expected, amount); } @Test public void test_until_convertedType() { LocalTime start = LocalTime.of(11, 30); LocalDateTime end = start.plusSeconds(2).atDate(LocalDate.of(2010, 6, 30)); - assertEquals(start.until(end, SECONDS), 2); + assertEquals(2, start.until(end, SECONDS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_invalidType() { - LocalTime start = LocalTime.of(11, 30); - start.until(LocalDate.of(2010, 6, 30), SECONDS); + Assertions.assertThrows(DateTimeException.class, () -> { + LocalTime start = LocalTime.of(11, 30); + start.until(LocalDate.of(2010, 6, 30), SECONDS); + }); } - @Test(expectedExceptions = UnsupportedTemporalTypeException.class) + @Test public void test_until_TemporalUnit_unsupportedUnit() { - TEST_12_30_40_987654321.until(TEST_12_30_40_987654321, DAYS); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> TEST_12_30_40_987654321.until(TEST_12_30_40_987654321, DAYS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullEnd() { - TEST_12_30_40_987654321.until(null, HOURS); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.until(null, HOURS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullUnit() { - TEST_12_30_40_987654321.until(TEST_12_30_40_987654321, null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.until(TEST_12_30_40_987654321, null)); } //----------------------------------------------------------------------- @@ -2377,12 +2393,12 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_format_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("H m s"); String t = LocalTime.of(11, 30, 45).format(f); - assertEquals(t, "11 30 45"); + assertEquals("11 30 45", t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_format_formatter_null() { - LocalTime.of(11, 30, 45).format(null); + Assertions.assertThrows(NullPointerException.class, () -> LocalTime.of(11, 30, 45).format(null)); } //----------------------------------------------------------------------- @@ -2391,12 +2407,12 @@ public class TCKLocalTime extends AbstractDateTimeTest { @Test public void test_atDate() { LocalTime t = LocalTime.of(11, 30); - assertEquals(t.atDate(LocalDate.of(2012, 6, 30)), LocalDateTime.of(2012, 6, 30, 11, 30)); + assertEquals(LocalDateTime.of(2012, 6, 30, 11, 30), t.atDate(LocalDate.of(2012, 6, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atDate_nullDate() { - TEST_12_30_40_987654321.atDate((LocalDate) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.atDate((LocalDate) null)); } //----------------------------------------------------------------------- @@ -2405,13 +2421,15 @@ public class TCKLocalTime extends AbstractDateTimeTest { @Test public void test_atOffset() { LocalTime t = LocalTime.of(11, 30); - assertEquals(t.atOffset(OFFSET_PTWO), OffsetTime.of(LocalTime.of(11, 30), OFFSET_PTWO)); + assertEquals(OffsetTime.of(LocalTime.of(11, 30), OFFSET_PTWO), t.atOffset(OFFSET_PTWO)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atOffset_nullZoneOffset() { - LocalTime t = LocalTime.of(11, 30); - t.atOffset((ZoneOffset) null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalTime t = LocalTime.of(11, 30); + t.atOffset((ZoneOffset) null); + }); } //----------------------------------------------------------------------- @@ -2421,7 +2439,7 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_toSecondOfDay() { LocalTime t = LocalTime.of(0, 0); for (int i = 0; i < 24 * 60 * 60; i++) { - assertEquals(t.toSecondOfDay(), i); + assertEquals(i, t.toSecondOfDay()); t = t.plusSeconds(1); } } @@ -2429,7 +2447,6 @@ public class TCKLocalTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- // toEpochSecond() //-------------------------------------------------------------------------- - @DataProvider(name="epochSecond") Object[][] provider__toEpochSecond() { return new Object[][] { {LocalTime.of(0, 0).toEpochSecond(LocalDate.of(1970, 1, 1), OFFSET_PTWO), -7200L}, @@ -2444,9 +2461,10 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="epochSecond") + @ParameterizedTest + @MethodSource("provider__toEpochSecond") public void test_toEpochSecond(long actual, long expected) { - assertEquals(actual, expected); + assertEquals(expected, actual); } //----------------------------------------------------------------------- @@ -2456,7 +2474,7 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_toSecondOfDay_fromNanoOfDay_symmetry() { LocalTime t = LocalTime.of(0, 0); for (int i = 0; i < 24 * 60 * 60; i++) { - assertEquals(LocalTime.ofSecondOfDay(t.toSecondOfDay()), t); + assertEquals(t, LocalTime.ofSecondOfDay(t.toSecondOfDay())); t = t.plusSeconds(1); } } @@ -2468,13 +2486,13 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_toNanoOfDay() { LocalTime t = LocalTime.of(0, 0); for (int i = 0; i < 1000000; i++) { - assertEquals(t.toNanoOfDay(), i); + assertEquals(i, t.toNanoOfDay()); t = t.plusNanos(1); } t = LocalTime.of(0, 0); for (int i = 1; i <= 1000000; i++) { t = t.minusNanos(1); - assertEquals(t.toNanoOfDay(), 24 * 60 * 60 * 1000000000L - i); + assertEquals(24 * 60 * 60 * 1000000000L - i, t.toNanoOfDay()); } } @@ -2482,13 +2500,13 @@ public class TCKLocalTime extends AbstractDateTimeTest { public void test_toNanoOfDay_fromNanoOfDay_symmetry() { LocalTime t = LocalTime.of(0, 0); for (int i = 0; i < 1000000; i++) { - assertEquals(LocalTime.ofNanoOfDay(t.toNanoOfDay()), t); + assertEquals(t, LocalTime.ofNanoOfDay(t.toNanoOfDay())); t = t.plusNanos(1); } t = LocalTime.of(0, 0); for (int i = 1; i <= 1000000; i++) { t = t.minusNanos(1); - assertEquals(LocalTime.ofNanoOfDay(t.toNanoOfDay()), t); + assertEquals(t, LocalTime.ofNanoOfDay(t.toNanoOfDay())); } } @@ -2532,137 +2550,148 @@ public class TCKLocalTime extends AbstractDateTimeTest { LocalTime b = localTimes[j]; if (i < j) { assertTrue(a.compareTo(b) < 0, a + " <=> " + b); - assertEquals(a.isBefore(b), true, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { assertTrue(a.compareTo(b) > 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(true, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_ObjectNull() { - TEST_12_30_40_987654321.compareTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.compareTo(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isBefore_ObjectNull() { - TEST_12_30_40_987654321.isBefore(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.isBefore(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isAfter_ObjectNull() { - TEST_12_30_40_987654321.isAfter(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_12_30_40_987654321.isAfter(null)); } - @Test(expectedExceptions=ClassCastException.class) @SuppressWarnings({"unchecked", "rawtypes"}) + @Test public void compareToNonLocalTime() { - Comparable c = TEST_12_30_40_987654321; - c.compareTo(new Object()); + Assertions.assertThrows(ClassCastException.class, () -> { + Comparable c = TEST_12_30_40_987654321; + c.compareTo(new Object()); + }); } //----------------------------------------------------------------------- // equals() //----------------------------------------------------------------------- - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_true(int h, int m, int s, int n) { LocalTime a = LocalTime.of(h, m, s, n); LocalTime b = LocalTime.of(h, m, s, n); - assertEquals(a.equals(b), true); + assertEquals(true, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_hour_differs(int h, int m, int s, int n) { LocalTime a = LocalTime.of(h, m, s, n); LocalTime b = LocalTime.of(h + 1, m, s, n); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_minute_differs(int h, int m, int s, int n) { LocalTime a = LocalTime.of(h, m, s, n); LocalTime b = LocalTime.of(h, m + 1, s, n); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_second_differs(int h, int m, int s, int n) { LocalTime a = LocalTime.of(h, m, s, n); LocalTime b = LocalTime.of(h, m, s + 1, n); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_nano_differs(int h, int m, int s, int n) { LocalTime a = LocalTime.of(h, m, s, n); LocalTime b = LocalTime.of(h, m, s, n + 1); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } @Test public void test_equals_itself_true() { - assertEquals(TEST_12_30_40_987654321.equals(TEST_12_30_40_987654321), true); + assertEquals(true, TEST_12_30_40_987654321.equals(TEST_12_30_40_987654321)); } @Test public void test_equals_string_false() { - assertEquals(TEST_12_30_40_987654321.equals("2007-07-15"), false); + assertEquals(false, TEST_12_30_40_987654321.equals("2007-07-15")); } @Test public void test_equals_null_false() { - assertEquals(TEST_12_30_40_987654321.equals(null), false); + assertEquals(false, TEST_12_30_40_987654321.equals(null)); } //----------------------------------------------------------------------- // hashCode() //----------------------------------------------------------------------- - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_hashCode_same(int h, int m, int s, int n) { LocalTime a = LocalTime.of(h, m, s, n); LocalTime b = LocalTime.of(h, m, s, n); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_hashCode_hour_differs(int h, int m, int s, int n) { LocalTime a = LocalTime.of(h, m, s, n); LocalTime b = LocalTime.of(h + 1, m, s, n); - assertEquals(a.hashCode() == b.hashCode(), false); + assertEquals(false, a.hashCode() == b.hashCode()); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_hashCode_minute_differs(int h, int m, int s, int n) { LocalTime a = LocalTime.of(h, m, s, n); LocalTime b = LocalTime.of(h, m + 1, s, n); - assertEquals(a.hashCode() == b.hashCode(), false); + assertEquals(false, a.hashCode() == b.hashCode()); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_hashCode_second_differs(int h, int m, int s, int n) { LocalTime a = LocalTime.of(h, m, s, n); LocalTime b = LocalTime.of(h, m, s + 1, n); - assertEquals(a.hashCode() == b.hashCode(), false); + assertEquals(false, a.hashCode() == b.hashCode()); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_hashCode_nano_differs(int h, int m, int s, int n) { LocalTime a = LocalTime.of(h, m, s, n); LocalTime b = LocalTime.of(h, m, s, n + 1); - assertEquals(a.hashCode() == b.hashCode(), false); + assertEquals(false, a.hashCode() == b.hashCode()); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="sampleToString") Object[][] provider_sampleToString() { return new Object[][] { {0, 0, 0, 0, "00:00"}, @@ -2694,11 +2723,12 @@ public class TCKLocalTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_toString(int h, int m, int s, int n, String expected) { LocalTime t = LocalTime.of(h, m, s, n); String str = t.toString(); - assertEquals(str, expected); + assertEquals(expected, str); } private LocalTime time(int hour, int min, int sec, int nano) { diff --git a/test/jdk/java/time/tck/java/time/TCKMonth.java b/test/jdk/java/time/tck/java/time/TCKMonth.java index df879e7d1db..a2f1c6ccabf 100644 --- a/test/jdk/java/time/tck/java/time/TCKMonth.java +++ b/test/jdk/java/time/tck/java/time/TCKMonth.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -60,7 +60,8 @@ package tck.java.time; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DateTimeException; import java.time.LocalDate; @@ -80,13 +81,16 @@ import java.util.Arrays; import java.util.List; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test Month. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKMonth extends AbstractDateTimeTest { private static final int MAX_LENGTH = 12; @@ -121,34 +125,34 @@ public class TCKMonth extends AbstractDateTimeTest { public void test_factory_int_singleton() { for (int i = 1; i <= MAX_LENGTH; i++) { Month test = Month.of(i); - assertEquals(test.getValue(), i); + assertEquals(i, test.getValue()); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_tooLow() { - Month.of(0); + Assertions.assertThrows(DateTimeException.class, () -> Month.of(0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_tooHigh() { - Month.of(13); + Assertions.assertThrows(DateTimeException.class, () -> Month.of(13)); } //----------------------------------------------------------------------- @Test public void test_factory_CalendricalObject() { - assertEquals(Month.from(LocalDate.of(2011, 6, 6)), Month.JUNE); + assertEquals(Month.JUNE, Month.from(LocalDate.of(2011, 6, 6))); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_CalendricalObject_invalid_noDerive() { - Month.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> Month.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_CalendricalObject_null() { - Month.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> Month.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- @@ -156,37 +160,37 @@ public class TCKMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(Month.AUGUST.isSupported((TemporalField) null), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.NANO_OF_SECOND), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.NANO_OF_DAY), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.MICRO_OF_SECOND), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.MICRO_OF_DAY), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.MILLI_OF_SECOND), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.MILLI_OF_DAY), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.SECOND_OF_MINUTE), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.SECOND_OF_DAY), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.MINUTE_OF_HOUR), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.MINUTE_OF_DAY), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.HOUR_OF_AMPM), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.HOUR_OF_DAY), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.AMPM_OF_DAY), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.DAY_OF_WEEK), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.DAY_OF_MONTH), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.DAY_OF_YEAR), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.EPOCH_DAY), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.MONTH_OF_YEAR), true); - assertEquals(Month.AUGUST.isSupported(ChronoField.PROLEPTIC_MONTH), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.YEAR), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.YEAR_OF_ERA), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.ERA), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.INSTANT_SECONDS), false); - assertEquals(Month.AUGUST.isSupported(ChronoField.OFFSET_SECONDS), false); + assertEquals(false, Month.AUGUST.isSupported((TemporalField) null)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(true, Month.AUGUST.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.YEAR)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.ERA)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(false, Month.AUGUST.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -194,18 +198,17 @@ public class TCKMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_get_TemporalField() { - assertEquals(Month.JULY.get(ChronoField.MONTH_OF_YEAR), 7); + assertEquals(7, Month.JULY.get(ChronoField.MONTH_OF_YEAR)); } @Test public void test_getLong_TemporalField() { - assertEquals(Month.JULY.getLong(ChronoField.MONTH_OF_YEAR), 7); + assertEquals(7, Month.JULY.getLong(ChronoField.MONTH_OF_YEAR)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {Month.JUNE, TemporalQueries.chronology(), IsoChronology.INSTANCE}, @@ -218,19 +221,21 @@ public class TCKMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - Month.JUNE.query(null); + Assertions.assertThrows(NullPointerException.class, () -> Month.JUNE.query(null)); } //----------------------------------------------------------------------- @@ -238,23 +243,22 @@ public class TCKMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_getText() { - assertEquals(Month.JANUARY.getDisplayName(TextStyle.SHORT, Locale.US), "Jan"); + assertEquals("Jan", Month.JANUARY.getDisplayName(TextStyle.SHORT, Locale.US)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_getText_nullStyle() { - Month.JANUARY.getDisplayName(null, Locale.US); + Assertions.assertThrows(NullPointerException.class, () -> Month.JANUARY.getDisplayName(null, Locale.US)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_getText_nullLocale() { - Month.JANUARY.getDisplayName(TextStyle.FULL, null); + Assertions.assertThrows(NullPointerException.class, () -> Month.JANUARY.getDisplayName(TextStyle.FULL, null)); } //----------------------------------------------------------------------- // plus(long), plus(long,unit) //----------------------------------------------------------------------- - @DataProvider(name="plus") Object[][] data_plus() { return new Object[][] { {1, -13, 12}, @@ -313,15 +317,15 @@ public class TCKMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="plus") + @ParameterizedTest + @MethodSource("data_plus") public void test_plus_long(int base, long amount, int expected) { - assertEquals(Month.of(base).plus(amount), Month.of(expected)); + assertEquals(Month.of(expected), Month.of(base).plus(amount)); } //----------------------------------------------------------------------- // minus(long), minus(long,unit) //----------------------------------------------------------------------- - @DataProvider(name="minus") Object[][] data_minus() { return new Object[][] { {1, -13, 2}, @@ -354,9 +358,10 @@ public class TCKMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="minus") + @ParameterizedTest + @MethodSource("data_minus") public void test_minus_long(int base, long amount, int expected) { - assertEquals(Month.of(base).minus(amount), Month.of(expected)); + assertEquals(Month.of(expected), Month.of(base).minus(amount)); } //----------------------------------------------------------------------- @@ -364,34 +369,34 @@ public class TCKMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_length_boolean_notLeapYear() { - assertEquals(Month.JANUARY.length(false), 31); - assertEquals(Month.FEBRUARY.length(false), 28); - assertEquals(Month.MARCH.length(false), 31); - assertEquals(Month.APRIL.length(false), 30); - assertEquals(Month.MAY.length(false), 31); - assertEquals(Month.JUNE.length(false), 30); - assertEquals(Month.JULY.length(false), 31); - assertEquals(Month.AUGUST.length(false), 31); - assertEquals(Month.SEPTEMBER.length(false), 30); - assertEquals(Month.OCTOBER.length(false), 31); - assertEquals(Month.NOVEMBER.length(false), 30); - assertEquals(Month.DECEMBER.length(false), 31); + assertEquals(31, Month.JANUARY.length(false)); + assertEquals(28, Month.FEBRUARY.length(false)); + assertEquals(31, Month.MARCH.length(false)); + assertEquals(30, Month.APRIL.length(false)); + assertEquals(31, Month.MAY.length(false)); + assertEquals(30, Month.JUNE.length(false)); + assertEquals(31, Month.JULY.length(false)); + assertEquals(31, Month.AUGUST.length(false)); + assertEquals(30, Month.SEPTEMBER.length(false)); + assertEquals(31, Month.OCTOBER.length(false)); + assertEquals(30, Month.NOVEMBER.length(false)); + assertEquals(31, Month.DECEMBER.length(false)); } @Test public void test_length_boolean_leapYear() { - assertEquals(Month.JANUARY.length(true), 31); - assertEquals(Month.FEBRUARY.length(true), 29); - assertEquals(Month.MARCH.length(true), 31); - assertEquals(Month.APRIL.length(true), 30); - assertEquals(Month.MAY.length(true), 31); - assertEquals(Month.JUNE.length(true), 30); - assertEquals(Month.JULY.length(true), 31); - assertEquals(Month.AUGUST.length(true), 31); - assertEquals(Month.SEPTEMBER.length(true), 30); - assertEquals(Month.OCTOBER.length(true), 31); - assertEquals(Month.NOVEMBER.length(true), 30); - assertEquals(Month.DECEMBER.length(true), 31); + assertEquals(31, Month.JANUARY.length(true)); + assertEquals(29, Month.FEBRUARY.length(true)); + assertEquals(31, Month.MARCH.length(true)); + assertEquals(30, Month.APRIL.length(true)); + assertEquals(31, Month.MAY.length(true)); + assertEquals(30, Month.JUNE.length(true)); + assertEquals(31, Month.JULY.length(true)); + assertEquals(31, Month.AUGUST.length(true)); + assertEquals(30, Month.SEPTEMBER.length(true)); + assertEquals(31, Month.OCTOBER.length(true)); + assertEquals(30, Month.NOVEMBER.length(true)); + assertEquals(31, Month.DECEMBER.length(true)); } //----------------------------------------------------------------------- @@ -399,18 +404,18 @@ public class TCKMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_minLength() { - assertEquals(Month.JANUARY.minLength(), 31); - assertEquals(Month.FEBRUARY.minLength(), 28); - assertEquals(Month.MARCH.minLength(), 31); - assertEquals(Month.APRIL.minLength(), 30); - assertEquals(Month.MAY.minLength(), 31); - assertEquals(Month.JUNE.minLength(), 30); - assertEquals(Month.JULY.minLength(), 31); - assertEquals(Month.AUGUST.minLength(), 31); - assertEquals(Month.SEPTEMBER.minLength(), 30); - assertEquals(Month.OCTOBER.minLength(), 31); - assertEquals(Month.NOVEMBER.minLength(), 30); - assertEquals(Month.DECEMBER.minLength(), 31); + assertEquals(31, Month.JANUARY.minLength()); + assertEquals(28, Month.FEBRUARY.minLength()); + assertEquals(31, Month.MARCH.minLength()); + assertEquals(30, Month.APRIL.minLength()); + assertEquals(31, Month.MAY.minLength()); + assertEquals(30, Month.JUNE.minLength()); + assertEquals(31, Month.JULY.minLength()); + assertEquals(31, Month.AUGUST.minLength()); + assertEquals(30, Month.SEPTEMBER.minLength()); + assertEquals(31, Month.OCTOBER.minLength()); + assertEquals(30, Month.NOVEMBER.minLength()); + assertEquals(31, Month.DECEMBER.minLength()); } //----------------------------------------------------------------------- @@ -418,18 +423,18 @@ public class TCKMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_maxLength() { - assertEquals(Month.JANUARY.maxLength(), 31); - assertEquals(Month.FEBRUARY.maxLength(), 29); - assertEquals(Month.MARCH.maxLength(), 31); - assertEquals(Month.APRIL.maxLength(), 30); - assertEquals(Month.MAY.maxLength(), 31); - assertEquals(Month.JUNE.maxLength(), 30); - assertEquals(Month.JULY.maxLength(), 31); - assertEquals(Month.AUGUST.maxLength(), 31); - assertEquals(Month.SEPTEMBER.maxLength(), 30); - assertEquals(Month.OCTOBER.maxLength(), 31); - assertEquals(Month.NOVEMBER.maxLength(), 30); - assertEquals(Month.DECEMBER.maxLength(), 31); + assertEquals(31, Month.JANUARY.maxLength()); + assertEquals(29, Month.FEBRUARY.maxLength()); + assertEquals(31, Month.MARCH.maxLength()); + assertEquals(30, Month.APRIL.maxLength()); + assertEquals(31, Month.MAY.maxLength()); + assertEquals(30, Month.JUNE.maxLength()); + assertEquals(31, Month.JULY.maxLength()); + assertEquals(31, Month.AUGUST.maxLength()); + assertEquals(30, Month.SEPTEMBER.maxLength()); + assertEquals(31, Month.OCTOBER.maxLength()); + assertEquals(30, Month.NOVEMBER.maxLength()); + assertEquals(31, Month.DECEMBER.maxLength()); } //----------------------------------------------------------------------- @@ -437,34 +442,34 @@ public class TCKMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_firstDayOfYear_notLeapYear() { - assertEquals(Month.JANUARY.firstDayOfYear(false), 1); - assertEquals(Month.FEBRUARY.firstDayOfYear(false), 1 + 31); - assertEquals(Month.MARCH.firstDayOfYear(false), 1 + 31 + 28); - assertEquals(Month.APRIL.firstDayOfYear(false), 1 + 31 + 28 + 31); - assertEquals(Month.MAY.firstDayOfYear(false), 1 + 31 + 28 + 31 + 30); - assertEquals(Month.JUNE.firstDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31); - assertEquals(Month.JULY.firstDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30); - assertEquals(Month.AUGUST.firstDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30 + 31); - assertEquals(Month.SEPTEMBER.firstDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31); - assertEquals(Month.OCTOBER.firstDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30); - assertEquals(Month.NOVEMBER.firstDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31); - assertEquals(Month.DECEMBER.firstDayOfYear(false), 1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30); + assertEquals(1, Month.JANUARY.firstDayOfYear(false)); + assertEquals(1 + 31, Month.FEBRUARY.firstDayOfYear(false)); + assertEquals(1 + 31 + 28, Month.MARCH.firstDayOfYear(false)); + assertEquals(1 + 31 + 28 + 31, Month.APRIL.firstDayOfYear(false)); + assertEquals(1 + 31 + 28 + 31 + 30, Month.MAY.firstDayOfYear(false)); + assertEquals(1 + 31 + 28 + 31 + 30 + 31, Month.JUNE.firstDayOfYear(false)); + assertEquals(1 + 31 + 28 + 31 + 30 + 31 + 30, Month.JULY.firstDayOfYear(false)); + assertEquals(1 + 31 + 28 + 31 + 30 + 31 + 30 + 31, Month.AUGUST.firstDayOfYear(false)); + assertEquals(1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31, Month.SEPTEMBER.firstDayOfYear(false)); + assertEquals(1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30, Month.OCTOBER.firstDayOfYear(false)); + assertEquals(1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, Month.NOVEMBER.firstDayOfYear(false)); + assertEquals(1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, Month.DECEMBER.firstDayOfYear(false)); } @Test public void test_firstDayOfYear_leapYear() { - assertEquals(Month.JANUARY.firstDayOfYear(true), 1); - assertEquals(Month.FEBRUARY.firstDayOfYear(true), 1 + 31); - assertEquals(Month.MARCH.firstDayOfYear(true), 1 + 31 + 29); - assertEquals(Month.APRIL.firstDayOfYear(true), 1 + 31 + 29 + 31); - assertEquals(Month.MAY.firstDayOfYear(true), 1 + 31 + 29 + 31 + 30); - assertEquals(Month.JUNE.firstDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31); - assertEquals(Month.JULY.firstDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30); - assertEquals(Month.AUGUST.firstDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30 + 31); - assertEquals(Month.SEPTEMBER.firstDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31); - assertEquals(Month.OCTOBER.firstDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30); - assertEquals(Month.NOVEMBER.firstDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31); - assertEquals(Month.DECEMBER.firstDayOfYear(true), 1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30); + assertEquals(1, Month.JANUARY.firstDayOfYear(true)); + assertEquals(1 + 31, Month.FEBRUARY.firstDayOfYear(true)); + assertEquals(1 + 31 + 29, Month.MARCH.firstDayOfYear(true)); + assertEquals(1 + 31 + 29 + 31, Month.APRIL.firstDayOfYear(true)); + assertEquals(1 + 31 + 29 + 31 + 30, Month.MAY.firstDayOfYear(true)); + assertEquals(1 + 31 + 29 + 31 + 30 + 31, Month.JUNE.firstDayOfYear(true)); + assertEquals(1 + 31 + 29 + 31 + 30 + 31 + 30, Month.JULY.firstDayOfYear(true)); + assertEquals(1 + 31 + 29 + 31 + 30 + 31 + 30 + 31, Month.AUGUST.firstDayOfYear(true)); + assertEquals(1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31, Month.SEPTEMBER.firstDayOfYear(true)); + assertEquals(1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30, Month.OCTOBER.firstDayOfYear(true)); + assertEquals(1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, Month.NOVEMBER.firstDayOfYear(true)); + assertEquals(1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, Month.DECEMBER.firstDayOfYear(true)); } //----------------------------------------------------------------------- @@ -472,18 +477,18 @@ public class TCKMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_firstMonthOfQuarter() { - assertEquals(Month.JANUARY.firstMonthOfQuarter(), Month.JANUARY); - assertEquals(Month.FEBRUARY.firstMonthOfQuarter(), Month.JANUARY); - assertEquals(Month.MARCH.firstMonthOfQuarter(), Month.JANUARY); - assertEquals(Month.APRIL.firstMonthOfQuarter(), Month.APRIL); - assertEquals(Month.MAY.firstMonthOfQuarter(), Month.APRIL); - assertEquals(Month.JUNE.firstMonthOfQuarter(), Month.APRIL); - assertEquals(Month.JULY.firstMonthOfQuarter(), Month.JULY); - assertEquals(Month.AUGUST.firstMonthOfQuarter(), Month.JULY); - assertEquals(Month.SEPTEMBER.firstMonthOfQuarter(), Month.JULY); - assertEquals(Month.OCTOBER.firstMonthOfQuarter(), Month.OCTOBER); - assertEquals(Month.NOVEMBER.firstMonthOfQuarter(), Month.OCTOBER); - assertEquals(Month.DECEMBER.firstMonthOfQuarter(), Month.OCTOBER); + assertEquals(Month.JANUARY, Month.JANUARY.firstMonthOfQuarter()); + assertEquals(Month.JANUARY, Month.FEBRUARY.firstMonthOfQuarter()); + assertEquals(Month.JANUARY, Month.MARCH.firstMonthOfQuarter()); + assertEquals(Month.APRIL, Month.APRIL.firstMonthOfQuarter()); + assertEquals(Month.APRIL, Month.MAY.firstMonthOfQuarter()); + assertEquals(Month.APRIL, Month.JUNE.firstMonthOfQuarter()); + assertEquals(Month.JULY, Month.JULY.firstMonthOfQuarter()); + assertEquals(Month.JULY, Month.AUGUST.firstMonthOfQuarter()); + assertEquals(Month.JULY, Month.SEPTEMBER.firstMonthOfQuarter()); + assertEquals(Month.OCTOBER, Month.OCTOBER.firstMonthOfQuarter()); + assertEquals(Month.OCTOBER, Month.NOVEMBER.firstMonthOfQuarter()); + assertEquals(Month.OCTOBER, Month.DECEMBER.firstMonthOfQuarter()); } //----------------------------------------------------------------------- @@ -491,18 +496,18 @@ public class TCKMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_toString() { - assertEquals(Month.JANUARY.toString(), "JANUARY"); - assertEquals(Month.FEBRUARY.toString(), "FEBRUARY"); - assertEquals(Month.MARCH.toString(), "MARCH"); - assertEquals(Month.APRIL.toString(), "APRIL"); - assertEquals(Month.MAY.toString(), "MAY"); - assertEquals(Month.JUNE.toString(), "JUNE"); - assertEquals(Month.JULY.toString(), "JULY"); - assertEquals(Month.AUGUST.toString(), "AUGUST"); - assertEquals(Month.SEPTEMBER.toString(), "SEPTEMBER"); - assertEquals(Month.OCTOBER.toString(), "OCTOBER"); - assertEquals(Month.NOVEMBER.toString(), "NOVEMBER"); - assertEquals(Month.DECEMBER.toString(), "DECEMBER"); + assertEquals("JANUARY", Month.JANUARY.toString()); + assertEquals("FEBRUARY", Month.FEBRUARY.toString()); + assertEquals("MARCH", Month.MARCH.toString()); + assertEquals("APRIL", Month.APRIL.toString()); + assertEquals("MAY", Month.MAY.toString()); + assertEquals("JUNE", Month.JUNE.toString()); + assertEquals("JULY", Month.JULY.toString()); + assertEquals("AUGUST", Month.AUGUST.toString()); + assertEquals("SEPTEMBER", Month.SEPTEMBER.toString()); + assertEquals("OCTOBER", Month.OCTOBER.toString()); + assertEquals("NOVEMBER", Month.NOVEMBER.toString()); + assertEquals("DECEMBER", Month.DECEMBER.toString()); } //----------------------------------------------------------------------- @@ -510,8 +515,8 @@ public class TCKMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_enum() { - assertEquals(Month.valueOf("JANUARY"), Month.JANUARY); - assertEquals(Month.values()[0], Month.JANUARY); + assertEquals(Month.JANUARY, Month.valueOf("JANUARY")); + assertEquals(Month.JANUARY, Month.values()[0]); } } diff --git a/test/jdk/java/time/tck/java/time/TCKMonthDay.java b/test/jdk/java/time/tck/java/time/TCKMonthDay.java index 99a711666d8..36ad4af069e 100644 --- a/test/jdk/java/time/tck/java/time/TCKMonthDay.java +++ b/test/jdk/java/time/tck/java/time/TCKMonthDay.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -61,9 +61,10 @@ package tck.java.time; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; @@ -94,19 +95,22 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test MonthDay. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKMonthDay extends AbstractDateTimeTest { private MonthDay TEST_07_15; - @BeforeMethod + @BeforeEach public void setUp() { TEST_07_15 = MonthDay.of(7, 15); } @@ -114,7 +118,7 @@ public class TCKMonthDay extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Override protected List samples() { - TemporalAccessor[] array = {TEST_07_15, }; + TemporalAccessor[] array = {MonthDay.of(7, 15), }; return Arrays.asList(array); } @@ -139,8 +143,8 @@ public class TCKMonthDay extends AbstractDateTimeTest { //----------------------------------------------------------------------- void check(MonthDay test, int m, int d) { - assertEquals(test.getMonth().getValue(), m); - assertEquals(test.getDayOfMonth(), d); + assertEquals(m, test.getMonth().getValue()); + assertEquals(d, test.getDayOfMonth()); } //----------------------------------------------------------------------- @@ -157,15 +161,15 @@ public class TCKMonthDay extends AbstractDateTimeTest { expected = MonthDay.now(Clock.systemDefaultZone()); test = MonthDay.now(); } - assertEquals(test, expected); + assertEquals(expected, test); } //----------------------------------------------------------------------- // now(ZoneId) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_ZoneId_nullZoneId() { - MonthDay.now((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> MonthDay.now((ZoneId) null)); } @Test @@ -180,7 +184,7 @@ public class TCKMonthDay extends AbstractDateTimeTest { expected = MonthDay.now(Clock.system(zone)); test = MonthDay.now(zone); } - assertEquals(test, expected); + assertEquals(expected, test); } //----------------------------------------------------------------------- @@ -191,34 +195,34 @@ public class TCKMonthDay extends AbstractDateTimeTest { Instant instant = LocalDateTime.of(2010, 12, 31, 0, 0).toInstant(ZoneOffset.UTC); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); MonthDay test = MonthDay.now(clock); - assertEquals(test.getMonth(), Month.DECEMBER); - assertEquals(test.getDayOfMonth(), 31); + assertEquals(Month.DECEMBER, test.getMonth()); + assertEquals(31, test.getDayOfMonth()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullClock() { - MonthDay.now((Clock) null); + Assertions.assertThrows(NullPointerException.class, () -> MonthDay.now((Clock) null)); } //----------------------------------------------------------------------- @Test public void factory_intMonth() { - assertEquals(TEST_07_15, MonthDay.of(Month.JULY, 15)); + assertEquals(MonthDay.of(Month.JULY, 15), TEST_07_15); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_intMonth_dayTooLow() { - MonthDay.of(Month.JANUARY, 0); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(Month.JANUARY, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_intMonth_dayTooHigh() { - MonthDay.of(Month.JANUARY, 32); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(Month.JANUARY, 32)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_intMonth_nullMonth() { - MonthDay.of(null, 15); + Assertions.assertThrows(NullPointerException.class, () -> MonthDay.of(null, 15)); } //----------------------------------------------------------------------- @@ -227,47 +231,46 @@ public class TCKMonthDay extends AbstractDateTimeTest { check(TEST_07_15, 7, 15); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ints_dayTooLow() { - MonthDay.of(1, 0); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(1, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ints_dayTooHigh() { - MonthDay.of(1, 32); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(1, 32)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ints_monthTooLow() { - MonthDay.of(0, 1); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(0, 1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ints_monthTooHigh() { - MonthDay.of(13, 1); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(13, 1)); } //----------------------------------------------------------------------- @Test public void test_factory_CalendricalObject() { - assertEquals(MonthDay.from(LocalDate.of(2007, 7, 15)), TEST_07_15); + assertEquals(TEST_07_15, MonthDay.from(LocalDate.of(2007, 7, 15))); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_CalendricalObject_invalid_noDerive() { - MonthDay.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_CalendricalObject_null() { - MonthDay.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> MonthDay.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- // parse() //----------------------------------------------------------------------- - @DataProvider(name="goodParseData") Object[][] provider_goodParseData() { return new Object[][] { {"--01-01", MonthDay.of(1, 1)}, @@ -297,14 +300,14 @@ public class TCKMonthDay extends AbstractDateTimeTest { }; } - @Test(dataProvider="goodParseData") + @ParameterizedTest + @MethodSource("provider_goodParseData") public void factory_parse_success(String text, MonthDay expected) { MonthDay monthDay = MonthDay.parse(text); - assertEquals(monthDay, expected); + assertEquals(expected, monthDay); } //----------------------------------------------------------------------- - @DataProvider(name="badParseData") Object[][] provider_badParseData() { return new Object[][] { {"", 0}, @@ -315,38 +318,40 @@ public class TCKMonthDay extends AbstractDateTimeTest { }; } - @Test(dataProvider="badParseData", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("provider_badParseData") public void factory_parse_fail(String text, int pos) { - try { - MonthDay.parse(text); - fail(String.format("Parse should have failed for %s at position %d", text, pos)); - } - catch (DateTimeParseException ex) { - assertEquals(ex.getParsedString(), text); - assertEquals(ex.getErrorIndex(), pos); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + try { + MonthDay.parse(text); + fail(String.format("Parse should have failed for %s at position %d", text, pos)); + } catch (DateTimeParseException ex) { + assertEquals(text, ex.getParsedString()); + assertEquals(pos, ex.getErrorIndex()); + throw ex; + } + }); } //----------------------------------------------------------------------- - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_illegalValue_Day() { - MonthDay.parse("--06-32"); + Assertions.assertThrows(DateTimeParseException.class, () -> MonthDay.parse("--06-32")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_invalidValue_Day() { - MonthDay.parse("--06-31"); + Assertions.assertThrows(DateTimeParseException.class, () -> MonthDay.parse("--06-31")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_illegalValue_Month() { - MonthDay.parse("--13-25"); + Assertions.assertThrows(DateTimeParseException.class, () -> MonthDay.parse("--13-25")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_nullText() { - MonthDay.parse(null); + Assertions.assertThrows(NullPointerException.class, () -> MonthDay.parse(null)); } //----------------------------------------------------------------------- @@ -356,18 +361,20 @@ public class TCKMonthDay extends AbstractDateTimeTest { public void factory_parse_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("M d"); MonthDay test = MonthDay.parse("12 3", f); - assertEquals(test, MonthDay.of(12, 3)); + assertEquals(MonthDay.of(12, 3), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullText() { - DateTimeFormatter f = DateTimeFormatter.ofPattern("M d"); - MonthDay.parse((String) null, f); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter f = DateTimeFormatter.ofPattern("M d"); + MonthDay.parse((String) null, f); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullFormatter() { - MonthDay.parse("ANY", null); + Assertions.assertThrows(NullPointerException.class, () -> MonthDay.parse("ANY", null)); } //----------------------------------------------------------------------- @@ -375,37 +382,37 @@ public class TCKMonthDay extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(TEST_07_15.isSupported((TemporalField) null), false); - assertEquals(TEST_07_15.isSupported(ChronoField.NANO_OF_SECOND), false); - assertEquals(TEST_07_15.isSupported(ChronoField.NANO_OF_DAY), false); - assertEquals(TEST_07_15.isSupported(ChronoField.MICRO_OF_SECOND), false); - assertEquals(TEST_07_15.isSupported(ChronoField.MICRO_OF_DAY), false); - assertEquals(TEST_07_15.isSupported(ChronoField.MILLI_OF_SECOND), false); - assertEquals(TEST_07_15.isSupported(ChronoField.MILLI_OF_DAY), false); - assertEquals(TEST_07_15.isSupported(ChronoField.SECOND_OF_MINUTE), false); - assertEquals(TEST_07_15.isSupported(ChronoField.SECOND_OF_DAY), false); - assertEquals(TEST_07_15.isSupported(ChronoField.MINUTE_OF_HOUR), false); - assertEquals(TEST_07_15.isSupported(ChronoField.MINUTE_OF_DAY), false); - assertEquals(TEST_07_15.isSupported(ChronoField.HOUR_OF_AMPM), false); - assertEquals(TEST_07_15.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), false); - assertEquals(TEST_07_15.isSupported(ChronoField.HOUR_OF_DAY), false); - assertEquals(TEST_07_15.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), false); - assertEquals(TEST_07_15.isSupported(ChronoField.AMPM_OF_DAY), false); - assertEquals(TEST_07_15.isSupported(ChronoField.DAY_OF_WEEK), false); - assertEquals(TEST_07_15.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), false); - assertEquals(TEST_07_15.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), false); - assertEquals(TEST_07_15.isSupported(ChronoField.DAY_OF_MONTH), true); - assertEquals(TEST_07_15.isSupported(ChronoField.DAY_OF_YEAR), false); - assertEquals(TEST_07_15.isSupported(ChronoField.EPOCH_DAY), false); - assertEquals(TEST_07_15.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), false); - assertEquals(TEST_07_15.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), false); - assertEquals(TEST_07_15.isSupported(ChronoField.MONTH_OF_YEAR), true); - assertEquals(TEST_07_15.isSupported(ChronoField.PROLEPTIC_MONTH), false); - assertEquals(TEST_07_15.isSupported(ChronoField.YEAR), false); - assertEquals(TEST_07_15.isSupported(ChronoField.YEAR_OF_ERA), false); - assertEquals(TEST_07_15.isSupported(ChronoField.ERA), false); - assertEquals(TEST_07_15.isSupported(ChronoField.INSTANT_SECONDS), false); - assertEquals(TEST_07_15.isSupported(ChronoField.OFFSET_SECONDS), false); + assertEquals(false, TEST_07_15.isSupported((TemporalField) null)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(true, TEST_07_15.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(true, TEST_07_15.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.YEAR)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.ERA)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(false, TEST_07_15.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -413,20 +420,19 @@ public class TCKMonthDay extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_get_TemporalField() { - assertEquals(TEST_07_15.get(ChronoField.DAY_OF_MONTH), 15); - assertEquals(TEST_07_15.get(ChronoField.MONTH_OF_YEAR), 7); + assertEquals(15, TEST_07_15.get(ChronoField.DAY_OF_MONTH)); + assertEquals(7, TEST_07_15.get(ChronoField.MONTH_OF_YEAR)); } @Test public void test_getLong_TemporalField() { - assertEquals(TEST_07_15.getLong(ChronoField.DAY_OF_MONTH), 15); - assertEquals(TEST_07_15.getLong(ChronoField.MONTH_OF_YEAR), 7); + assertEquals(15, TEST_07_15.getLong(ChronoField.DAY_OF_MONTH)); + assertEquals(7, TEST_07_15.getLong(ChronoField.MONTH_OF_YEAR)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {TEST_07_15, TemporalQueries.chronology(), IsoChronology.INSTANCE}, @@ -439,25 +445,26 @@ public class TCKMonthDay extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - TEST_07_15.query(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_07_15.query(null)); } //----------------------------------------------------------------------- // get*() //----------------------------------------------------------------------- - @DataProvider(name="sampleDates") Object[][] provider_sampleDates() { return new Object[][] { {1, 1}, @@ -470,12 +477,13 @@ public class TCKMonthDay extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_get(int m, int d) { MonthDay a = MonthDay.of(m, d); - assertEquals(a.getMonth(), Month.of(m)); - assertEquals(a.getMonthValue(), m); - assertEquals(a.getDayOfMonth(), d); + assertEquals(Month.of(m), a.getMonth()); + assertEquals(m, a.getMonthValue()); + assertEquals(d, a.getDayOfMonth()); } //----------------------------------------------------------------------- @@ -483,28 +491,28 @@ public class TCKMonthDay extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_with_Month() { - assertEquals(MonthDay.of(6, 30).with(Month.JANUARY), MonthDay.of(1, 30)); + assertEquals(MonthDay.of(1, 30), MonthDay.of(6, 30).with(Month.JANUARY)); } @Test public void test_with_Month_adjustToValid() { - assertEquals(MonthDay.of(7, 31).with(Month.JUNE), MonthDay.of(6, 30)); + assertEquals(MonthDay.of(6, 30), MonthDay.of(7, 31).with(Month.JUNE)); } @Test public void test_with_Month_adjustToValidFeb() { - assertEquals(MonthDay.of(7, 31).with(Month.FEBRUARY), MonthDay.of(2, 29)); + assertEquals(MonthDay.of(2, 29), MonthDay.of(7, 31).with(Month.FEBRUARY)); } @Test public void test_with_Month_noChangeEqual() { MonthDay test = MonthDay.of(6, 30); - assertEquals(test.with(Month.JUNE), test); + assertEquals(test, test.with(Month.JUNE)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_with_Month_null() { - MonthDay.of(6, 30).with((Month) null); + Assertions.assertThrows(NullPointerException.class, () -> MonthDay.of(6, 30).with((Month) null)); } //----------------------------------------------------------------------- @@ -512,33 +520,33 @@ public class TCKMonthDay extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_withMonth() { - assertEquals(MonthDay.of(6, 30).withMonth(1), MonthDay.of(1, 30)); + assertEquals(MonthDay.of(1, 30), MonthDay.of(6, 30).withMonth(1)); } @Test public void test_withMonth_adjustToValid() { - assertEquals(MonthDay.of(7, 31).withMonth(6), MonthDay.of(6, 30)); + assertEquals(MonthDay.of(6, 30), MonthDay.of(7, 31).withMonth(6)); } @Test public void test_withMonth_adjustToValidFeb() { - assertEquals(MonthDay.of(7, 31).withMonth(2), MonthDay.of(2, 29)); + assertEquals(MonthDay.of(2, 29), MonthDay.of(7, 31).withMonth(2)); } @Test public void test_withMonth_int_noChangeEqual() { MonthDay test = MonthDay.of(6, 30); - assertEquals(test.withMonth(6), test); + assertEquals(test, test.withMonth(6)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMonth_tooLow() { - MonthDay.of(6, 30).withMonth(0); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(6, 30).withMonth(0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMonth_tooHigh() { - MonthDay.of(6, 30).withMonth(13); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(6, 30).withMonth(13)); } //----------------------------------------------------------------------- @@ -546,33 +554,33 @@ public class TCKMonthDay extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_withDayOfMonth() { - assertEquals(MonthDay.of(6, 30).withDayOfMonth(1), MonthDay.of(6, 1)); + assertEquals(MonthDay.of(6, 1), MonthDay.of(6, 30).withDayOfMonth(1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfMonth_invalid() { - MonthDay.of(6, 30).withDayOfMonth(31); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(6, 30).withDayOfMonth(31)); } @Test public void test_withDayOfMonth_adjustToValidFeb() { - assertEquals(MonthDay.of(2, 1).withDayOfMonth(29), MonthDay.of(2, 29)); + assertEquals(MonthDay.of(2, 29), MonthDay.of(2, 1).withDayOfMonth(29)); } @Test public void test_withDayOfMonth_noChangeEqual() { MonthDay test = MonthDay.of(6, 30); - assertEquals(test.withDayOfMonth(30), test); + assertEquals(test, test.withDayOfMonth(30)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfMonth_tooLow() { - MonthDay.of(6, 30).withDayOfMonth(0); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(6, 30).withDayOfMonth(0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfMonth_tooHigh() { - MonthDay.of(6, 30).withDayOfMonth(32); + Assertions.assertThrows(DateTimeException.class, () -> MonthDay.of(6, 30).withDayOfMonth(32)); } //----------------------------------------------------------------------- @@ -582,26 +590,26 @@ public class TCKMonthDay extends AbstractDateTimeTest { public void test_adjustDate() { MonthDay test = MonthDay.of(6, 30); LocalDate date = LocalDate.of(2007, 1, 1); - assertEquals(test.adjustInto(date), LocalDate.of(2007, 6, 30)); + assertEquals(LocalDate.of(2007, 6, 30), test.adjustInto(date)); } @Test public void test_adjustDate_resolve() { MonthDay test = MonthDay.of(2, 29); LocalDate date = LocalDate.of(2007, 6, 30); - assertEquals(test.adjustInto(date), LocalDate.of(2007, 2, 28)); + assertEquals(LocalDate.of(2007, 2, 28), test.adjustInto(date)); } @Test public void test_adjustDate_equal() { MonthDay test = MonthDay.of(6, 30); LocalDate date = LocalDate.of(2007, 6, 30); - assertEquals(test.adjustInto(date), date); + assertEquals(date, test.adjustInto(date)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_adjustDate_null() { - TEST_07_15.adjustInto((LocalDate) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_07_15.adjustInto((LocalDate) null)); } //----------------------------------------------------------------------- @@ -610,19 +618,19 @@ public class TCKMonthDay extends AbstractDateTimeTest { @Test public void test_isValidYear_june() { MonthDay test = MonthDay.of(6, 30); - assertEquals(test.isValidYear(2007), true); + assertEquals(true, test.isValidYear(2007)); } @Test public void test_isValidYear_febNonLeap() { MonthDay test = MonthDay.of(2, 29); - assertEquals(test.isValidYear(2007), false); + assertEquals(false, test.isValidYear(2007)); } @Test public void test_isValidYear_febLeap() { MonthDay test = MonthDay.of(2, 29); - assertEquals(test.isValidYear(2008), true); + assertEquals(true, test.isValidYear(2008)); } //----------------------------------------------------------------------- @@ -632,12 +640,12 @@ public class TCKMonthDay extends AbstractDateTimeTest { public void test_format_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("M d"); String t = MonthDay.of(12, 3).format(f); - assertEquals(t, "12 3"); + assertEquals("12 3", t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_format_formatter_null() { - MonthDay.of(12, 3).format(null); + Assertions.assertThrows(NullPointerException.class, () -> MonthDay.of(12, 3).format(null)); } //----------------------------------------------------------------------- @@ -646,19 +654,21 @@ public class TCKMonthDay extends AbstractDateTimeTest { @Test public void test_atYear_int() { MonthDay test = MonthDay.of(6, 30); - assertEquals(test.atYear(2008), LocalDate.of(2008, 6, 30)); + assertEquals(LocalDate.of(2008, 6, 30), test.atYear(2008)); } @Test public void test_atYear_int_leapYearAdjust() { MonthDay test = MonthDay.of(2, 29); - assertEquals(test.atYear(2005), LocalDate.of(2005, 2, 28)); + assertEquals(LocalDate.of(2005, 2, 28), test.atYear(2005)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atYear_int_invalidYear() { - MonthDay test = MonthDay.of(6, 30); - test.atYear(Integer.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + MonthDay test = MonthDay.of(6, 30); + test.atYear(Integer.MIN_VALUE); + }); } //----------------------------------------------------------------------- @@ -683,37 +693,37 @@ public class TCKMonthDay extends AbstractDateTimeTest { MonthDay b = localDates[j]; if (i < j) { assertTrue(a.compareTo(b) < 0, a + " <=> " + b); - assertEquals(a.isBefore(b), true, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { assertTrue(a.compareTo(b) > 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(true, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_ObjectNull() { - TEST_07_15.compareTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_07_15.compareTo(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isBefore_ObjectNull() { - TEST_07_15.isBefore(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_07_15.isBefore(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isAfter_ObjectNull() { - TEST_07_15.isAfter(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_07_15.isAfter(null)); } //----------------------------------------------------------------------- @@ -726,51 +736,52 @@ public class TCKMonthDay extends AbstractDateTimeTest { MonthDay c = MonthDay.of(2, 1); MonthDay d = MonthDay.of(1, 2); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), true); - assertEquals(a.equals(c), false); - assertEquals(a.equals(d), false); + assertEquals(true, a.equals(a)); + assertEquals(true, a.equals(b)); + assertEquals(false, a.equals(c)); + assertEquals(false, a.equals(d)); - assertEquals(b.equals(a), true); - assertEquals(b.equals(b), true); - assertEquals(b.equals(c), false); - assertEquals(b.equals(d), false); + assertEquals(true, b.equals(a)); + assertEquals(true, b.equals(b)); + assertEquals(false, b.equals(c)); + assertEquals(false, b.equals(d)); - assertEquals(c.equals(a), false); - assertEquals(c.equals(b), false); - assertEquals(c.equals(c), true); - assertEquals(c.equals(d), false); + assertEquals(false, c.equals(a)); + assertEquals(false, c.equals(b)); + assertEquals(true, c.equals(c)); + assertEquals(false, c.equals(d)); - assertEquals(d.equals(a), false); - assertEquals(d.equals(b), false); - assertEquals(d.equals(c), false); - assertEquals(d.equals(d), true); + assertEquals(false, d.equals(a)); + assertEquals(false, d.equals(b)); + assertEquals(false, d.equals(c)); + assertEquals(true, d.equals(d)); } @Test public void test_equals_itself_true() { - assertEquals(TEST_07_15.equals(TEST_07_15), true); + assertEquals(true, TEST_07_15.equals(TEST_07_15)); } @Test public void test_equals_string_false() { - assertEquals(TEST_07_15.equals("2007-07-15"), false); + assertEquals(false, TEST_07_15.equals("2007-07-15")); } @Test public void test_equals_null_false() { - assertEquals(TEST_07_15.equals(null), false); + assertEquals(false, TEST_07_15.equals(null)); } //----------------------------------------------------------------------- // hashCode() //----------------------------------------------------------------------- - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_hashCode(int m, int d) { MonthDay a = MonthDay.of(m, d); assertEquals(a.hashCode(), a.hashCode()); MonthDay b = MonthDay.of(m, d); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); } @Test @@ -789,7 +800,6 @@ public class TCKMonthDay extends AbstractDateTimeTest { //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="sampleToString") Object[][] provider_sampleToString() { return new Object[][] { {7, 5, "--07-05"}, @@ -798,11 +808,12 @@ public class TCKMonthDay extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_toString(int m, int d, String expected) { MonthDay test = MonthDay.of(m, d); String str = test.toString(); - assertEquals(str, expected); + assertEquals(expected, str); } } diff --git a/test/jdk/java/time/tck/java/time/TCKOffsetDateTime.java b/test/jdk/java/time/tck/java/time/TCKOffsetDateTime.java index 7b45ba35ca6..6ba0318890f 100644 --- a/test/jdk/java/time/tck/java/time/TCKOffsetDateTime.java +++ b/test/jdk/java/time/tck/java/time/TCKOffsetDateTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -100,9 +100,10 @@ import static java.time.temporal.ChronoUnit.MINUTES; import static java.time.temporal.ChronoUnit.MONTHS; import static java.time.temporal.ChronoUnit.NANOS; import static java.time.temporal.ChronoUnit.SECONDS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.Clock; import java.time.DateTimeException; @@ -135,15 +136,19 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.MockSimplePeriod; /** * Test OffsetDateTime. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKOffsetDateTime extends AbstractDateTimeTest { private static final ZoneId ZONE_PARIS = ZoneId.of("Europe/Paris"); @@ -154,7 +159,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { private static final ZoneOffset OFFSET_MTWO = ZoneOffset.ofHours(-2); private OffsetDateTime TEST_2008_6_30_11_30_59_000000500; - @BeforeMethod + @BeforeEach public void setUp() { TEST_2008_6_30_11_30_59_000000500 = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 500, OFFSET_PONE); } @@ -162,7 +167,8 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Override protected List samples() { - TemporalAccessor[] array = {TEST_2008_6_30_11_30_59_000000500, OffsetDateTime.MIN, OffsetDateTime.MAX}; + TemporalAccessor[] array = {OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 500, OFFSET_PONE), + OffsetDateTime.MIN, OffsetDateTime.MAX}; return Arrays.asList(array); } @@ -253,14 +259,14 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); OffsetDateTime test = OffsetDateTime.now(clock); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60 ? 1 : 2)); - assertEquals(test.getHour(), (i / (60 * 60)) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); - assertEquals(test.getNano(), 123456789); - assertEquals(test.getOffset(), ZoneOffset.UTC); + assertEquals(1970, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals((i < 24 * 60 * 60 ? 1 : 2), test.getDayOfMonth()); + assertEquals((i / (60 * 60)) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); + assertEquals(123456789, test.getNano()); + assertEquals(ZoneOffset.UTC, test.getOffset()); } } @@ -270,14 +276,14 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L); Clock clock = Clock.fixed(instant.minusSeconds(OFFSET_PONE.getTotalSeconds()), OFFSET_PONE); OffsetDateTime test = OffsetDateTime.now(clock); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60) ? 1 : 2); - assertEquals(test.getHour(), (i / (60 * 60)) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); - assertEquals(test.getNano(), 123456789); - assertEquals(test.getOffset(), OFFSET_PONE); + assertEquals(1970, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals((i < 24 * 60 * 60) ? 1 : 2, test.getDayOfMonth()); + assertEquals((i / (60 * 60)) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); + assertEquals(123456789, test.getNano()); + assertEquals(OFFSET_PONE, test.getOffset()); } } @@ -288,12 +294,12 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); OffsetDateTime test = OffsetDateTime.now(clock); - assertEquals(test.getYear(), 1969); - assertEquals(test.getMonth(), Month.DECEMBER); - assertEquals(test.getDayOfMonth(), 31); + assertEquals(1969, test.getYear()); + assertEquals(Month.DECEMBER, test.getMonth()); + assertEquals(31, test.getDayOfMonth()); expected = expected.minusSeconds(1); - assertEquals(test.toLocalTime(), expected); - assertEquals(test.getOffset(), ZoneOffset.UTC); + assertEquals(expected, test.toLocalTime()); + assertEquals(ZoneOffset.UTC, test.getOffset()); } } @@ -304,37 +310,37 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { ZoneOffset offset = ZoneOffset.ofHours(i); Clock clock = Clock.fixed(base.toInstant(), offset); OffsetDateTime test = OffsetDateTime.now(clock); - assertEquals(test.getHour(), (12 + i) % 24); - assertEquals(test.getMinute(), 0); - assertEquals(test.getSecond(), 0); - assertEquals(test.getNano(), 0); - assertEquals(test.getOffset(), offset); + assertEquals((12 + i) % 24, test.getHour()); + assertEquals(0, test.getMinute()); + assertEquals(0, test.getSecond()); + assertEquals(0, test.getNano()); + assertEquals(offset, test.getOffset()); } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullZoneId() { - OffsetDateTime.now((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetDateTime.now((ZoneId) null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullClock() { - OffsetDateTime.now((Clock) null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetDateTime.now((Clock) null)); } //----------------------------------------------------------------------- private void check(OffsetDateTime test, int y, int mo, int d, int h, int m, int s, int n, ZoneOffset offset) { - assertEquals(test.getYear(), y); - assertEquals(test.getMonth().getValue(), mo); - assertEquals(test.getDayOfMonth(), d); - assertEquals(test.getHour(), h); - assertEquals(test.getMinute(), m); - assertEquals(test.getSecond(), s); - assertEquals(test.getNano(), n); - assertEquals(test.getOffset(), offset); + assertEquals(y, test.getYear()); + assertEquals(mo, test.getMonth().getValue()); + assertEquals(d, test.getDayOfMonth()); + assertEquals(h, test.getHour()); + assertEquals(m, test.getMinute()); + assertEquals(s, test.getSecond()); + assertEquals(n, test.getNano()); + assertEquals(offset, test.getOffset()); assertEquals(test, test); assertEquals(test.hashCode(), test.hashCode()); - assertEquals(OffsetDateTime.of(LocalDateTime.of(y, mo, d, h, m, s, n), offset), test); + assertEquals(test, OffsetDateTime.of(LocalDateTime.of(y, mo, d, h, m, s, n), offset)); } //----------------------------------------------------------------------- @@ -355,23 +361,29 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { check(test, 2008, 6, 30, 11, 30, 10, 500, OFFSET_PONE); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDateLocalTimeZoneOffset_nullLocalDate() { - LocalTime time = LocalTime.of(11, 30, 10, 500); - OffsetDateTime.of((LocalDate) null, time, OFFSET_PONE); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalTime time = LocalTime.of(11, 30, 10, 500); + OffsetDateTime.of((LocalDate) null, time, OFFSET_PONE); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDateLocalTimeZoneOffset_nullLocalTime() { - LocalDate date = LocalDate.of(2008, 6, 30); - OffsetDateTime.of(date, (LocalTime) null, OFFSET_PONE); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDate date = LocalDate.of(2008, 6, 30); + OffsetDateTime.of(date, (LocalTime) null, OFFSET_PONE); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDateLocalTimeZoneOffset_nullOffset() { - LocalDate date = LocalDate.of(2008, 6, 30); - LocalTime time = LocalTime.of(11, 30, 10, 500); - OffsetDateTime.of(date, time, (ZoneOffset) null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDate date = LocalDate.of(2008, 6, 30); + LocalTime time = LocalTime.of(11, 30, 10, 500); + OffsetDateTime.of(date, time, (ZoneOffset) null); + }); } //----------------------------------------------------------------------- @@ -382,15 +394,17 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { check(test, 2008, 6, 30, 11, 30, 10, 500, OFFSET_PONE); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDateTimeZoneOffset_nullProvider() { - OffsetDateTime.of((LocalDateTime) null, OFFSET_PONE); + Assertions.assertThrows(NullPointerException.class, () -> OffsetDateTime.of((LocalDateTime) null, OFFSET_PONE)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDateTimeZoneOffset_nullOffset() { - LocalDateTime dt = LocalDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 10, 500)); - OffsetDateTime.of(dt, (ZoneOffset) null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDateTime dt = LocalDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 10, 500)); + OffsetDateTime.of(dt, (ZoneOffset) null); + }); } //----------------------------------------------------------------------- @@ -398,50 +412,50 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_factory_CalendricalObject() { - assertEquals(OffsetDateTime.from( - OffsetDateTime.of(LocalDate.of(2007, 7, 15), LocalTime.of(17, 30), OFFSET_PONE)), - OffsetDateTime.of(LocalDate.of(2007, 7, 15), LocalTime.of(17, 30), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2007, 7, 15), LocalTime.of(17, 30), OFFSET_PONE), OffsetDateTime.from( + OffsetDateTime.of(LocalDate.of(2007, 7, 15), LocalTime.of(17, 30), OFFSET_PONE))); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_CalendricalObject_invalid_noDerive() { - OffsetDateTime.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> OffsetDateTime.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_Calendricals_null() { - OffsetDateTime.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetDateTime.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- // parse() //----------------------------------------------------------------------- - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_parse(int y, int month, int d, int h, int m, int s, int n, String offsetId, String text) { OffsetDateTime t = OffsetDateTime.parse(text); - assertEquals(t.getYear(), y); - assertEquals(t.getMonth().getValue(), month); - assertEquals(t.getDayOfMonth(), d); - assertEquals(t.getHour(), h); - assertEquals(t.getMinute(), m); - assertEquals(t.getSecond(), s); - assertEquals(t.getNano(), n); - assertEquals(t.getOffset().getId(), offsetId); + assertEquals(y, t.getYear()); + assertEquals(month, t.getMonth().getValue()); + assertEquals(d, t.getDayOfMonth()); + assertEquals(h, t.getHour()); + assertEquals(m, t.getMinute()); + assertEquals(s, t.getSecond()); + assertEquals(n, t.getNano()); + assertEquals(offsetId, t.getOffset().getId()); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_illegalValue() { - OffsetDateTime.parse("2008-06-32T11:15+01:00"); + Assertions.assertThrows(DateTimeParseException.class, () -> OffsetDateTime.parse("2008-06-32T11:15+01:00")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_invalidValue() { - OffsetDateTime.parse("2008-06-31T11:15+01:00"); + Assertions.assertThrows(DateTimeParseException.class, () -> OffsetDateTime.parse("2008-06-31T11:15+01:00")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_nullText() { - OffsetDateTime.parse((String) null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetDateTime.parse((String) null)); } //----------------------------------------------------------------------- @@ -451,35 +465,36 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void factory_parse_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s XXX"); OffsetDateTime test = OffsetDateTime.parse("2010 12 3 11 30 0 +01:00", f); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2010, 12, 3), LocalTime.of(11, 30), ZoneOffset.ofHours(1))); + assertEquals(OffsetDateTime.of(LocalDate.of(2010, 12, 3), LocalTime.of(11, 30), ZoneOffset.ofHours(1)), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullText() { - DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); - OffsetDateTime.parse((String) null, f); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); + OffsetDateTime.parse((String) null, f); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullFormatter() { - OffsetDateTime.parse("ANY", null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetDateTime.parse("ANY", null)); } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void constructor_nullTime() throws Throwable { - OffsetDateTime.of(null, OFFSET_PONE); + Assertions.assertThrows(NullPointerException.class, () -> OffsetDateTime.of(null, OFFSET_PONE)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void constructor_nullOffset() throws Throwable { - OffsetDateTime.of(LocalDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30)), null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetDateTime.of(LocalDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30)), null)); } //----------------------------------------------------------------------- // basics //----------------------------------------------------------------------- - @DataProvider(name="sampleTimes") Object[][] provider_sampleTimes() { return new Object[][] { {2008, 6, 30, 11, 30, 20, 500, OFFSET_PONE}, @@ -489,26 +504,27 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_get(int y, int o, int d, int h, int m, int s, int n, ZoneOffset offset) { LocalDate localDate = LocalDate.of(y, o, d); LocalTime localTime = LocalTime.of(h, m, s, n); LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime); OffsetDateTime a = OffsetDateTime.of(localDateTime, offset); - assertEquals(a.getYear(), localDate.getYear()); - assertEquals(a.getMonth(), localDate.getMonth()); - assertEquals(a.getDayOfMonth(), localDate.getDayOfMonth()); - assertEquals(a.getDayOfYear(), localDate.getDayOfYear()); - assertEquals(a.getDayOfWeek(), localDate.getDayOfWeek()); + assertEquals(localDate.getYear(), a.getYear()); + assertEquals(localDate.getMonth(), a.getMonth()); + assertEquals(localDate.getDayOfMonth(), a.getDayOfMonth()); + assertEquals(localDate.getDayOfYear(), a.getDayOfYear()); + assertEquals(localDate.getDayOfWeek(), a.getDayOfWeek()); - assertEquals(a.getHour(), localDateTime.getHour()); - assertEquals(a.getMinute(), localDateTime.getMinute()); - assertEquals(a.getSecond(), localDateTime.getSecond()); - assertEquals(a.getNano(), localDateTime.getNano()); + assertEquals(localDateTime.getHour(), a.getHour()); + assertEquals(localDateTime.getMinute(), a.getMinute()); + assertEquals(localDateTime.getSecond(), a.getSecond()); + assertEquals(localDateTime.getNano(), a.getNano()); - assertEquals(a.toOffsetTime(), OffsetTime.of(localTime, offset)); - assertEquals(a.toString(), localDateTime.toString() + offset.toString()); + assertEquals(OffsetTime.of(localTime, offset), a.toOffsetTime()); + assertEquals(localDateTime.toString() + offset.toString(), a.toString()); } //----------------------------------------------------------------------- @@ -516,37 +532,37 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported((TemporalField) null), false); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.NANO_OF_SECOND), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.NANO_OF_DAY), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MICRO_OF_SECOND), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MICRO_OF_DAY), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MILLI_OF_SECOND), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MILLI_OF_DAY), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.SECOND_OF_MINUTE), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.SECOND_OF_DAY), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MINUTE_OF_HOUR), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MINUTE_OF_DAY), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.HOUR_OF_AMPM), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.HOUR_OF_DAY), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.AMPM_OF_DAY), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.DAY_OF_WEEK), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.DAY_OF_MONTH), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.DAY_OF_YEAR), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.EPOCH_DAY), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MONTH_OF_YEAR), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.PROLEPTIC_MONTH), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.YEAR), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.YEAR_OF_ERA), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.ERA), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.INSTANT_SECONDS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.OFFSET_SECONDS), true); + assertEquals(false, TEST_2008_6_30_11_30_59_000000500.isSupported((TemporalField) null)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.YEAR)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.ERA)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -554,23 +570,23 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalUnit() { - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported((TemporalUnit) null), false); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.NANOS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MICROS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MILLIS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.SECONDS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MINUTES), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.HOURS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.HALF_DAYS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.DAYS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.WEEKS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MONTHS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.YEARS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.DECADES), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.CENTURIES), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MILLENNIA), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.ERAS), true); - assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.FOREVER), false); + assertEquals(false, TEST_2008_6_30_11_30_59_000000500.isSupported((TemporalUnit) null)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.NANOS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MICROS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MILLIS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.SECONDS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MINUTES)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.HOURS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.HALF_DAYS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.DAYS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.WEEKS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MONTHS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.YEARS)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.DECADES)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.CENTURIES)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MILLENNIA)); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.ERAS)); + assertEquals(false, TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.FOREVER)); } //----------------------------------------------------------------------- @@ -579,46 +595,45 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { @Test public void test_get_TemporalField() { OffsetDateTime test = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(12, 30, 40, 987654321), OFFSET_PONE); - assertEquals(test.get(ChronoField.YEAR), 2008); - assertEquals(test.get(ChronoField.MONTH_OF_YEAR), 6); - assertEquals(test.get(ChronoField.DAY_OF_MONTH), 30); - assertEquals(test.get(ChronoField.DAY_OF_WEEK), 1); - assertEquals(test.get(ChronoField.DAY_OF_YEAR), 182); + assertEquals(2008, test.get(ChronoField.YEAR)); + assertEquals(6, test.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(30, test.get(ChronoField.DAY_OF_MONTH)); + assertEquals(1, test.get(ChronoField.DAY_OF_WEEK)); + assertEquals(182, test.get(ChronoField.DAY_OF_YEAR)); - assertEquals(test.get(ChronoField.HOUR_OF_DAY), 12); - assertEquals(test.get(ChronoField.MINUTE_OF_HOUR), 30); - assertEquals(test.get(ChronoField.SECOND_OF_MINUTE), 40); - assertEquals(test.get(ChronoField.NANO_OF_SECOND), 987654321); - assertEquals(test.get(ChronoField.HOUR_OF_AMPM), 0); - assertEquals(test.get(ChronoField.AMPM_OF_DAY), 1); + assertEquals(12, test.get(ChronoField.HOUR_OF_DAY)); + assertEquals(30, test.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(40, test.get(ChronoField.SECOND_OF_MINUTE)); + assertEquals(987654321, test.get(ChronoField.NANO_OF_SECOND)); + assertEquals(0, test.get(ChronoField.HOUR_OF_AMPM)); + assertEquals(1, test.get(ChronoField.AMPM_OF_DAY)); - assertEquals(test.get(ChronoField.OFFSET_SECONDS), 3600); + assertEquals(3600, test.get(ChronoField.OFFSET_SECONDS)); } @Test public void test_getLong_TemporalField() { OffsetDateTime test = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(12, 30, 40, 987654321), OFFSET_PONE); - assertEquals(test.getLong(ChronoField.YEAR), 2008); - assertEquals(test.getLong(ChronoField.MONTH_OF_YEAR), 6); - assertEquals(test.getLong(ChronoField.DAY_OF_MONTH), 30); - assertEquals(test.getLong(ChronoField.DAY_OF_WEEK), 1); - assertEquals(test.getLong(ChronoField.DAY_OF_YEAR), 182); + assertEquals(2008, test.getLong(ChronoField.YEAR)); + assertEquals(6, test.getLong(ChronoField.MONTH_OF_YEAR)); + assertEquals(30, test.getLong(ChronoField.DAY_OF_MONTH)); + assertEquals(1, test.getLong(ChronoField.DAY_OF_WEEK)); + assertEquals(182, test.getLong(ChronoField.DAY_OF_YEAR)); - assertEquals(test.getLong(ChronoField.HOUR_OF_DAY), 12); - assertEquals(test.getLong(ChronoField.MINUTE_OF_HOUR), 30); - assertEquals(test.getLong(ChronoField.SECOND_OF_MINUTE), 40); - assertEquals(test.getLong(ChronoField.NANO_OF_SECOND), 987654321); - assertEquals(test.getLong(ChronoField.HOUR_OF_AMPM), 0); - assertEquals(test.getLong(ChronoField.AMPM_OF_DAY), 1); + assertEquals(12, test.getLong(ChronoField.HOUR_OF_DAY)); + assertEquals(30, test.getLong(ChronoField.MINUTE_OF_HOUR)); + assertEquals(40, test.getLong(ChronoField.SECOND_OF_MINUTE)); + assertEquals(987654321, test.getLong(ChronoField.NANO_OF_SECOND)); + assertEquals(0, test.getLong(ChronoField.HOUR_OF_AMPM)); + assertEquals(1, test.getLong(ChronoField.AMPM_OF_DAY)); - assertEquals(test.getLong(ChronoField.INSTANT_SECONDS), test.toEpochSecond()); - assertEquals(test.getLong(ChronoField.OFFSET_SECONDS), 3600); + assertEquals(test.toEpochSecond(), test.getLong(ChronoField.INSTANT_SECONDS)); + assertEquals(3600, test.getLong(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {TEST_2008_6_30_11_30_59_000000500, TemporalQueries.chronology(), IsoChronology.INSTANCE}, @@ -631,25 +646,26 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - TEST_2008_6_30_11_30_59_000000500.query(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_6_30_11_30_59_000000500.query(null)); } //----------------------------------------------------------------------- // adjustInto(Temporal) //----------------------------------------------------------------------- - @DataProvider(name="adjustInto") Object[][] data_adjustInto() { return new Object[][]{ {OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), OffsetDateTime.of(2012, 3, 4, 1, 1, 1, 100, ZoneOffset.UTC), OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), null}, @@ -671,11 +687,12 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="adjustInto") + @ParameterizedTest + @MethodSource("data_adjustInto") public void test_adjustInto(OffsetDateTime test, Temporal temporal, Temporal expected, Class expectedEx) { if (expectedEx == null) { Temporal result = test.adjustInto(temporal); - assertEquals(result, expected); + assertEquals(expected, result); } else { try { Temporal result = test.adjustInto(temporal); @@ -698,60 +715,62 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { return sample; } }; - assertEquals(TEST_2008_6_30_11_30_59_000000500.with(adjuster), sample); + assertEquals(sample, TEST_2008_6_30_11_30_59_000000500.with(adjuster)); } @Test public void test_with_adjustment_LocalDate() { OffsetDateTime test = TEST_2008_6_30_11_30_59_000000500.with(LocalDate.of(2012, 9, 3)); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2012, 9, 3), LocalTime.of(11, 30, 59, 500), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2012, 9, 3), LocalTime.of(11, 30, 59, 500), OFFSET_PONE), test); } @Test public void test_with_adjustment_LocalTime() { OffsetDateTime test = TEST_2008_6_30_11_30_59_000000500.with(LocalTime.of(19, 15)); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(19, 15), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(19, 15), OFFSET_PONE), test); } @Test public void test_with_adjustment_LocalDateTime() { OffsetDateTime test = TEST_2008_6_30_11_30_59_000000500.with(LocalDateTime.of(LocalDate.of(2012, 9, 3), LocalTime.of(19, 15))); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2012, 9, 3), LocalTime.of(19, 15), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2012, 9, 3), LocalTime.of(19, 15), OFFSET_PONE), test); } @Test public void test_with_adjustment_OffsetTime() { OffsetDateTime test = TEST_2008_6_30_11_30_59_000000500.with(OffsetTime.of(LocalTime.of(19, 15), OFFSET_PTWO)); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(19, 15), OFFSET_PTWO)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(19, 15), OFFSET_PTWO), test); } @Test public void test_with_adjustment_OffsetDateTime() { OffsetDateTime test = TEST_2008_6_30_11_30_59_000000500.with(OffsetDateTime.of(LocalDate.of(2012, 9, 3), LocalTime.of(19, 15), OFFSET_PTWO)); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2012, 9, 3), LocalTime.of(19, 15), OFFSET_PTWO)); + assertEquals(OffsetDateTime.of(LocalDate.of(2012, 9, 3), LocalTime.of(19, 15), OFFSET_PTWO), test); } @Test public void test_with_adjustment_Month() { OffsetDateTime test = TEST_2008_6_30_11_30_59_000000500.with(DECEMBER); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2008, 12, 30),LocalTime.of(11, 30, 59, 500), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 12, 30),LocalTime.of(11, 30, 59, 500), OFFSET_PONE), test); } @Test public void test_with_adjustment_ZoneOffset() { OffsetDateTime test = TEST_2008_6_30_11_30_59_000000500.with(OFFSET_PTWO); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59, 500), OFFSET_PTWO)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59, 500), OFFSET_PTWO), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_with_adjustment_null() { - TEST_2008_6_30_11_30_59_000000500.with((TemporalAdjuster) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_6_30_11_30_59_000000500.with((TemporalAdjuster) null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_withOffsetSameLocal_null() { - OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); - base.withOffsetSameLocal(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); + base.withOffsetSameLocal(null); + }); } //----------------------------------------------------------------------- @@ -762,19 +781,20 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); OffsetDateTime test = base.withOffsetSameInstant(OFFSET_PTWO); OffsetDateTime expected = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(12, 30, 59), OFFSET_PTWO); - assertEquals(test, expected); + assertEquals(expected, test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_withOffsetSameInstant_null() { - OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); - base.withOffsetSameInstant(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); + base.withOffsetSameInstant(null); + }); } //----------------------------------------------------------------------- // with(long,TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name = "withFieldLong") Object[][] data_withFieldLong() { return new Object[][] { {TEST_2008_6_30_11_30_59_000000500, YEAR, 2009, @@ -790,9 +810,10 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { }; }; - @Test(dataProvider = "withFieldLong") + @ParameterizedTest + @MethodSource("data_withFieldLong") public void test_with_fieldLong(OffsetDateTime base, TemporalField setField, long setValue, OffsetDateTime expected) { - assertEquals(base.with(setField, setValue), expected); + assertEquals(expected, base.with(setField, setValue)); } //----------------------------------------------------------------------- @@ -802,7 +823,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_withYear_normal() { OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); OffsetDateTime test = base.withYear(2007); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2007, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2007, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -812,7 +833,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_withMonth_normal() { OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); OffsetDateTime test = base.withMonth(1); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2008, 1, 30), LocalTime.of(11, 30, 59), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 1, 30), LocalTime.of(11, 30, 59), OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -822,7 +843,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_withDayOfMonth_normal() { OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); OffsetDateTime test = base.withDayOfMonth(15); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2008, 6, 15), LocalTime.of(11, 30, 59), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 6, 15), LocalTime.of(11, 30, 59), OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -831,17 +852,17 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { @Test public void test_withDayOfYear_normal() { OffsetDateTime t = TEST_2008_6_30_11_30_59_000000500.withDayOfYear(33); - assertEquals(t, OffsetDateTime.of(LocalDate.of(2008, 2, 2), LocalTime.of(11, 30, 59, 500), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 2, 2), LocalTime.of(11, 30, 59, 500), OFFSET_PONE), t); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfYear_illegal() { - TEST_2008_6_30_11_30_59_000000500.withDayOfYear(367); + Assertions.assertThrows(DateTimeException.class, () -> TEST_2008_6_30_11_30_59_000000500.withDayOfYear(367)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfYear_invalid() { - OffsetDateTime.of(LocalDate.of(2007, 2, 2), LocalTime.of(11, 30), OFFSET_PONE).withDayOfYear(366); + Assertions.assertThrows(DateTimeException.class, () -> OffsetDateTime.of(LocalDate.of(2007, 2, 2), LocalTime.of(11, 30), OFFSET_PONE).withDayOfYear(366)); } //----------------------------------------------------------------------- @@ -851,7 +872,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_withHour_normal() { OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); OffsetDateTime test = base.withHour(15); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(15, 30, 59), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(15, 30, 59), OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -861,7 +882,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_withMinute_normal() { OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); OffsetDateTime test = base.withMinute(15); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 15, 59), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 15, 59), OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -871,7 +892,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_withSecond_normal() { OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); OffsetDateTime test = base.withSecond(15); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 15), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 15), OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -881,7 +902,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_withNanoOfSecond_normal() { OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59, 1), OFFSET_PONE); OffsetDateTime test = base.withNano(15); - assertEquals(test, OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59, 15), OFFSET_PONE)); + assertEquals(OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59, 15), OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -889,14 +910,14 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_truncatedTo_normal() { - assertEquals(TEST_2008_6_30_11_30_59_000000500.truncatedTo(NANOS), TEST_2008_6_30_11_30_59_000000500); - assertEquals(TEST_2008_6_30_11_30_59_000000500.truncatedTo(SECONDS), TEST_2008_6_30_11_30_59_000000500.withNano(0)); - assertEquals(TEST_2008_6_30_11_30_59_000000500.truncatedTo(DAYS), TEST_2008_6_30_11_30_59_000000500.with(LocalTime.MIDNIGHT)); + assertEquals(TEST_2008_6_30_11_30_59_000000500, TEST_2008_6_30_11_30_59_000000500.truncatedTo(NANOS)); + assertEquals(TEST_2008_6_30_11_30_59_000000500.withNano(0), TEST_2008_6_30_11_30_59_000000500.truncatedTo(SECONDS)); + assertEquals(TEST_2008_6_30_11_30_59_000000500.with(LocalTime.MIDNIGHT), TEST_2008_6_30_11_30_59_000000500.truncatedTo(DAYS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_truncatedTo_null() { - TEST_2008_6_30_11_30_59_000000500.truncatedTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_6_30_11_30_59_000000500.truncatedTo(null)); } //----------------------------------------------------------------------- @@ -906,7 +927,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_plus_Period() { MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.MONTHS); OffsetDateTime t = TEST_2008_6_30_11_30_59_000000500.plus(period); - assertEquals(t, OffsetDateTime.of(2009, 1, 30, 11, 30, 59, 500, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2009, 1, 30, 11, 30, 59, 500, OFFSET_PONE), t); } //----------------------------------------------------------------------- @@ -916,18 +937,18 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_plus_Duration() { Duration dur = Duration.ofSeconds(62, 3); OffsetDateTime t = TEST_2008_6_30_11_30_59_000000500.plus(dur); - assertEquals(t, OffsetDateTime.of(2008, 6, 30, 11, 32, 1, 503, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 30, 11, 32, 1, 503, OFFSET_PONE), t); } @Test public void test_plus_Duration_zero() { OffsetDateTime t = TEST_2008_6_30_11_30_59_000000500.plus(Duration.ZERO); - assertEquals(t, TEST_2008_6_30_11_30_59_000000500); + assertEquals(TEST_2008_6_30_11_30_59_000000500, t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_Duration_null() { - TEST_2008_6_30_11_30_59_000000500.plus((Duration) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_6_30_11_30_59_000000500.plus((Duration) null)); } //----------------------------------------------------------------------- @@ -937,7 +958,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_plusYears() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.plusYears(1); - assertEquals(test, OffsetDateTime.of(2009, 6, 30, 11, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2009, 6, 30, 11, 30, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -947,7 +968,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_plusMonths() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.plusMonths(1); - assertEquals(test, OffsetDateTime.of(2008, 7, 30, 11, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 7, 30, 11, 30, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -957,7 +978,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_plusWeeks() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.plusWeeks(1); - assertEquals(test, OffsetDateTime.of(2008, 7, 7, 11, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 7, 7, 11, 30, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -967,7 +988,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_plusDays() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.plusDays(1); - assertEquals(test, OffsetDateTime.of(2008, 7, 1, 11, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 7, 1, 11, 30, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -977,7 +998,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_plusHours() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.plusHours(13); - assertEquals(test, OffsetDateTime.of(2008, 7, 1, 0, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 7, 1, 0, 30, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -987,7 +1008,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_plusMinutes() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.plusMinutes(30); - assertEquals(test, OffsetDateTime.of(2008, 6, 30, 12, 0, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 30, 12, 0, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -997,7 +1018,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_plusSeconds() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.plusSeconds(1); - assertEquals(test, OffsetDateTime.of(2008, 6, 30, 11, 31, 0, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 30, 11, 31, 0, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -1007,7 +1028,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_plusNanos() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.plusNanos(1); - assertEquals(test, OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 1, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 1, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -1017,7 +1038,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_minus_Period() { MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.MONTHS); OffsetDateTime t = TEST_2008_6_30_11_30_59_000000500.minus(period); - assertEquals(t, OffsetDateTime.of(2007, 11, 30, 11, 30, 59, 500, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2007, 11, 30, 11, 30, 59, 500, OFFSET_PONE), t); } //----------------------------------------------------------------------- @@ -1027,18 +1048,18 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_minus_Duration() { Duration dur = Duration.ofSeconds(62, 3); OffsetDateTime t = TEST_2008_6_30_11_30_59_000000500.minus(dur); - assertEquals(t, OffsetDateTime.of(2008, 6, 30, 11, 29, 57, 497, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 30, 11, 29, 57, 497, OFFSET_PONE), t); } @Test public void test_minus_Duration_zero() { OffsetDateTime t = TEST_2008_6_30_11_30_59_000000500.minus(Duration.ZERO); - assertEquals(t, TEST_2008_6_30_11_30_59_000000500); + assertEquals(TEST_2008_6_30_11_30_59_000000500, t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_minus_Duration_null() { - TEST_2008_6_30_11_30_59_000000500.minus((Duration) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_6_30_11_30_59_000000500.minus((Duration) null)); } //----------------------------------------------------------------------- @@ -1048,7 +1069,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_minusYears() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.minusYears(1); - assertEquals(test, OffsetDateTime.of(2007, 6, 30, 11, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2007, 6, 30, 11, 30, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -1058,7 +1079,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_minusMonths() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.minusMonths(1); - assertEquals(test, OffsetDateTime.of(2008, 5, 30, 11, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 5, 30, 11, 30, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -1068,7 +1089,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_minusWeeks() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.minusWeeks(1); - assertEquals(test, OffsetDateTime.of(2008, 6, 23, 11, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 23, 11, 30, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -1078,7 +1099,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_minusDays() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.minusDays(1); - assertEquals(test, OffsetDateTime.of(2008, 6, 29, 11, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 29, 11, 30, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -1088,7 +1109,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_minusHours() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.minusHours(13); - assertEquals(test, OffsetDateTime.of(2008, 6, 29, 22, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 29, 22, 30, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -1098,7 +1119,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_minusMinutes() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.minusMinutes(30); - assertEquals(test, OffsetDateTime.of(2008, 6, 30, 11, 0, 59, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 30, 11, 0, 59, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -1108,7 +1129,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_minusSeconds() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.minusSeconds(1); - assertEquals(test, OffsetDateTime.of(2008, 6, 30, 11, 30, 58, 0, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 30, 11, 30, 58, 0, OFFSET_PONE), test); } //----------------------------------------------------------------------- @@ -1118,13 +1139,12 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_minusNanos() { OffsetDateTime base = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); OffsetDateTime test = base.minusNanos(1); - assertEquals(test, OffsetDateTime.of(2008, 6, 30, 11, 30, 58, 999999999, OFFSET_PONE)); + assertEquals(OffsetDateTime.of(2008, 6, 30, 11, 30, 58, 999999999, OFFSET_PONE), test); } //----------------------------------------------------------------------- // until(Temporal, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="periodUntilUnit") Object[][] data_untilUnit() { return new Object[][] { {OffsetDateTime.of(2010, 6, 30, 1, 1, 1, 0, OFFSET_PONE), OffsetDateTime.of(2010, 6, 30, 13, 1, 1, 0, OFFSET_PONE), HALF_DAYS, 1}, @@ -1151,42 +1171,49 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_untilUnit") public void test_until_TemporalUnit(OffsetDateTime odt1, OffsetDateTime odt2, TemporalUnit unit, long expected) { long amount = odt1.until(odt2, unit); - assertEquals(amount, expected); + assertEquals(expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_untilUnit") public void test_until_TemporalUnit_negated(OffsetDateTime odt1, OffsetDateTime odt2, TemporalUnit unit, long expected) { long amount = odt2.until(odt1, unit); - assertEquals(amount, -expected); + assertEquals(-expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_untilUnit") public void test_until_TemporalUnit_between(OffsetDateTime odt1, OffsetDateTime odt2, TemporalUnit unit, long expected) { long amount = unit.between(odt1, odt2); - assertEquals(amount, expected); + assertEquals(expected, amount); } @Test public void test_until_convertedType() { OffsetDateTime odt = OffsetDateTime.of(2010, 6, 30, 1, 1, 1, 0, OFFSET_PONE); ZonedDateTime zdt = odt.plusSeconds(3).toZonedDateTime(); - assertEquals(odt.until(zdt, SECONDS), 3); + assertEquals(3, odt.until(zdt, SECONDS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_invalidType() { - OffsetDateTime odt = OffsetDateTime.of(2010, 6, 30, 1, 1, 1, 0, OFFSET_PONE); - odt.until(Instant.ofEpochSecond(12), SECONDS); + Assertions.assertThrows(DateTimeException.class, () -> { + OffsetDateTime odt = OffsetDateTime.of(2010, 6, 30, 1, 1, 1, 0, OFFSET_PONE); + odt.until(Instant.ofEpochSecond(12), SECONDS); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_invalidTemporalUnit() { - OffsetDateTime odt1 = OffsetDateTime.of(2010, 6, 30, 1, 1, 1, 0, OFFSET_PONE); - OffsetDateTime odt2 = OffsetDateTime.of(2010, 6, 30, 2, 1, 1, 0, OFFSET_PONE); - odt1.until(odt2, FOREVER); + Assertions.assertThrows(DateTimeException.class, () -> { + OffsetDateTime odt1 = OffsetDateTime.of(2010, 6, 30, 1, 1, 1, 0, OFFSET_PONE); + OffsetDateTime odt2 = OffsetDateTime.of(2010, 6, 30, 2, 1, 1, 0, OFFSET_PONE); + odt1.until(odt2, FOREVER); + }); } //----------------------------------------------------------------------- @@ -1196,12 +1223,12 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_format_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); String t = OffsetDateTime.of(2010, 12, 3, 11, 30, 0, 0, OFFSET_PONE).format(f); - assertEquals(t, "2010 12 3 11 30 0"); + assertEquals("2010 12 3 11 30 0", t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_format_formatter_null() { - OffsetDateTime.of(2010, 12, 3, 11, 30, 0, 0, OFFSET_PONE).format(null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetDateTime.of(2010, 12, 3, 11, 30, 0, 0, OFFSET_PONE).format(null)); } //----------------------------------------------------------------------- @@ -1210,14 +1237,15 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { @Test public void test_atZone() { OffsetDateTime t = OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_MTWO); - assertEquals(t.atZoneSameInstant(ZONE_PARIS), - ZonedDateTime.of(2008, 6, 30, 15, 30, 0, 0, ZONE_PARIS)); + assertEquals(ZonedDateTime.of(2008, 6, 30, 15, 30, 0, 0, ZONE_PARIS), t.atZoneSameInstant(ZONE_PARIS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atZone_nullTimeZone() { - OffsetDateTime t = OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_PTWO); - t.atZoneSameInstant((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetDateTime t = OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_PTWO); + t.atZoneSameInstant((ZoneId) null); + }); } //----------------------------------------------------------------------- @@ -1226,37 +1254,37 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { @Test public void test_atZoneSimilarLocal() { OffsetDateTime t = OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_MTWO); - assertEquals(t.atZoneSimilarLocal(ZONE_PARIS), - ZonedDateTime.of(2008, 6, 30, 11, 30, 0, 0, ZONE_PARIS)); + assertEquals(ZonedDateTime.of(2008, 6, 30, 11, 30, 0, 0, ZONE_PARIS), t.atZoneSimilarLocal(ZONE_PARIS)); } @Test public void test_atZoneSimilarLocal_dstGap() { OffsetDateTime t = OffsetDateTime.of(2007, 4, 1, 0, 0, 0, 0, OFFSET_MTWO); - assertEquals(t.atZoneSimilarLocal(ZONE_GAZA), - ZonedDateTime.of(2007, 4, 1, 1, 0, 0, 0, ZONE_GAZA)); + assertEquals(ZonedDateTime.of(2007, 4, 1, 1, 0, 0, 0, ZONE_GAZA), t.atZoneSimilarLocal(ZONE_GAZA)); } @Test public void test_atZone_dstOverlapSummer() { OffsetDateTime t = OffsetDateTime.of(2007, 10, 28, 2, 30, 0, 0, OFFSET_PTWO); - assertEquals(t.atZoneSimilarLocal(ZONE_PARIS).toLocalDateTime(), t.toLocalDateTime()); - assertEquals(t.atZoneSimilarLocal(ZONE_PARIS).getOffset(), OFFSET_PTWO); - assertEquals(t.atZoneSimilarLocal(ZONE_PARIS).getZone(), ZONE_PARIS); + assertEquals(t.toLocalDateTime(), t.atZoneSimilarLocal(ZONE_PARIS).toLocalDateTime()); + assertEquals(OFFSET_PTWO, t.atZoneSimilarLocal(ZONE_PARIS).getOffset()); + assertEquals(ZONE_PARIS, t.atZoneSimilarLocal(ZONE_PARIS).getZone()); } @Test public void test_atZone_dstOverlapWinter() { OffsetDateTime t = OffsetDateTime.of(2007, 10, 28, 2, 30, 0, 0, OFFSET_PONE); - assertEquals(t.atZoneSimilarLocal(ZONE_PARIS).toLocalDateTime(), t.toLocalDateTime()); - assertEquals(t.atZoneSimilarLocal(ZONE_PARIS).getOffset(), OFFSET_PONE); - assertEquals(t.atZoneSimilarLocal(ZONE_PARIS).getZone(), ZONE_PARIS); + assertEquals(t.toLocalDateTime(), t.atZoneSimilarLocal(ZONE_PARIS).toLocalDateTime()); + assertEquals(OFFSET_PONE, t.atZoneSimilarLocal(ZONE_PARIS).getOffset()); + assertEquals(ZONE_PARIS, t.atZoneSimilarLocal(ZONE_PARIS).getZone()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atZoneSimilarLocal_nullTimeZone() { - OffsetDateTime t = OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_PTWO); - t.atZoneSimilarLocal((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetDateTime t = OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_PTWO); + t.atZoneSimilarLocal((ZoneId) null); + }); } //----------------------------------------------------------------------- @@ -1266,7 +1294,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_toEpochSecond_afterEpoch() { for (int i = 0; i < 100000; i++) { OffsetDateTime a = OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).plusSeconds(i); - assertEquals(a.toEpochSecond(), i); + assertEquals(i, a.toEpochSecond()); } } @@ -1274,7 +1302,7 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_toEpochSecond_beforeEpoch() { for (int i = 0; i < 100000; i++) { OffsetDateTime a = OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).minusSeconds(i); - assertEquals(a.toEpochSecond(), -i); + assertEquals(-i, a.toEpochSecond()); } } @@ -1285,136 +1313,140 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_compareTo_timeMins() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 29, 3, 0, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 11, 30, 2, 0, OFFSET_PONE); // a is before b due to time - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(a.toInstant().compareTo(b.toInstant()) < 0, true); - assertEquals(OffsetDateTime.timeLineOrder().compare(a, b) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, a.toInstant().compareTo(b.toInstant()) < 0); + assertEquals(true, OffsetDateTime.timeLineOrder().compare(a, b) < 0); } @Test public void test_compareTo_timeSecs() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 29, 2, 0, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 11, 29, 3, 0, OFFSET_PONE); // a is before b due to time - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(a.toInstant().compareTo(b.toInstant()) < 0, true); - assertEquals(OffsetDateTime.timeLineOrder().compare(a, b) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, a.toInstant().compareTo(b.toInstant()) < 0); + assertEquals(true, OffsetDateTime.timeLineOrder().compare(a, b) < 0); } @Test public void test_compareTo_timeNanos() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 29, 40, 4, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 11, 29, 40, 5, OFFSET_PONE); // a is before b due to time - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(a.toInstant().compareTo(b.toInstant()) < 0, true); - assertEquals(OffsetDateTime.timeLineOrder().compare(a, b) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, a.toInstant().compareTo(b.toInstant()) < 0); + assertEquals(true, OffsetDateTime.timeLineOrder().compare(a, b) < 0); } @Test public void test_compareTo_offset() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_PTWO); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_PONE); // a is before b due to offset - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(a.toInstant().compareTo(b.toInstant()) < 0, true); - assertEquals(OffsetDateTime.timeLineOrder().compare(a, b) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, a.toInstant().compareTo(b.toInstant()) < 0); + assertEquals(true, OffsetDateTime.timeLineOrder().compare(a, b) < 0); } @Test public void test_compareTo_offsetNanos() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 40, 6, OFFSET_PTWO); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 11, 30, 40, 5, OFFSET_PONE); // a is before b due to offset - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(a.toInstant().compareTo(b.toInstant()) < 0, true); - assertEquals(OffsetDateTime.timeLineOrder().compare(a, b) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, a.toInstant().compareTo(b.toInstant()) < 0); + assertEquals(true, OffsetDateTime.timeLineOrder().compare(a, b) < 0); } @Test public void test_compareTo_both() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 50, 0, 0, OFFSET_PTWO); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 11, 20, 0, 0, OFFSET_PONE); // a is before b on instant scale - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(a.toInstant().compareTo(b.toInstant()) < 0, true); - assertEquals(OffsetDateTime.timeLineOrder().compare(a, b) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, a.toInstant().compareTo(b.toInstant()) < 0); + assertEquals(true, OffsetDateTime.timeLineOrder().compare(a, b) < 0); } @Test public void test_compareTo_bothNanos() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 20, 40, 4, OFFSET_PTWO); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 10, 20, 40, 5, OFFSET_PONE); // a is before b on instant scale - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(a.toInstant().compareTo(b.toInstant()) < 0, true); - assertEquals(OffsetDateTime.timeLineOrder().compare(a, b) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, a.toInstant().compareTo(b.toInstant()) < 0); + assertEquals(true, OffsetDateTime.timeLineOrder().compare(a, b) < 0); } @Test public void test_compareTo_bothInstantComparator() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 20, 40, 4, OFFSET_PTWO); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 10, 20, 40, 5, OFFSET_PONE); - assertEquals(a.compareTo(b), OffsetDateTime.timeLineOrder().compare(a,b), "for nano != nano, compareTo and timeLineOrder() should be the same"); + assertEquals(OffsetDateTime.timeLineOrder().compare(a,b), a.compareTo(b), "for nano != nano, compareTo and timeLineOrder() should be the same"); } @Test public void test_compareTo_hourDifference() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 10, 0, 0, 0, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 11, 0, 0, 0, OFFSET_PTWO); // a is before b despite being same time-line time - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(a.toInstant().compareTo(b.toInstant()) == 0, true); - assertEquals(OffsetDateTime.timeLineOrder().compare(a,b) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, a.toInstant().compareTo(b.toInstant()) == 0); + assertEquals(true, OffsetDateTime.timeLineOrder().compare(a,b) == 0); } @Test public void test_compareTo_max() { OffsetDateTime a = OffsetDateTime.of(Year.MAX_VALUE, 12, 31, 23, 59, 0, 0, OFFSET_MONE); OffsetDateTime b = OffsetDateTime.of(Year.MAX_VALUE, 12, 31, 23, 59, 0, 0, OFFSET_MTWO); // a is before b due to offset - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); } @Test public void test_compareTo_min() { OffsetDateTime a = OffsetDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0, 0, 0, OFFSET_PTWO); OffsetDateTime b = OffsetDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0, 0, 0, OFFSET_PONE); // a is before b due to offset - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_null() { - OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); - a.compareTo(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); + a.compareTo(null); + }); } - @Test(expectedExceptions=ClassCastException.class) @SuppressWarnings({"unchecked", "rawtypes"}) + @Test public void compareToNonOffsetDateTime() { - Comparable c = TEST_2008_6_30_11_30_59_000000500; - c.compareTo(new Object()); + Assertions.assertThrows(ClassCastException.class, () -> { + Comparable c = TEST_2008_6_30_11_30_59_000000500; + c.compareTo(new Object()); + }); } //----------------------------------------------------------------------- @@ -1424,156 +1456,168 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { public void test_isBeforeIsAfterIsEqual1() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 58, 3, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 2, OFFSET_PONE); // a is before b due to time - assertEquals(a.isBefore(b), true); - assertEquals(a.isEqual(b), false); - assertEquals(a.isAfter(b), false); + assertEquals(true, a.isBefore(b)); + assertEquals(false, a.isEqual(b)); + assertEquals(false, a.isAfter(b)); - assertEquals(b.isBefore(a), false); - assertEquals(b.isEqual(a), false); - assertEquals(b.isAfter(a), true); + assertEquals(false, b.isBefore(a)); + assertEquals(false, b.isEqual(a)); + assertEquals(true, b.isAfter(a)); - assertEquals(a.isBefore(a), false); - assertEquals(b.isBefore(b), false); + assertEquals(false, a.isBefore(a)); + assertEquals(false, b.isBefore(b)); - assertEquals(a.isEqual(a), true); - assertEquals(b.isEqual(b), true); + assertEquals(true, a.isEqual(a)); + assertEquals(true, b.isEqual(b)); - assertEquals(a.isAfter(a), false); - assertEquals(b.isAfter(b), false); + assertEquals(false, a.isAfter(a)); + assertEquals(false, b.isAfter(b)); } @Test public void test_isBeforeIsAfterIsEqual2() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 2, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 3, OFFSET_PONE); // a is before b due to time - assertEquals(a.isBefore(b), true); - assertEquals(a.isEqual(b), false); - assertEquals(a.isAfter(b), false); + assertEquals(true, a.isBefore(b)); + assertEquals(false, a.isEqual(b)); + assertEquals(false, a.isAfter(b)); - assertEquals(b.isBefore(a), false); - assertEquals(b.isEqual(a), false); - assertEquals(b.isAfter(a), true); + assertEquals(false, b.isBefore(a)); + assertEquals(false, b.isEqual(a)); + assertEquals(true, b.isAfter(a)); - assertEquals(a.isBefore(a), false); - assertEquals(b.isBefore(b), false); + assertEquals(false, a.isBefore(a)); + assertEquals(false, b.isBefore(b)); - assertEquals(a.isEqual(a), true); - assertEquals(b.isEqual(b), true); + assertEquals(true, a.isEqual(a)); + assertEquals(true, b.isEqual(b)); - assertEquals(a.isAfter(a), false); - assertEquals(b.isAfter(b), false); + assertEquals(false, a.isAfter(a)); + assertEquals(false, b.isAfter(b)); } @Test public void test_isBeforeIsAfterIsEqual_instantComparison() { OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 10, 0, 0, 0, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 11, 0, 0, 0, OFFSET_PTWO); // a is same instant as b - assertEquals(a.isBefore(b), false); - assertEquals(a.isEqual(b), true); - assertEquals(a.isAfter(b), false); + assertEquals(false, a.isBefore(b)); + assertEquals(true, a.isEqual(b)); + assertEquals(false, a.isAfter(b)); - assertEquals(b.isBefore(a), false); - assertEquals(b.isEqual(a), true); - assertEquals(b.isAfter(a), false); + assertEquals(false, b.isBefore(a)); + assertEquals(true, b.isEqual(a)); + assertEquals(false, b.isAfter(a)); - assertEquals(a.isBefore(a), false); - assertEquals(b.isBefore(b), false); + assertEquals(false, a.isBefore(a)); + assertEquals(false, b.isBefore(b)); - assertEquals(a.isEqual(a), true); - assertEquals(b.isEqual(b), true); + assertEquals(true, a.isEqual(a)); + assertEquals(true, b.isEqual(b)); - assertEquals(a.isAfter(a), false); - assertEquals(b.isAfter(b), false); + assertEquals(false, a.isAfter(a)); + assertEquals(false, b.isAfter(b)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isBefore_null() { - OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); - a.isBefore(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); + a.isBefore(null); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isEqual_null() { - OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); - a.isEqual(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); + a.isEqual(null); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isAfter_null() { - OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); - a.isAfter(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 0, OFFSET_PONE); + a.isAfter(null); + }); } //----------------------------------------------------------------------- // equals() / hashCode() //----------------------------------------------------------------------- - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_true(int y, int o, int d, int h, int m, int s, int n, ZoneOffset ignored) { OffsetDateTime a = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PONE); - assertEquals(a.equals(b), true); - assertEquals(a.hashCode() == b.hashCode(), true); + assertEquals(true, a.equals(b)); + assertEquals(true, a.hashCode() == b.hashCode()); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_year_differs(int y, int o, int d, int h, int m, int s, int n, ZoneOffset ignored) { OffsetDateTime a = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(y + 1, o, d, h, m, s, n, OFFSET_PONE); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_hour_differs(int y, int o, int d, int h, int m, int s, int n, ZoneOffset ignored) { h = (h == 23 ? 22 : h); OffsetDateTime a = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(y, o, d, h + 1, m, s, n, OFFSET_PONE); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_minute_differs(int y, int o, int d, int h, int m, int s, int n, ZoneOffset ignored) { m = (m == 59 ? 58 : m); OffsetDateTime a = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(y, o, d, h, m + 1, s, n, OFFSET_PONE); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_second_differs(int y, int o, int d, int h, int m, int s, int n, ZoneOffset ignored) { s = (s == 59 ? 58 : s); OffsetDateTime a = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(y, o, d, h, m, s + 1, n, OFFSET_PONE); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_nano_differs(int y, int o, int d, int h, int m, int s, int n, ZoneOffset ignored) { n = (n == 999999999 ? 999999998 : n); OffsetDateTime a = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(y, o, d, h, m, s, n + 1, OFFSET_PONE); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_offset_differs(int y, int o, int d, int h, int m, int s, int n, ZoneOffset ignored) { OffsetDateTime a = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PONE); OffsetDateTime b = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PTWO); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } @Test public void test_equals_itself_true() { - assertEquals(TEST_2008_6_30_11_30_59_000000500.equals(TEST_2008_6_30_11_30_59_000000500), true); + assertEquals(true, TEST_2008_6_30_11_30_59_000000500.equals(TEST_2008_6_30_11_30_59_000000500)); } @Test public void test_equals_string_false() { - assertEquals(TEST_2008_6_30_11_30_59_000000500.equals("2007-07-15"), false); + assertEquals(false, TEST_2008_6_30_11_30_59_000000500.equals("2007-07-15")); } @Test public void test_equals_null_false() { - assertEquals(TEST_2008_6_30_11_30_59_000000500.equals(null), false); + assertEquals(false, TEST_2008_6_30_11_30_59_000000500.equals(null)); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="sampleToString") Object[][] provider_sampleToString() { return new Object[][] { {2008, 6, 30, 11, 30, 59, 0, "Z", "2008-06-30T11:30:59Z"}, @@ -1587,11 +1631,12 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_toString(int y, int o, int d, int h, int m, int s, int n, String offsetId, String expected) { OffsetDateTime t = OffsetDateTime.of(y, o, d, h, m, s, n, ZoneOffset.of(offsetId)); String str = t.toString(); - assertEquals(str, expected); + assertEquals(expected, str); } } diff --git a/test/jdk/java/time/tck/java/time/TCKOffsetTime.java b/test/jdk/java/time/tck/java/time/TCKOffsetTime.java index 738bb86c2f4..7ea9504edbc 100644 --- a/test/jdk/java/time/tck/java/time/TCKOffsetTime.java +++ b/test/jdk/java/time/tck/java/time/TCKOffsetTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -84,10 +84,11 @@ import static java.time.temporal.ChronoUnit.MILLIS; import static java.time.temporal.ChronoUnit.HALF_DAYS; import static java.time.temporal.ChronoUnit.NANOS; import static java.time.temporal.ChronoUnit.SECONDS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.Clock; import java.time.DateTimeException; @@ -118,15 +119,19 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.MockSimplePeriod; /** * Test OffsetTime. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKOffsetTime extends AbstractDateTimeTest { private static final ZoneId ZONE_GAZA = ZoneId.of("Asia/Gaza"); @@ -136,7 +141,7 @@ public class TCKOffsetTime extends AbstractDateTimeTest { private static final LocalDate DATE = LocalDate.of(2008, 12, 3); private OffsetTime TEST_11_30_59_500_PONE; - @BeforeMethod + @BeforeEach public void setUp() { TEST_11_30_59_500_PONE = OffsetTime.of(11, 30, 59, 500, OFFSET_PONE); } @@ -144,7 +149,8 @@ public class TCKOffsetTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Override protected List samples() { - TemporalAccessor[] array = {TEST_11_30_59_500_PONE, OffsetTime.MIN, OffsetTime.MAX}; + TemporalAccessor[] array = {OffsetTime.of(11, 30, 59, 500, OFFSET_PONE), + OffsetTime.MIN, OffsetTime.MAX}; return Arrays.asList(array); } @@ -212,7 +218,7 @@ public class TCKOffsetTime extends AbstractDateTimeTest { diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay()); } assertTrue(diff < DELTA); - assertEquals(test.getOffset(), nowDT.getOffset()); + assertEquals(nowDT.getOffset(), test.getOffset()); } //----------------------------------------------------------------------- @@ -224,11 +230,11 @@ public class TCKOffsetTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i, 8); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); OffsetTime test = OffsetTime.now(clock); - assertEquals(test.getHour(), (i / (60 * 60)) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); - assertEquals(test.getNano(), 8); - assertEquals(test.getOffset(), ZoneOffset.UTC); + assertEquals((i / (60 * 60)) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); + assertEquals(8, test.getNano()); + assertEquals(ZoneOffset.UTC, test.getOffset()); } } @@ -238,11 +244,11 @@ public class TCKOffsetTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i, 8); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); OffsetTime test = OffsetTime.now(clock); - assertEquals(test.getHour(), ((i + 24 * 60 * 60) / (60 * 60)) % 24); - assertEquals(test.getMinute(), ((i + 24 * 60 * 60) / 60) % 60); - assertEquals(test.getSecond(), (i + 24 * 60 * 60) % 60); - assertEquals(test.getNano(), 8); - assertEquals(test.getOffset(), ZoneOffset.UTC); + assertEquals(((i + 24 * 60 * 60) / (60 * 60)) % 24, test.getHour()); + assertEquals(((i + 24 * 60 * 60) / 60) % 60, test.getMinute()); + assertEquals((i + 24 * 60 * 60) % 60, test.getSecond()); + assertEquals(8, test.getNano()); + assertEquals(ZoneOffset.UTC, test.getOffset()); } } @@ -253,39 +259,39 @@ public class TCKOffsetTime extends AbstractDateTimeTest { ZoneOffset offset = ZoneOffset.ofHours(i); Clock clock = Clock.fixed(base, offset); OffsetTime test = OffsetTime.now(clock); - assertEquals(test.getHour(), (12 + i) % 24); - assertEquals(test.getMinute(), 0); - assertEquals(test.getSecond(), 0); - assertEquals(test.getNano(), 0); - assertEquals(test.getOffset(), offset); + assertEquals((12 + i) % 24, test.getHour()); + assertEquals(0, test.getMinute()); + assertEquals(0, test.getSecond()); + assertEquals(0, test.getNano()); + assertEquals(offset, test.getOffset()); } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullZoneId() { - OffsetTime.now((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetTime.now((ZoneId) null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullClock() { - OffsetTime.now((Clock) null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetTime.now((Clock) null)); } //----------------------------------------------------------------------- // factories //----------------------------------------------------------------------- private void check(OffsetTime test, int h, int m, int s, int n, ZoneOffset offset) { - assertEquals(test.toLocalTime(), LocalTime.of(h, m, s, n)); - assertEquals(test.getOffset(), offset); + assertEquals(LocalTime.of(h, m, s, n), test.toLocalTime()); + assertEquals(offset, test.getOffset()); - assertEquals(test.getHour(), h); - assertEquals(test.getMinute(), m); - assertEquals(test.getSecond(), s); - assertEquals(test.getNano(), n); + assertEquals(h, test.getHour()); + assertEquals(m, test.getMinute()); + assertEquals(s, test.getSecond()); + assertEquals(n, test.getNano()); assertEquals(test, test); assertEquals(test.hashCode(), test.hashCode()); - assertEquals(OffsetTime.of(LocalTime.of(h, m, s, n), offset), test); + assertEquals(test, OffsetTime.of(LocalTime.of(h, m, s, n), offset)); } //----------------------------------------------------------------------- @@ -303,29 +309,33 @@ public class TCKOffsetTime extends AbstractDateTimeTest { check(test, 11, 30, 10, 500, OFFSET_PONE); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_LocalTimeZoneOffset_nullTime() { - OffsetTime.of((LocalTime) null, OFFSET_PONE); + Assertions.assertThrows(NullPointerException.class, () -> OffsetTime.of((LocalTime) null, OFFSET_PONE)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_LocalTimeZoneOffset_nullOffset() { - LocalTime localTime = LocalTime.of(11, 30, 10, 500); - OffsetTime.of(localTime, (ZoneOffset) null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalTime localTime = LocalTime.of(11, 30, 10, 500); + OffsetTime.of(localTime, (ZoneOffset) null); + }); } //----------------------------------------------------------------------- // ofInstant() //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_nullInstant() { - OffsetTime.ofInstant((Instant) null, ZoneOffset.UTC); + Assertions.assertThrows(NullPointerException.class, () -> OffsetTime.ofInstant((Instant) null, ZoneOffset.UTC)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_nullOffset() { - Instant instant = Instant.ofEpochSecond(0L); - OffsetTime.ofInstant(instant, (ZoneOffset) null); + Assertions.assertThrows(NullPointerException.class, () -> { + Instant instant = Instant.ofEpochSecond(0L); + OffsetTime.ofInstant(instant, (ZoneOffset) null); + }); } @Test @@ -333,10 +343,10 @@ public class TCKOffsetTime extends AbstractDateTimeTest { for (int i = 0; i < (2 * 24 * 60 * 60); i++) { Instant instant = Instant.ofEpochSecond(i, 8); OffsetTime test = OffsetTime.ofInstant(instant, ZoneOffset.UTC); - assertEquals(test.getHour(), (i / (60 * 60)) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); - assertEquals(test.getNano(), 8); + assertEquals((i / (60 * 60)) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); + assertEquals(8, test.getNano()); } } @@ -345,10 +355,10 @@ public class TCKOffsetTime extends AbstractDateTimeTest { for (int i =-1; i >= -(24 * 60 * 60); i--) { Instant instant = Instant.ofEpochSecond(i, 8); OffsetTime test = OffsetTime.ofInstant(instant, ZoneOffset.UTC); - assertEquals(test.getHour(), ((i + 24 * 60 * 60) / (60 * 60)) % 24); - assertEquals(test.getMinute(), ((i + 24 * 60 * 60) / 60) % 60); - assertEquals(test.getSecond(), (i + 24 * 60 * 60) % 60); - assertEquals(test.getNano(), 8); + assertEquals(((i + 24 * 60 * 60) / (60 * 60)) % 24, test.getHour()); + assertEquals(((i + 24 * 60 * 60) / 60) % 60, test.getMinute()); + assertEquals((i + 24 * 60 * 60) % 60, test.getSecond()); + assertEquals(8, test.getNano()); } } @@ -356,19 +366,19 @@ public class TCKOffsetTime extends AbstractDateTimeTest { @Test public void factory_ofInstant_maxYear() { OffsetTime test = OffsetTime.ofInstant(Instant.MAX, ZoneOffset.UTC); - assertEquals(test.getHour(), 23); - assertEquals(test.getMinute(), 59); - assertEquals(test.getSecond(), 59); - assertEquals(test.getNano(), 999_999_999); + assertEquals(23, test.getHour()); + assertEquals(59, test.getMinute()); + assertEquals(59, test.getSecond()); + assertEquals(999_999_999, test.getNano()); } @Test public void factory_ofInstant_minYear() { OffsetTime test = OffsetTime.ofInstant(Instant.MIN, ZoneOffset.UTC); - assertEquals(test.getHour(), 0); - assertEquals(test.getMinute(), 0); - assertEquals(test.getSecond(), 0); - assertEquals(test.getNano(), 0); + assertEquals(0, test.getHour()); + assertEquals(0, test.getMinute()); + assertEquals(0, test.getSecond()); + assertEquals(0, test.getNano()); } //----------------------------------------------------------------------- @@ -376,36 +386,36 @@ public class TCKOffsetTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void factory_from_TemporalAccessor_OT() { - assertEquals(OffsetTime.from(OffsetTime.of(17, 30, 0, 0, OFFSET_PONE)), OffsetTime.of(17, 30, 0, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(17, 30, 0, 0, OFFSET_PONE), OffsetTime.from(OffsetTime.of(17, 30, 0, 0, OFFSET_PONE))); } @Test public void test_from_TemporalAccessor_ZDT() { ZonedDateTime base = LocalDateTime.of(2007, 7, 15, 11, 30, 59, 500).atZone(OFFSET_PONE); - assertEquals(OffsetTime.from(base), TEST_11_30_59_500_PONE); + assertEquals(TEST_11_30_59_500_PONE, OffsetTime.from(base)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_from_TemporalAccessor_invalid_noDerive() { - OffsetTime.from(LocalDate.of(2007, 7, 15)); + Assertions.assertThrows(DateTimeException.class, () -> OffsetTime.from(LocalDate.of(2007, 7, 15))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_from_TemporalAccessor_null() { - OffsetTime.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetTime.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- // parse() //----------------------------------------------------------------------- - @Test(dataProvider = "sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void factory_parse_validText(int h, int m, int s, int n, String offsetId, String parsable) { OffsetTime t = OffsetTime.parse(parsable); assertNotNull(t, parsable); check(t, h, m, s, n, ZoneOffset.of(offsetId)); } - @DataProvider(name="sampleBadParse") Object[][] provider_sampleBadParse() { return new Object[][]{ {"00;00"}, @@ -420,25 +430,26 @@ public class TCKOffsetTime extends AbstractDateTimeTest { }; } - @Test(dataProvider = "sampleBadParse", expectedExceptions={DateTimeParseException.class}) + @ParameterizedTest + @MethodSource("provider_sampleBadParse") public void factory_parse_invalidText(String unparsable) { - OffsetTime.parse(unparsable); + Assertions.assertThrows(DateTimeParseException.class, () -> OffsetTime.parse(unparsable)); } //-----------------------------------------------------------------------s - @Test(expectedExceptions={DateTimeParseException.class}) + @Test public void factory_parse_illegalHour() { - OffsetTime.parse("25:00+01:00"); + Assertions.assertThrows(DateTimeParseException.class, () -> OffsetTime.parse("25:00+01:00")); } - @Test(expectedExceptions={DateTimeParseException.class}) + @Test public void factory_parse_illegalMinute() { - OffsetTime.parse("12:60+01:00"); + Assertions.assertThrows(DateTimeParseException.class, () -> OffsetTime.parse("12:60+01:00")); } - @Test(expectedExceptions={DateTimeParseException.class}) + @Test public void factory_parse_illegalSecond() { - OffsetTime.parse("12:12:60+01:00"); + Assertions.assertThrows(DateTimeParseException.class, () -> OffsetTime.parse("12:12:60+01:00")); } //----------------------------------------------------------------------- @@ -448,37 +459,38 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void factory_parse_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("H m s XXX"); OffsetTime test = OffsetTime.parse("11 30 0 +01:00", f); - assertEquals(test, OffsetTime.of(11, 30, 0, 0, ZoneOffset.ofHours(1))); + assertEquals(OffsetTime.of(11, 30, 0, 0, ZoneOffset.ofHours(1)), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullText() { - DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); - OffsetTime.parse((String) null, f); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); + OffsetTime.parse((String) null, f); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullFormatter() { - OffsetTime.parse("ANY", null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetTime.parse("ANY", null)); } //----------------------------------------------------------------------- // constructor via factory //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void constructor_nullTime() throws Throwable { - OffsetTime.of(null, OFFSET_PONE); + Assertions.assertThrows(NullPointerException.class, () -> OffsetTime.of(null, OFFSET_PONE)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void constructor_nullOffset() throws Throwable { - OffsetTime.of(LocalTime.of(11, 30, 0, 0), null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetTime.of(LocalTime.of(11, 30, 0, 0), null)); } //----------------------------------------------------------------------- // basics //----------------------------------------------------------------------- - @DataProvider(name="sampleTimes") Object[][] provider_sampleTimes() { return new Object[][] { {11, 30, 20, 500, OFFSET_PONE}, @@ -487,18 +499,19 @@ public class TCKOffsetTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_get(int h, int m, int s, int n, ZoneOffset offset) { LocalTime localTime = LocalTime.of(h, m, s, n); OffsetTime a = OffsetTime.of(localTime, offset); - assertEquals(a.toLocalTime(), localTime); - assertEquals(a.getOffset(), offset); - assertEquals(a.toString(), localTime.toString() + offset.toString()); - assertEquals(a.getHour(), localTime.getHour()); - assertEquals(a.getMinute(), localTime.getMinute()); - assertEquals(a.getSecond(), localTime.getSecond()); - assertEquals(a.getNano(), localTime.getNano()); + assertEquals(localTime, a.toLocalTime()); + assertEquals(offset, a.getOffset()); + assertEquals(localTime.toString() + offset.toString(), a.toString()); + assertEquals(localTime.getHour(), a.getHour()); + assertEquals(localTime.getMinute(), a.getMinute()); + assertEquals(localTime.getSecond(), a.getSecond()); + assertEquals(localTime.getNano(), a.getNano()); } //----------------------------------------------------------------------- @@ -506,37 +519,37 @@ public class TCKOffsetTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(TEST_11_30_59_500_PONE.isSupported((TemporalField) null), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.NANO_OF_SECOND), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.NANO_OF_DAY), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.MICRO_OF_SECOND), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.MICRO_OF_DAY), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.MILLI_OF_SECOND), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.MILLI_OF_DAY), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.SECOND_OF_MINUTE), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.SECOND_OF_DAY), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.MINUTE_OF_HOUR), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.MINUTE_OF_DAY), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.HOUR_OF_AMPM), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.HOUR_OF_DAY), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.AMPM_OF_DAY), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.DAY_OF_WEEK), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.DAY_OF_MONTH), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.DAY_OF_YEAR), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.EPOCH_DAY), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.MONTH_OF_YEAR), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.PROLEPTIC_MONTH), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.YEAR), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.YEAR_OF_ERA), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.ERA), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.INSTANT_SECONDS), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoField.OFFSET_SECONDS), true); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported((TemporalField) null)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.YEAR)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.ERA)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -544,23 +557,23 @@ public class TCKOffsetTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalUnit() { - assertEquals(TEST_11_30_59_500_PONE.isSupported((TemporalUnit) null), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.NANOS), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.MICROS), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.MILLIS), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.SECONDS), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.MINUTES), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.HOURS), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.HALF_DAYS), true); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.DAYS), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.WEEKS), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.MONTHS), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.YEARS), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.DECADES), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.CENTURIES), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.MILLENNIA), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.ERAS), false); - assertEquals(TEST_11_30_59_500_PONE.isSupported(ChronoUnit.FOREVER), false); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported((TemporalUnit) null)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.NANOS)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.MICROS)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.MILLIS)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.SECONDS)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.MINUTES)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.HOURS)); + assertEquals(true, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.HALF_DAYS)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.DAYS)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.WEEKS)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.MONTHS)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.YEARS)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.DECADES)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.CENTURIES)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.MILLENNIA)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.ERAS)); + assertEquals(false, TEST_11_30_59_500_PONE.isSupported(ChronoUnit.FOREVER)); } //----------------------------------------------------------------------- @@ -569,33 +582,32 @@ public class TCKOffsetTime extends AbstractDateTimeTest { @Test public void test_get_TemporalField() { OffsetTime test = OffsetTime.of(12, 30, 40, 987654321, OFFSET_PONE); - assertEquals(test.get(ChronoField.HOUR_OF_DAY), 12); - assertEquals(test.get(ChronoField.MINUTE_OF_HOUR), 30); - assertEquals(test.get(ChronoField.SECOND_OF_MINUTE), 40); - assertEquals(test.get(ChronoField.NANO_OF_SECOND), 987654321); - assertEquals(test.get(ChronoField.HOUR_OF_AMPM), 0); - assertEquals(test.get(ChronoField.AMPM_OF_DAY), 1); + assertEquals(12, test.get(ChronoField.HOUR_OF_DAY)); + assertEquals(30, test.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(40, test.get(ChronoField.SECOND_OF_MINUTE)); + assertEquals(987654321, test.get(ChronoField.NANO_OF_SECOND)); + assertEquals(0, test.get(ChronoField.HOUR_OF_AMPM)); + assertEquals(1, test.get(ChronoField.AMPM_OF_DAY)); - assertEquals(test.get(ChronoField.OFFSET_SECONDS), 3600); + assertEquals(3600, test.get(ChronoField.OFFSET_SECONDS)); } @Test public void test_getLong_TemporalField() { OffsetTime test = OffsetTime.of(12, 30, 40, 987654321, OFFSET_PONE); - assertEquals(test.getLong(ChronoField.HOUR_OF_DAY), 12); - assertEquals(test.getLong(ChronoField.MINUTE_OF_HOUR), 30); - assertEquals(test.getLong(ChronoField.SECOND_OF_MINUTE), 40); - assertEquals(test.getLong(ChronoField.NANO_OF_SECOND), 987654321); - assertEquals(test.getLong(ChronoField.HOUR_OF_AMPM), 0); - assertEquals(test.getLong(ChronoField.AMPM_OF_DAY), 1); + assertEquals(12, test.getLong(ChronoField.HOUR_OF_DAY)); + assertEquals(30, test.getLong(ChronoField.MINUTE_OF_HOUR)); + assertEquals(40, test.getLong(ChronoField.SECOND_OF_MINUTE)); + assertEquals(987654321, test.getLong(ChronoField.NANO_OF_SECOND)); + assertEquals(0, test.getLong(ChronoField.HOUR_OF_AMPM)); + assertEquals(1, test.getLong(ChronoField.AMPM_OF_DAY)); - assertEquals(test.getLong(ChronoField.OFFSET_SECONDS), 3600); + assertEquals(3600, test.getLong(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {TEST_11_30_59_500_PONE, TemporalQueries.chronology(), null}, @@ -608,19 +620,21 @@ public class TCKOffsetTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - TEST_11_30_59_500_PONE.query(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_11_30_59_500_PONE.query(null)); } //----------------------------------------------------------------------- @@ -630,21 +644,23 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_withOffsetSameLocal() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.withOffsetSameLocal(OFFSET_PTWO); - assertEquals(test.toLocalTime(), base.toLocalTime()); - assertEquals(test.getOffset(), OFFSET_PTWO); + assertEquals(base.toLocalTime(), test.toLocalTime()); + assertEquals(OFFSET_PTWO, test.getOffset()); } @Test public void test_withOffsetSameLocal_noChange() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.withOffsetSameLocal(OFFSET_PONE); - assertEquals(test, base); + assertEquals(base, test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_withOffsetSameLocal_null() { - OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); - base.withOffsetSameLocal(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); + base.withOffsetSameLocal(null); + }); } //----------------------------------------------------------------------- @@ -655,26 +671,27 @@ public class TCKOffsetTime extends AbstractDateTimeTest { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.withOffsetSameInstant(OFFSET_PTWO); OffsetTime expected = OffsetTime.of(12, 30, 59, 0, OFFSET_PTWO); - assertEquals(test, expected); + assertEquals(expected, test); } @Test public void test_withOffsetSameInstant_noChange() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.withOffsetSameInstant(OFFSET_PONE); - assertEquals(test, base); + assertEquals(base, test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_withOffsetSameInstant_null() { - OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); - base.withOffsetSameInstant(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); + base.withOffsetSameInstant(null); + }); } //----------------------------------------------------------------------- // adjustInto(Temporal) //----------------------------------------------------------------------- - @DataProvider(name="adjustInto") Object[][] data_adjustInto() { return new Object[][]{ {OffsetTime.of(LocalTime.of(23, 5), OFFSET_PONE), OffsetTime.of(LocalTime.of(1, 1, 1, 100), ZoneOffset.UTC), OffsetTime.of(LocalTime.of(23, 5), OFFSET_PONE), null}, @@ -695,11 +712,12 @@ public class TCKOffsetTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="adjustInto") + @ParameterizedTest + @MethodSource("data_adjustInto") public void test_adjustInto(OffsetTime test, Temporal temporal, Temporal expected, Class expectedEx) { if (expectedEx == null) { Temporal result = test.adjustInto(temporal); - assertEquals(result, expected); + assertEquals(expected, result); } else { try { Temporal result = test.adjustInto(temporal); @@ -722,25 +740,25 @@ public class TCKOffsetTime extends AbstractDateTimeTest { return sample; } }; - assertEquals(TEST_11_30_59_500_PONE.with(adjuster), sample); + assertEquals(sample, TEST_11_30_59_500_PONE.with(adjuster)); } @Test public void test_with_adjustment_LocalTime() { OffsetTime test = TEST_11_30_59_500_PONE.with(LocalTime.of(13, 30)); - assertEquals(test, OffsetTime.of(13, 30, 0, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(13, 30, 0, 0, OFFSET_PONE), test); } @Test public void test_with_adjustment_OffsetTime() { OffsetTime test = TEST_11_30_59_500_PONE.with(OffsetTime.of(13, 35, 0, 0, OFFSET_PTWO)); - assertEquals(test, OffsetTime.of(13, 35, 0, 0, OFFSET_PTWO)); + assertEquals(OffsetTime.of(13, 35, 0, 0, OFFSET_PTWO), test); } @Test public void test_with_adjustment_ZoneOffset() { OffsetTime test = TEST_11_30_59_500_PONE.with(OFFSET_PTWO); - assertEquals(test, OffsetTime.of(11, 30, 59, 500, OFFSET_PTWO)); + assertEquals(OffsetTime.of(11, 30, 59, 500, OFFSET_PTWO), test); } @Test @@ -751,12 +769,12 @@ public class TCKOffsetTime extends AbstractDateTimeTest { return dateTime.with(HOUR_OF_DAY, 23); } }); - assertEquals(test, OffsetTime.of(23, 30, 59, 500, OFFSET_PONE)); + assertEquals(OffsetTime.of(23, 30, 59, 500, OFFSET_PONE), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_with_adjustment_null() { - TEST_11_30_59_500_PONE.with((TemporalAdjuster) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_11_30_59_500_PONE.with((TemporalAdjuster) null)); } //----------------------------------------------------------------------- @@ -765,24 +783,24 @@ public class TCKOffsetTime extends AbstractDateTimeTest { @Test public void test_with_TemporalField() { OffsetTime test = OffsetTime.of(12, 30, 40, 987654321, OFFSET_PONE); - assertEquals(test.with(ChronoField.HOUR_OF_DAY, 15), OffsetTime.of(15, 30, 40, 987654321, OFFSET_PONE)); - assertEquals(test.with(ChronoField.MINUTE_OF_HOUR, 50), OffsetTime.of(12, 50, 40, 987654321, OFFSET_PONE)); - assertEquals(test.with(ChronoField.SECOND_OF_MINUTE, 50), OffsetTime.of(12, 30, 50, 987654321, OFFSET_PONE)); - assertEquals(test.with(ChronoField.NANO_OF_SECOND, 12345), OffsetTime.of(12, 30, 40, 12345, OFFSET_PONE)); - assertEquals(test.with(ChronoField.HOUR_OF_AMPM, 6), OffsetTime.of(18, 30, 40, 987654321, OFFSET_PONE)); - assertEquals(test.with(ChronoField.AMPM_OF_DAY, 0), OffsetTime.of(0, 30, 40, 987654321, OFFSET_PONE)); + assertEquals(OffsetTime.of(15, 30, 40, 987654321, OFFSET_PONE), test.with(ChronoField.HOUR_OF_DAY, 15)); + assertEquals(OffsetTime.of(12, 50, 40, 987654321, OFFSET_PONE), test.with(ChronoField.MINUTE_OF_HOUR, 50)); + assertEquals(OffsetTime.of(12, 30, 50, 987654321, OFFSET_PONE), test.with(ChronoField.SECOND_OF_MINUTE, 50)); + assertEquals(OffsetTime.of(12, 30, 40, 12345, OFFSET_PONE), test.with(ChronoField.NANO_OF_SECOND, 12345)); + assertEquals(OffsetTime.of(18, 30, 40, 987654321, OFFSET_PONE), test.with(ChronoField.HOUR_OF_AMPM, 6)); + assertEquals(OffsetTime.of(0, 30, 40, 987654321, OFFSET_PONE), test.with(ChronoField.AMPM_OF_DAY, 0)); - assertEquals(test.with(ChronoField.OFFSET_SECONDS, 7205), OffsetTime.of(12, 30, 40, 987654321, ZoneOffset.ofHoursMinutesSeconds(2, 0, 5))); + assertEquals(OffsetTime.of(12, 30, 40, 987654321, ZoneOffset.ofHoursMinutesSeconds(2, 0, 5)), test.with(ChronoField.OFFSET_SECONDS, 7205)); } - @Test(expectedExceptions=NullPointerException.class ) + @Test public void test_with_TemporalField_null() { - TEST_11_30_59_500_PONE.with((TemporalField) null, 0); + Assertions.assertThrows(NullPointerException.class, () -> TEST_11_30_59_500_PONE.with((TemporalField) null, 0)); } - @Test(expectedExceptions=DateTimeException.class ) + @Test public void test_with_TemporalField_invalidField() { - TEST_11_30_59_500_PONE.with(ChronoField.YEAR, 0); + Assertions.assertThrows(DateTimeException.class, () -> TEST_11_30_59_500_PONE.with(ChronoField.YEAR, 0)); } //----------------------------------------------------------------------- @@ -792,14 +810,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_withHour_normal() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.withHour(15); - assertEquals(test, OffsetTime.of(15, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(15, 30, 59, 0, OFFSET_PONE), test); } @Test public void test_withHour_noChange() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.withHour(11); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -809,14 +827,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_withMinute_normal() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.withMinute(15); - assertEquals(test, OffsetTime.of(11, 15, 59, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(11, 15, 59, 0, OFFSET_PONE), test); } @Test public void test_withMinute_noChange() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.withMinute(30); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -826,14 +844,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_withSecond_normal() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.withSecond(15); - assertEquals(test, OffsetTime.of(11, 30, 15, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(11, 30, 15, 0, OFFSET_PONE), test); } @Test public void test_withSecond_noChange() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.withSecond(59); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -843,14 +861,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_withNanoOfSecond_normal() { OffsetTime base = OffsetTime.of(11, 30, 59, 1, OFFSET_PONE); OffsetTime test = base.withNano(15); - assertEquals(test, OffsetTime.of(11, 30, 59, 15, OFFSET_PONE)); + assertEquals(OffsetTime.of(11, 30, 59, 15, OFFSET_PONE), test); } @Test public void test_withNanoOfSecond_noChange() { OffsetTime base = OffsetTime.of(11, 30, 59, 1, OFFSET_PONE); OffsetTime test = base.withNano(1); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -858,14 +876,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_truncatedTo_normal() { - assertEquals(TEST_11_30_59_500_PONE.truncatedTo(NANOS), TEST_11_30_59_500_PONE); - assertEquals(TEST_11_30_59_500_PONE.truncatedTo(SECONDS), TEST_11_30_59_500_PONE.withNano(0)); - assertEquals(TEST_11_30_59_500_PONE.truncatedTo(DAYS), TEST_11_30_59_500_PONE.with(LocalTime.MIDNIGHT)); + assertEquals(TEST_11_30_59_500_PONE, TEST_11_30_59_500_PONE.truncatedTo(NANOS)); + assertEquals(TEST_11_30_59_500_PONE.withNano(0), TEST_11_30_59_500_PONE.truncatedTo(SECONDS)); + assertEquals(TEST_11_30_59_500_PONE.with(LocalTime.MIDNIGHT), TEST_11_30_59_500_PONE.truncatedTo(DAYS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_truncatedTo_null() { - TEST_11_30_59_500_PONE.truncatedTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_11_30_59_500_PONE.truncatedTo(null)); } //----------------------------------------------------------------------- @@ -875,24 +893,24 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_plus_PlusAdjuster() { MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.MINUTES); OffsetTime t = TEST_11_30_59_500_PONE.plus(period); - assertEquals(t, OffsetTime.of(11, 37, 59, 500, OFFSET_PONE)); + assertEquals(OffsetTime.of(11, 37, 59, 500, OFFSET_PONE), t); } @Test public void test_plus_PlusAdjuster_noChange() { OffsetTime t = TEST_11_30_59_500_PONE.plus(MockSimplePeriod.of(0, SECONDS)); - assertEquals(t, TEST_11_30_59_500_PONE); + assertEquals(TEST_11_30_59_500_PONE, t); } @Test public void test_plus_PlusAdjuster_zero() { OffsetTime t = TEST_11_30_59_500_PONE.plus(Period.ZERO); - assertEquals(t, TEST_11_30_59_500_PONE); + assertEquals(TEST_11_30_59_500_PONE, t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_PlusAdjuster_null() { - TEST_11_30_59_500_PONE.plus((TemporalAmount) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_11_30_59_500_PONE.plus((TemporalAmount) null)); } //----------------------------------------------------------------------- @@ -902,14 +920,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_plusHours() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.plusHours(13); - assertEquals(test, OffsetTime.of(0, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(0, 30, 59, 0, OFFSET_PONE), test); } @Test public void test_plusHours_zero() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.plusHours(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -919,14 +937,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_plusMinutes() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.plusMinutes(30); - assertEquals(test, OffsetTime.of(12, 0, 59, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(12, 0, 59, 0, OFFSET_PONE), test); } @Test public void test_plusMinutes_zero() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.plusMinutes(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -936,14 +954,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_plusSeconds() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.plusSeconds(1); - assertEquals(test, OffsetTime.of(11, 31, 0, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(11, 31, 0, 0, OFFSET_PONE), test); } @Test public void test_plusSeconds_zero() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.plusSeconds(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -953,14 +971,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_plusNanos() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.plusNanos(1); - assertEquals(test, OffsetTime.of(11, 30, 59, 1, OFFSET_PONE)); + assertEquals(OffsetTime.of(11, 30, 59, 1, OFFSET_PONE), test); } @Test public void test_plusNanos_zero() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.plusNanos(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -970,24 +988,24 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_minus_MinusAdjuster() { MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.MINUTES); OffsetTime t = TEST_11_30_59_500_PONE.minus(period); - assertEquals(t, OffsetTime.of(11, 23, 59, 500, OFFSET_PONE)); + assertEquals(OffsetTime.of(11, 23, 59, 500, OFFSET_PONE), t); } @Test public void test_minus_MinusAdjuster_noChange() { OffsetTime t = TEST_11_30_59_500_PONE.minus(MockSimplePeriod.of(0, SECONDS)); - assertEquals(t, TEST_11_30_59_500_PONE); + assertEquals(TEST_11_30_59_500_PONE, t); } @Test public void test_minus_MinusAdjuster_zero() { OffsetTime t = TEST_11_30_59_500_PONE.minus(Period.ZERO); - assertEquals(t, TEST_11_30_59_500_PONE); + assertEquals(TEST_11_30_59_500_PONE, t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_minus_MinusAdjuster_null() { - TEST_11_30_59_500_PONE.minus((TemporalAmount) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_11_30_59_500_PONE.minus((TemporalAmount) null)); } //----------------------------------------------------------------------- @@ -997,14 +1015,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_minusHours() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.minusHours(-13); - assertEquals(test, OffsetTime.of(0, 30, 59, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(0, 30, 59, 0, OFFSET_PONE), test); } @Test public void test_minusHours_zero() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.minusHours(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1014,14 +1032,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_minusMinutes() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.minusMinutes(50); - assertEquals(test, OffsetTime.of(10, 40, 59, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(10, 40, 59, 0, OFFSET_PONE), test); } @Test public void test_minusMinutes_zero() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.minusMinutes(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1031,14 +1049,14 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_minusSeconds() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.minusSeconds(60); - assertEquals(test, OffsetTime.of(11, 29, 59, 0, OFFSET_PONE)); + assertEquals(OffsetTime.of(11, 29, 59, 0, OFFSET_PONE), test); } @Test public void test_minusSeconds_zero() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.minusSeconds(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1048,20 +1066,19 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_minusNanos() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.minusNanos(1); - assertEquals(test, OffsetTime.of(11, 30, 58, 999999999, OFFSET_PONE)); + assertEquals(OffsetTime.of(11, 30, 58, 999999999, OFFSET_PONE), test); } @Test public void test_minusNanos_zero() { OffsetTime base = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); OffsetTime test = base.minusNanos(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- // until(Temporal, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="periodUntilUnit") Object[][] data_untilUnit() { return new Object[][] { {OffsetTime.of(1, 1, 1, 0, OFFSET_PONE), OffsetTime.of(13, 1, 1, 0, OFFSET_PONE), HALF_DAYS, 1}, @@ -1082,42 +1099,49 @@ public class TCKOffsetTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_untilUnit") public void test_until_TemporalUnit(OffsetTime offsetTime1, OffsetTime offsetTime2, TemporalUnit unit, long expected) { long amount = offsetTime1.until(offsetTime2, unit); - assertEquals(amount, expected); + assertEquals(expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_untilUnit") public void test_until_TemporalUnit_negated(OffsetTime offsetTime1, OffsetTime offsetTime2, TemporalUnit unit, long expected) { long amount = offsetTime2.until(offsetTime1, unit); - assertEquals(amount, -expected); + assertEquals(-expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_untilUnit") public void test_until_TemporalUnit_between(OffsetTime offsetTime1, OffsetTime offsetTime2, TemporalUnit unit, long expected) { long amount = unit.between(offsetTime1, offsetTime2); - assertEquals(amount, expected); + assertEquals(expected, amount); } @Test public void test_until_convertedType() { OffsetTime offsetTime = OffsetTime.of(1, 1, 1, 0, OFFSET_PONE); OffsetDateTime offsetDateTime = offsetTime.plusSeconds(3).atDate(LocalDate.of(1980, 2, 10)); - assertEquals(offsetTime.until(offsetDateTime, SECONDS), 3); + assertEquals(3, offsetTime.until(offsetDateTime, SECONDS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_invalidType() { - OffsetTime offsetTime = OffsetTime.of(1, 1, 1, 0, OFFSET_PONE); - offsetTime.until(LocalDate.of(1980, 2, 10), SECONDS); + Assertions.assertThrows(DateTimeException.class, () -> { + OffsetTime offsetTime = OffsetTime.of(1, 1, 1, 0, OFFSET_PONE); + offsetTime.until(LocalDate.of(1980, 2, 10), SECONDS); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_invalidTemporalUnit() { - OffsetTime offsetTime1 = OffsetTime.of(1, 1, 1, 0, OFFSET_PONE); - OffsetTime offsetTime2 = OffsetTime.of(2, 1, 1, 0, OFFSET_PONE); - offsetTime1.until(offsetTime2, MONTHS); + Assertions.assertThrows(DateTimeException.class, () -> { + OffsetTime offsetTime1 = OffsetTime.of(1, 1, 1, 0, OFFSET_PONE); + OffsetTime offsetTime2 = OffsetTime.of(2, 1, 1, 0, OFFSET_PONE); + offsetTime1.until(offsetTime2, MONTHS); + }); } //----------------------------------------------------------------------- @@ -1127,18 +1151,17 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_format_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("H m s"); String t = OffsetTime.of(11, 30, 0, 0, OFFSET_PONE).format(f); - assertEquals(t, "11 30 0"); + assertEquals("11 30 0", t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_format_formatter_null() { - OffsetTime.of(11, 30, 0, 0, OFFSET_PONE).format(null); + Assertions.assertThrows(NullPointerException.class, () -> OffsetTime.of(11, 30, 0, 0, OFFSET_PONE).format(null)); } //----------------------------------------------------------------------- // toEpochSecond() //----------------------------------------------------------------------- - @DataProvider(name="epochSecond") Object[][] provider_toEpochSecond() { return new Object[][] { {OffsetTime.of(0, 0, 0, 0, OFFSET_PTWO).toEpochSecond(LocalDate.of(1970, 1, 1)), -7200L}, @@ -1153,9 +1176,10 @@ public class TCKOffsetTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="epochSecond") + @ParameterizedTest + @MethodSource("provider_toEpochSecond") public void test_toEpochSecond(long actual, long expected) { - assertEquals(actual, expected); + assertEquals(expected, actual); } //----------------------------------------------------------------------- @@ -1165,68 +1189,72 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_compareTo_time() { OffsetTime a = OffsetTime.of(11, 29, 0, 0, OFFSET_PONE); OffsetTime b = OffsetTime.of(11, 30, 0, 0, OFFSET_PONE); // a is before b due to time - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(convertInstant(a).compareTo(convertInstant(b)) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, convertInstant(a).compareTo(convertInstant(b)) < 0); } @Test public void test_compareTo_offset() { OffsetTime a = OffsetTime.of(11, 30, 0, 0, OFFSET_PTWO); OffsetTime b = OffsetTime.of(11, 30, 0, 0, OFFSET_PONE); // a is before b due to offset - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(convertInstant(a).compareTo(convertInstant(b)) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, convertInstant(a).compareTo(convertInstant(b)) < 0); } @Test public void test_compareTo_both() { OffsetTime a = OffsetTime.of(11, 50, 0, 0, OFFSET_PTWO); OffsetTime b = OffsetTime.of(11, 20, 0, 0, OFFSET_PONE); // a is before b on instant scale - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(convertInstant(a).compareTo(convertInstant(b)) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, convertInstant(a).compareTo(convertInstant(b)) < 0); } @Test public void test_compareTo_bothNearStartOfDay() { OffsetTime a = OffsetTime.of(0, 10, 0, 0, OFFSET_PONE); OffsetTime b = OffsetTime.of(2, 30, 0, 0, OFFSET_PTWO); // a is before b on instant scale - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(convertInstant(a).compareTo(convertInstant(b)) < 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, convertInstant(a).compareTo(convertInstant(b)) < 0); } @Test public void test_compareTo_hourDifference() { OffsetTime a = OffsetTime.of(10, 0, 0, 0, OFFSET_PONE); OffsetTime b = OffsetTime.of(11, 0, 0, 0, OFFSET_PTWO); // a is before b despite being same time-line time - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(convertInstant(a).compareTo(convertInstant(b)) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, convertInstant(a).compareTo(convertInstant(b)) == 0); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_null() { - OffsetTime a = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); - a.compareTo(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetTime a = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); + a.compareTo(null); + }); } - @Test(expectedExceptions=ClassCastException.class) @SuppressWarnings({"unchecked", "rawtypes"}) + @Test public void compareToNonOffsetTime() { - Comparable c = TEST_11_30_59_500_PONE; - c.compareTo(new Object()); + Assertions.assertThrows(ClassCastException.class, () -> { + Comparable c = TEST_11_30_59_500_PONE; + c.compareTo(new Object()); + }); } private Instant convertInstant(OffsetTime ot) { @@ -1240,194 +1268,205 @@ public class TCKOffsetTime extends AbstractDateTimeTest { public void test_isBeforeIsAfterIsEqual1() { OffsetTime a = OffsetTime.of(11, 30, 58, 0, OFFSET_PONE); OffsetTime b = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); // a is before b due to time - assertEquals(a.isBefore(b), true); - assertEquals(a.isEqual(b), false); - assertEquals(a.isAfter(b), false); + assertEquals(true, a.isBefore(b)); + assertEquals(false, a.isEqual(b)); + assertEquals(false, a.isAfter(b)); - assertEquals(b.isBefore(a), false); - assertEquals(b.isEqual(a), false); - assertEquals(b.isAfter(a), true); + assertEquals(false, b.isBefore(a)); + assertEquals(false, b.isEqual(a)); + assertEquals(true, b.isAfter(a)); - assertEquals(a.isBefore(a), false); - assertEquals(b.isBefore(b), false); + assertEquals(false, a.isBefore(a)); + assertEquals(false, b.isBefore(b)); - assertEquals(a.isEqual(a), true); - assertEquals(b.isEqual(b), true); + assertEquals(true, a.isEqual(a)); + assertEquals(true, b.isEqual(b)); - assertEquals(a.isAfter(a), false); - assertEquals(b.isAfter(b), false); + assertEquals(false, a.isAfter(a)); + assertEquals(false, b.isAfter(b)); } @Test public void test_isBeforeIsAfterIsEqual1nanos() { OffsetTime a = OffsetTime.of(11, 30, 59, 3, OFFSET_PONE); OffsetTime b = OffsetTime.of(11, 30, 59, 4, OFFSET_PONE); // a is before b due to time - assertEquals(a.isBefore(b), true); - assertEquals(a.isEqual(b), false); - assertEquals(a.isAfter(b), false); + assertEquals(true, a.isBefore(b)); + assertEquals(false, a.isEqual(b)); + assertEquals(false, a.isAfter(b)); - assertEquals(b.isBefore(a), false); - assertEquals(b.isEqual(a), false); - assertEquals(b.isAfter(a), true); + assertEquals(false, b.isBefore(a)); + assertEquals(false, b.isEqual(a)); + assertEquals(true, b.isAfter(a)); - assertEquals(a.isBefore(a), false); - assertEquals(b.isBefore(b), false); + assertEquals(false, a.isBefore(a)); + assertEquals(false, b.isBefore(b)); - assertEquals(a.isEqual(a), true); - assertEquals(b.isEqual(b), true); + assertEquals(true, a.isEqual(a)); + assertEquals(true, b.isEqual(b)); - assertEquals(a.isAfter(a), false); - assertEquals(b.isAfter(b), false); + assertEquals(false, a.isAfter(a)); + assertEquals(false, b.isAfter(b)); } @Test public void test_isBeforeIsAfterIsEqual2() { OffsetTime a = OffsetTime.of(11, 30, 59, 0, OFFSET_PTWO); OffsetTime b = OffsetTime.of(11, 30, 58, 0, OFFSET_PONE); // a is before b due to offset - assertEquals(a.isBefore(b), true); - assertEquals(a.isEqual(b), false); - assertEquals(a.isAfter(b), false); + assertEquals(true, a.isBefore(b)); + assertEquals(false, a.isEqual(b)); + assertEquals(false, a.isAfter(b)); - assertEquals(b.isBefore(a), false); - assertEquals(b.isEqual(a), false); - assertEquals(b.isAfter(a), true); + assertEquals(false, b.isBefore(a)); + assertEquals(false, b.isEqual(a)); + assertEquals(true, b.isAfter(a)); - assertEquals(a.isBefore(a), false); - assertEquals(b.isBefore(b), false); + assertEquals(false, a.isBefore(a)); + assertEquals(false, b.isBefore(b)); - assertEquals(a.isEqual(a), true); - assertEquals(b.isEqual(b), true); + assertEquals(true, a.isEqual(a)); + assertEquals(true, b.isEqual(b)); - assertEquals(a.isAfter(a), false); - assertEquals(b.isAfter(b), false); + assertEquals(false, a.isAfter(a)); + assertEquals(false, b.isAfter(b)); } @Test public void test_isBeforeIsAfterIsEqual2nanos() { OffsetTime a = OffsetTime.of(11, 30, 59, 4, ZoneOffset.ofTotalSeconds(OFFSET_PONE.getTotalSeconds() + 1)); OffsetTime b = OffsetTime.of(11, 30, 59, 3, OFFSET_PONE); // a is before b due to offset - assertEquals(a.isBefore(b), true); - assertEquals(a.isEqual(b), false); - assertEquals(a.isAfter(b), false); + assertEquals(true, a.isBefore(b)); + assertEquals(false, a.isEqual(b)); + assertEquals(false, a.isAfter(b)); - assertEquals(b.isBefore(a), false); - assertEquals(b.isEqual(a), false); - assertEquals(b.isAfter(a), true); + assertEquals(false, b.isBefore(a)); + assertEquals(false, b.isEqual(a)); + assertEquals(true, b.isAfter(a)); - assertEquals(a.isBefore(a), false); - assertEquals(b.isBefore(b), false); + assertEquals(false, a.isBefore(a)); + assertEquals(false, b.isBefore(b)); - assertEquals(a.isEqual(a), true); - assertEquals(b.isEqual(b), true); + assertEquals(true, a.isEqual(a)); + assertEquals(true, b.isEqual(b)); - assertEquals(a.isAfter(a), false); - assertEquals(b.isAfter(b), false); + assertEquals(false, a.isAfter(a)); + assertEquals(false, b.isAfter(b)); } @Test public void test_isBeforeIsAfterIsEqual_instantComparison() { OffsetTime a = OffsetTime.of(11, 30, 59, 0, OFFSET_PTWO); OffsetTime b = OffsetTime.of(10, 30, 59, 0, OFFSET_PONE); // a is same instant as b - assertEquals(a.isBefore(b), false); - assertEquals(a.isEqual(b), true); - assertEquals(a.isAfter(b), false); + assertEquals(false, a.isBefore(b)); + assertEquals(true, a.isEqual(b)); + assertEquals(false, a.isAfter(b)); - assertEquals(b.isBefore(a), false); - assertEquals(b.isEqual(a), true); - assertEquals(b.isAfter(a), false); + assertEquals(false, b.isBefore(a)); + assertEquals(true, b.isEqual(a)); + assertEquals(false, b.isAfter(a)); - assertEquals(a.isBefore(a), false); - assertEquals(b.isBefore(b), false); + assertEquals(false, a.isBefore(a)); + assertEquals(false, b.isBefore(b)); - assertEquals(a.isEqual(a), true); - assertEquals(b.isEqual(b), true); + assertEquals(true, a.isEqual(a)); + assertEquals(true, b.isEqual(b)); - assertEquals(a.isAfter(a), false); - assertEquals(b.isAfter(b), false); + assertEquals(false, a.isAfter(a)); + assertEquals(false, b.isAfter(b)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isBefore_null() { - OffsetTime a = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); - a.isBefore(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetTime a = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); + a.isBefore(null); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isAfter_null() { - OffsetTime a = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); - a.isAfter(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetTime a = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); + a.isAfter(null); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isEqual_null() { - OffsetTime a = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); - a.isEqual(null); + Assertions.assertThrows(NullPointerException.class, () -> { + OffsetTime a = OffsetTime.of(11, 30, 59, 0, OFFSET_PONE); + a.isEqual(null); + }); } //----------------------------------------------------------------------- // equals() / hashCode() //----------------------------------------------------------------------- - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_true(int h, int m, int s, int n, ZoneOffset ignored) { OffsetTime a = OffsetTime.of(h, m, s, n, OFFSET_PONE); OffsetTime b = OffsetTime.of(h, m, s, n, OFFSET_PONE); - assertEquals(a.equals(b), true); - assertEquals(a.hashCode() == b.hashCode(), true); + assertEquals(true, a.equals(b)); + assertEquals(true, a.hashCode() == b.hashCode()); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_hour_differs(int h, int m, int s, int n, ZoneOffset ignored) { h = (h == 23 ? 22 : h); OffsetTime a = OffsetTime.of(h, m, s, n, OFFSET_PONE); OffsetTime b = OffsetTime.of(h + 1, m, s, n, OFFSET_PONE); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_minute_differs(int h, int m, int s, int n, ZoneOffset ignored) { m = (m == 59 ? 58 : m); OffsetTime a = OffsetTime.of(h, m, s, n, OFFSET_PONE); OffsetTime b = OffsetTime.of(h, m + 1, s, n, OFFSET_PONE); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_second_differs(int h, int m, int s, int n, ZoneOffset ignored) { s = (s == 59 ? 58 : s); OffsetTime a = OffsetTime.of(h, m, s, n, OFFSET_PONE); OffsetTime b = OffsetTime.of(h, m, s + 1, n, OFFSET_PONE); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_nano_differs(int h, int m, int s, int n, ZoneOffset ignored) { n = (n == 999999999 ? 999999998 : n); OffsetTime a = OffsetTime.of(h, m, s, n, OFFSET_PONE); OffsetTime b = OffsetTime.of(h, m, s, n + 1, OFFSET_PONE); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_offset_differs(int h, int m, int s, int n, ZoneOffset ignored) { OffsetTime a = OffsetTime.of(h, m, s, n, OFFSET_PONE); OffsetTime b = OffsetTime.of(h, m, s, n, OFFSET_PTWO); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } @Test public void test_equals_itself_true() { - assertEquals(TEST_11_30_59_500_PONE.equals(TEST_11_30_59_500_PONE), true); + assertEquals(true, TEST_11_30_59_500_PONE.equals(TEST_11_30_59_500_PONE)); } @Test public void test_equals_string_false() { - assertEquals(TEST_11_30_59_500_PONE.equals("2007-07-15"), false); + assertEquals(false, TEST_11_30_59_500_PONE.equals("2007-07-15")); } @Test public void test_equals_null_false() { - assertEquals(TEST_11_30_59_500_PONE.equals(null), false); + assertEquals(false, TEST_11_30_59_500_PONE.equals(null)); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="sampleToString") Object[][] provider_sampleToString() { return new Object[][] { {11, 30, 59, 0, "Z", "11:30:59Z"}, @@ -1441,11 +1480,12 @@ public class TCKOffsetTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_toString(int h, int m, int s, int n, String offsetId, String expected) { OffsetTime t = OffsetTime.of(h, m, s, n, ZoneOffset.of(offsetId)); String str = t.toString(); - assertEquals(str, expected); + assertEquals(expected, str); } } diff --git a/test/jdk/java/time/tck/java/time/TCKPeriod.java b/test/jdk/java/time/tck/java/time/TCKPeriod.java index 7743512002f..2d85482d610 100644 --- a/test/jdk/java/time/tck/java/time/TCKPeriod.java +++ b/test/jdk/java/time/tck/java/time/TCKPeriod.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -62,7 +62,8 @@ package tck.java.time; import static java.time.temporal.ChronoUnit.DAYS; import static java.time.temporal.ChronoUnit.HOURS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DateTimeException; import java.time.Duration; @@ -79,13 +80,16 @@ import java.util.Collections; import java.util.List; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test Period. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKPeriod extends AbstractTCKTest { //----------------------------------------------------------------------- @@ -191,78 +195,81 @@ public class TCKPeriod extends AbstractTCKTest { assertPeriod(Period.from(amount), 23, 0, 45); } - @Test(expectedExceptions = ArithmeticException.class) + @Test public void factory_from_TemporalAmount_Years_tooBig() { - TemporalAmount amount = new TemporalAmount() { - @Override - public long get(TemporalUnit unit) { - return ((long) (Integer.MAX_VALUE)) + 1; - } - @Override - public List getUnits() { - return Collections.singletonList(YEARS); - } - @Override - public Temporal addTo(Temporal temporal) { - throw new UnsupportedOperationException(); - } - @Override - public Temporal subtractFrom(Temporal temporal) { - throw new UnsupportedOperationException(); - } - }; - Period.from(amount); - } - - @Test(expectedExceptions = DateTimeException.class) - public void factory_from_TemporalAmount_DaysHours() { - TemporalAmount amount = new TemporalAmount() { - @Override - public long get(TemporalUnit unit) { - if (unit == DAYS) { - return 1; - } else { - return 2; + Assertions.assertThrows(ArithmeticException.class, () -> { + TemporalAmount amount = new TemporalAmount() { + @Override + public long get(TemporalUnit unit) { + return ((long) (Integer.MAX_VALUE)) + 1; } - } - @Override - public List getUnits() { - List list = new ArrayList<>(); - list.add(DAYS); - list.add(HOURS); - return list; - } - @Override - public Temporal addTo(Temporal temporal) { - throw new UnsupportedOperationException(); - } - @Override - public Temporal subtractFrom(Temporal temporal) { - throw new UnsupportedOperationException(); - } - }; - Period.from(amount); + @Override + public List getUnits() { + return Collections.singletonList(YEARS); + } + @Override + public Temporal addTo(Temporal temporal) { + throw new UnsupportedOperationException(); + } + @Override + public Temporal subtractFrom(Temporal temporal) { + throw new UnsupportedOperationException(); + } + }; + Period.from(amount); + }); } - @Test(expectedExceptions = DateTimeException.class) + @Test + public void factory_from_TemporalAmount_DaysHours() { + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAmount amount = new TemporalAmount() { + @Override + public long get(TemporalUnit unit) { + if (unit == DAYS) { + return 1; + } else { + return 2; + } + } + @Override + public List getUnits() { + List list = new ArrayList<>(); + list.add(DAYS); + list.add(HOURS); + return list; + } + @Override + public Temporal addTo(Temporal temporal) { + throw new UnsupportedOperationException(); + } + @Override + public Temporal subtractFrom(Temporal temporal) { + throw new UnsupportedOperationException(); + } + }; + Period.from(amount); + }); + } + + @Test public void factory_from_TemporalAmount_NonISO() { - Period.from(ThaiBuddhistChronology.INSTANCE.period(1, 1, 1)); + Assertions.assertThrows(DateTimeException.class, () -> Period.from(ThaiBuddhistChronology.INSTANCE.period(1, 1, 1))); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void factory_from_TemporalAmount_Duration() { - Period.from(Duration.ZERO); + Assertions.assertThrows(DateTimeException.class, () -> Period.from(Duration.ZERO)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void factory_from_TemporalAmount_null() { - Period.from(null); + Assertions.assertThrows(NullPointerException.class, () -> Period.from(null)); } //----------------------------------------------------------------------- // parse(String) //----------------------------------------------------------------------- - @DataProvider(name="parseSuccess") Object[][] data_factory_parseSuccess() { return new Object[][] { {"P1Y", Period.ofYears(1)}, @@ -335,40 +342,43 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_factory_parseSuccess") public void factory_parse(String text, Period expected) { Period p = Period.parse(text); - assertEquals(p, expected); + assertEquals(expected, p); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_factory_parseSuccess") public void factory_parse_plus(String text, Period expected) { Period p = Period.parse("+" + text); - assertEquals(p, expected); + assertEquals(expected, p); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_factory_parseSuccess") public void factory_parse_minus(String text, Period expected) { Period p = null; try { p = Period.parse("-" + text); } catch (DateTimeParseException ex) { - assertEquals(expected.getYears() == Integer.MIN_VALUE || + assertEquals(true, expected.getYears() == Integer.MIN_VALUE || expected.getMonths() == Integer.MIN_VALUE || - expected.getDays() == Integer.MIN_VALUE, true); + expected.getDays() == Integer.MIN_VALUE); return; } // not inside try/catch or it breaks test - assertEquals(p, expected.negated()); + assertEquals(expected.negated(), p); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_factory_parseSuccess") public void factory_parse_lowerCase(String text, Period expected) { Period p = Period.parse(text.toLowerCase(Locale.ENGLISH)); - assertEquals(p, expected); + assertEquals(expected, p); } - @DataProvider(name="parseFailure") Object[][] data_parseFailure() { return new Object[][] { {""}, @@ -417,25 +427,27 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="parseFailure", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("data_parseFailure") public void factory_parseFailures(String text) { - try { - Period.parse(text); - } catch (DateTimeParseException ex) { - assertEquals(ex.getParsedString(), text); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + try { + Period.parse(text); + } catch (DateTimeParseException ex) { + assertEquals(text, ex.getParsedString()); + throw ex; + } + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_null() { - Period.parse(null); + Assertions.assertThrows(NullPointerException.class, () -> Period.parse(null)); } //----------------------------------------------------------------------- // between(LocalDate,LocalDate) //----------------------------------------------------------------------- - @DataProvider(name="between") Object[][] data_between() { return new Object[][] { {2010, 1, 1, 2010, 1, 1, 0, 0, 0}, @@ -522,7 +534,8 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="between") + @ParameterizedTest + @MethodSource("data_between") public void factory_between_LocalDate(int y1, int m1, int d1, int y2, int m2, int d2, int ye, int me, int de) { LocalDate start = LocalDate.of(y1, m1, d1); LocalDate end = LocalDate.of(y2, m2, d2); @@ -531,14 +544,14 @@ public class TCKPeriod extends AbstractTCKTest { //assertEquals(start.plus(test), end); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_between_LocalDate_nullFirst() { - Period.between((LocalDate) null, LocalDate.of(2010, 1, 1)); + Assertions.assertThrows(NullPointerException.class, () -> Period.between((LocalDate) null, LocalDate.of(2010, 1, 1))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_between_LocalDate_nullSecond() { - Period.between(LocalDate.of(2010, 1, 1), (LocalDate) null); + Assertions.assertThrows(NullPointerException.class, () -> Period.between(LocalDate.of(2010, 1, 1), (LocalDate) null)); } //----------------------------------------------------------------------- @@ -546,11 +559,11 @@ public class TCKPeriod extends AbstractTCKTest { //----------------------------------------------------------------------- @Test public void test_isZero() { - assertEquals(Period.of(0, 0, 0).isZero(), true); - assertEquals(Period.of(1, 2, 3).isZero(), false); - assertEquals(Period.of(1, 0, 0).isZero(), false); - assertEquals(Period.of(0, 2, 0).isZero(), false); - assertEquals(Period.of(0, 0, 3).isZero(), false); + assertEquals(true, Period.of(0, 0, 0).isZero()); + assertEquals(false, Period.of(1, 2, 3).isZero()); + assertEquals(false, Period.of(1, 0, 0).isZero()); + assertEquals(false, Period.of(0, 2, 0).isZero()); + assertEquals(false, Period.of(0, 0, 3).isZero()); } //----------------------------------------------------------------------- @@ -558,19 +571,19 @@ public class TCKPeriod extends AbstractTCKTest { //----------------------------------------------------------------------- @Test public void test_isPositive() { - assertEquals(Period.of(0, 0, 0).isNegative(), false); - assertEquals(Period.of(1, 2, 3).isNegative(), false); - assertEquals(Period.of(1, 0, 0).isNegative(), false); - assertEquals(Period.of(0, 2, 0).isNegative(), false); - assertEquals(Period.of(0, 0, 3).isNegative(), false); + assertEquals(false, Period.of(0, 0, 0).isNegative()); + assertEquals(false, Period.of(1, 2, 3).isNegative()); + assertEquals(false, Period.of(1, 0, 0).isNegative()); + assertEquals(false, Period.of(0, 2, 0).isNegative()); + assertEquals(false, Period.of(0, 0, 3).isNegative()); - assertEquals(Period.of(-1, -2, -3).isNegative(), true); - assertEquals(Period.of(-1, -2, 3).isNegative(), true); - assertEquals(Period.of(1, -2, -3).isNegative(), true); - assertEquals(Period.of(-1, 2, -3).isNegative(), true); - assertEquals(Period.of(-1, 2, 3).isNegative(), true); - assertEquals(Period.of(1, -2, 3).isNegative(), true); - assertEquals(Period.of(1, 2, -3).isNegative(), true); + assertEquals(true, Period.of(-1, -2, -3).isNegative()); + assertEquals(true, Period.of(-1, -2, 3).isNegative()); + assertEquals(true, Period.of(1, -2, -3).isNegative()); + assertEquals(true, Period.of(-1, 2, -3).isNegative()); + assertEquals(true, Period.of(-1, 2, 3).isNegative()); + assertEquals(true, Period.of(1, -2, 3).isNegative()); + assertEquals(true, Period.of(1, 2, -3).isNegative()); } //----------------------------------------------------------------------- @@ -612,7 +625,6 @@ public class TCKPeriod extends AbstractTCKTest { //----------------------------------------------------------------------- // plus(Period) //----------------------------------------------------------------------- - @DataProvider(name="plus") Object[][] data_plus() { return new Object[][] { {pymd(0, 0, 0), pymd(0, 0, 0), pymd(0, 0, 0)}, @@ -630,44 +642,47 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="plus") + @ParameterizedTest + @MethodSource("data_plus") public void test_plus_TemporalAmount(Period base, Period add, Period expected) { - assertEquals(base.plus(add), expected); + assertEquals(expected, base.plus(add)); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_plus_TemporalAmount_nonISO() { - pymd(4, 5, 6).plus(ThaiBuddhistChronology.INSTANCE.period(1, 0, 0)); + Assertions.assertThrows(DateTimeException.class, () -> pymd(4, 5, 6).plus(ThaiBuddhistChronology.INSTANCE.period(1, 0, 0))); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_plus_TemporalAmount_DaysHours() { - TemporalAmount amount = new TemporalAmount() { - @Override - public long get(TemporalUnit unit) { - if (unit == DAYS) { - return 1; - } else { - return 2; + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAmount amount = new TemporalAmount() { + @Override + public long get(TemporalUnit unit) { + if (unit == DAYS) { + return 1; + } else { + return 2; + } } - } - @Override - public List getUnits() { - List list = new ArrayList<>(); - list.add(DAYS); - list.add(HOURS); - return list; - } - @Override - public Temporal addTo(Temporal temporal) { - throw new UnsupportedOperationException(); - } - @Override - public Temporal subtractFrom(Temporal temporal) { - throw new UnsupportedOperationException(); - } - }; - pymd(4, 5, 6).plus(amount); + @Override + public List getUnits() { + List list = new ArrayList<>(); + list.add(DAYS); + list.add(HOURS); + return list; + } + @Override + public Temporal addTo(Temporal temporal) { + throw new UnsupportedOperationException(); + } + @Override + public Temporal subtractFrom(Temporal temporal) { + throw new UnsupportedOperationException(); + } + }; + pymd(4, 5, 6).plus(amount); + }); } //----------------------------------------------------------------------- @@ -686,16 +701,20 @@ public class TCKPeriod extends AbstractTCKTest { assertPeriod(Period.of(1, 2, 3).plus(Period.ofYears(-1)), 0, 2, 3); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_plusYears_overflowTooBig() { - Period test = Period.ofYears(Integer.MAX_VALUE); - test.plusYears(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofYears(Integer.MAX_VALUE); + test.plusYears(1); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_plusYears_overflowTooSmall() { - Period test = Period.ofYears(Integer.MIN_VALUE); - test.plusYears(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofYears(Integer.MIN_VALUE); + test.plusYears(-1); + }); } //----------------------------------------------------------------------- @@ -714,16 +733,20 @@ public class TCKPeriod extends AbstractTCKTest { assertPeriod(Period.of(1, 2, 3).plus(Period.ofMonths(-2)), 1, 0, 3); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_plusMonths_overflowTooBig() { - Period test = Period.ofMonths(Integer.MAX_VALUE); - test.plusMonths(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofMonths(Integer.MAX_VALUE); + test.plusMonths(1); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_plusMonths_overflowTooSmall() { - Period test = Period.ofMonths(Integer.MIN_VALUE); - test.plusMonths(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofMonths(Integer.MIN_VALUE); + test.plusMonths(-1); + }); } //----------------------------------------------------------------------- @@ -742,22 +765,25 @@ public class TCKPeriod extends AbstractTCKTest { assertPeriod(Period.of(1, 2, 3).plus(Period.ofDays(-3)), 1, 2, 0); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_plusDays_overflowTooBig() { - Period test = Period.ofDays(Integer.MAX_VALUE); - test.plusDays(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofDays(Integer.MAX_VALUE); + test.plusDays(1); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_plusDays_overflowTooSmall() { - Period test = Period.ofDays(Integer.MIN_VALUE); - test.plusDays(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofDays(Integer.MIN_VALUE); + test.plusDays(-1); + }); } //----------------------------------------------------------------------- // minus(Period) //----------------------------------------------------------------------- - @DataProvider(name="minus") Object[][] data_minus() { return new Object[][] { {pymd(0, 0, 0), pymd(0, 0, 0), pymd(0, 0, 0)}, @@ -775,44 +801,47 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="minus") + @ParameterizedTest + @MethodSource("data_minus") public void test_minus_TemporalAmount(Period base, Period subtract, Period expected) { - assertEquals(base.minus(subtract), expected); + assertEquals(expected, base.minus(subtract)); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_minus_TemporalAmount_nonISO() { - pymd(4, 5, 6).minus(ThaiBuddhistChronology.INSTANCE.period(1, 0, 0)); + Assertions.assertThrows(DateTimeException.class, () -> pymd(4, 5, 6).minus(ThaiBuddhistChronology.INSTANCE.period(1, 0, 0))); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_minus_TemporalAmount_DaysHours() { - TemporalAmount amount = new TemporalAmount() { - @Override - public long get(TemporalUnit unit) { - if (unit == DAYS) { - return 1; - } else { - return 2; + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAmount amount = new TemporalAmount() { + @Override + public long get(TemporalUnit unit) { + if (unit == DAYS) { + return 1; + } else { + return 2; + } } - } - @Override - public List getUnits() { - List list = new ArrayList<>(); - list.add(DAYS); - list.add(HOURS); - return list; - } - @Override - public Temporal addTo(Temporal temporal) { - throw new UnsupportedOperationException(); - } - @Override - public Temporal subtractFrom(Temporal temporal) { - throw new UnsupportedOperationException(); - } - }; - pymd(4, 5, 6).minus(amount); + @Override + public List getUnits() { + List list = new ArrayList<>(); + list.add(DAYS); + list.add(HOURS); + return list; + } + @Override + public Temporal addTo(Temporal temporal) { + throw new UnsupportedOperationException(); + } + @Override + public Temporal subtractFrom(Temporal temporal) { + throw new UnsupportedOperationException(); + } + }; + pymd(4, 5, 6).minus(amount); + }); } //----------------------------------------------------------------------- @@ -831,16 +860,20 @@ public class TCKPeriod extends AbstractTCKTest { assertPeriod(Period.of(1, 2, 3).minus(Period.ofYears(-1)), 2, 2, 3); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_minusYears_overflowTooBig() { - Period test = Period.ofYears(Integer.MAX_VALUE); - test.minusYears(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofYears(Integer.MAX_VALUE); + test.minusYears(-1); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_minusYears_overflowTooSmall() { - Period test = Period.ofYears(Integer.MIN_VALUE); - test.minusYears(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofYears(Integer.MIN_VALUE); + test.minusYears(1); + }); } //----------------------------------------------------------------------- @@ -859,16 +892,20 @@ public class TCKPeriod extends AbstractTCKTest { assertPeriod(Period.of(1, 2, 3).minus(Period.ofMonths(-2)), 1, 4, 3); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_minusMonths_overflowTooBig() { - Period test = Period.ofMonths(Integer.MAX_VALUE); - test.minusMonths(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofMonths(Integer.MAX_VALUE); + test.minusMonths(-1); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_minusMonths_overflowTooSmall() { - Period test = Period.ofMonths(Integer.MIN_VALUE); - test.minusMonths(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofMonths(Integer.MIN_VALUE); + test.minusMonths(1); + }); } //----------------------------------------------------------------------- @@ -887,16 +924,20 @@ public class TCKPeriod extends AbstractTCKTest { assertPeriod(Period.of(1, 2, 3).minus(Period.ofDays(-3)), 1, 2, 6); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_minusDays_overflowTooBig() { - Period test = Period.ofDays(Integer.MAX_VALUE); - test.minusDays(-1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofDays(Integer.MAX_VALUE); + test.minusDays(-1); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_minusDays_overflowTooSmall() { - Period test = Period.ofDays(Integer.MIN_VALUE); - test.minusDays(1); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofDays(Integer.MIN_VALUE); + test.minusDays(1); + }); } //----------------------------------------------------------------------- @@ -916,16 +957,20 @@ public class TCKPeriod extends AbstractTCKTest { assertPeriod(Period.ZERO.multipliedBy(2), 0, 0, 0); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_multipliedBy_overflowTooBig() { - Period test = Period.ofYears(Integer.MAX_VALUE / 2 + 1); - test.multipliedBy(2); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofYears(Integer.MAX_VALUE / 2 + 1); + test.multipliedBy(2); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_multipliedBy_overflowTooSmall() { - Period test = Period.ofYears(Integer.MIN_VALUE / 2 - 1); - test.multipliedBy(2); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period test = Period.ofYears(Integer.MIN_VALUE / 2 - 1); + test.multipliedBy(2); + }); } //----------------------------------------------------------------------- @@ -941,25 +986,24 @@ public class TCKPeriod extends AbstractTCKTest { -Integer.MAX_VALUE, -Integer.MAX_VALUE, -Integer.MAX_VALUE); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_negated_overflow_years() { - Period.ofYears(Integer.MIN_VALUE).negated(); + Assertions.assertThrows(ArithmeticException.class, () -> Period.ofYears(Integer.MIN_VALUE).negated()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_negated_overflow_months() { - Period.ofMonths(Integer.MIN_VALUE).negated(); + Assertions.assertThrows(ArithmeticException.class, () -> Period.ofMonths(Integer.MIN_VALUE).negated()); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_negated_overflow_days() { - Period.ofDays(Integer.MIN_VALUE).negated(); + Assertions.assertThrows(ArithmeticException.class, () -> Period.ofDays(Integer.MIN_VALUE).negated()); } //----------------------------------------------------------------------- // normalized() //----------------------------------------------------------------------- - @DataProvider(name="normalized") Object[][] data_normalized() { return new Object[][] { {0, 0, 0, 0}, @@ -1002,32 +1046,37 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="normalized") + @ParameterizedTest + @MethodSource("data_normalized") public void test_normalized(int inputYears, int inputMonths, int expectedYears, int expectedMonths) { assertPeriod(Period.of(inputYears, inputMonths, 0).normalized(), expectedYears, expectedMonths, 0); } - @Test(dataProvider="normalized") + @ParameterizedTest + @MethodSource("data_normalized") public void test_normalized_daysUnaffected(int inputYears, int inputMonths, int expectedYears, int expectedMonths) { assertPeriod(Period.of(inputYears, inputMonths, 5).normalized(), expectedYears, expectedMonths, 5); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_normalized_min() { - Period base = Period.of(Integer.MIN_VALUE, -12, 0); - base.normalized(); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period base = Period.of(Integer.MIN_VALUE, -12, 0); + base.normalized(); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void test_normalized_max() { - Period base = Period.of(Integer.MAX_VALUE, 12, 0); - base.normalized(); + Assertions.assertThrows(ArithmeticException.class, () -> { + Period base = Period.of(Integer.MAX_VALUE, 12, 0); + base.normalized(); + }); } //----------------------------------------------------------------------- // addTo() //----------------------------------------------------------------------- - @DataProvider(name="addTo") Object[][] data_addTo() { return new Object[][] { {pymd(0, 0, 0), date(2012, 6, 30), date(2012, 6, 30)}, @@ -1056,30 +1105,31 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="addTo") + @ParameterizedTest + @MethodSource("data_addTo") public void test_addTo(Period period, LocalDate baseDate, LocalDate expected) { - assertEquals(period.addTo(baseDate), expected); + assertEquals(expected, period.addTo(baseDate)); } - @Test(dataProvider="addTo") + @ParameterizedTest + @MethodSource("data_addTo") public void test_addTo_usingLocalDatePlus(Period period, LocalDate baseDate, LocalDate expected) { - assertEquals(baseDate.plus(period), expected); + assertEquals(expected, baseDate.plus(period)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_addTo_nullZero() { - Period.ZERO.addTo(null); + Assertions.assertThrows(NullPointerException.class, () -> Period.ZERO.addTo(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_addTo_nullNonZero() { - Period.ofDays(2).addTo(null); + Assertions.assertThrows(NullPointerException.class, () -> Period.ofDays(2).addTo(null)); } //----------------------------------------------------------------------- // subtractFrom() //----------------------------------------------------------------------- - @DataProvider(name="subtractFrom") Object[][] data_subtractFrom() { return new Object[][] { {pymd(0, 0, 0), date(2012, 6, 30), date(2012, 6, 30)}, @@ -1109,24 +1159,26 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="subtractFrom") + @ParameterizedTest + @MethodSource("data_subtractFrom") public void test_subtractFrom(Period period, LocalDate baseDate, LocalDate expected) { - assertEquals(period.subtractFrom(baseDate), expected); + assertEquals(expected, period.subtractFrom(baseDate)); } - @Test(dataProvider="subtractFrom") + @ParameterizedTest + @MethodSource("data_subtractFrom") public void test_subtractFrom_usingLocalDateMinus(Period period, LocalDate baseDate, LocalDate expected) { - assertEquals(baseDate.minus(period), expected); + assertEquals(expected, baseDate.minus(period)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_subtractFrom_nullZero() { - Period.ZERO.subtractFrom(null); + Assertions.assertThrows(NullPointerException.class, () -> Period.ZERO.subtractFrom(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_subtractFrom_nullNonZero() { - Period.ofDays(2).subtractFrom(null); + Assertions.assertThrows(NullPointerException.class, () -> Period.ofDays(2).subtractFrom(null)); } //----------------------------------------------------------------------- @@ -1136,14 +1188,13 @@ public class TCKPeriod extends AbstractTCKTest { public void test_Period_getUnits() { Period period = Period.of(2012, 1, 1); List units = period.getUnits(); - assertEquals(units.size(), 3, "Period.getUnits should return 3 units"); - assertEquals(units.get(0), ChronoUnit.YEARS, "Period.getUnits contains ChronoUnit.YEARS"); - assertEquals(units.get(1), ChronoUnit.MONTHS, "Period.getUnits contains ChronoUnit.MONTHS"); - assertEquals(units.get(2), ChronoUnit.DAYS, "Period.getUnits contains ChronoUnit.DAYS"); + assertEquals(3, units.size(), "Period.getUnits should return 3 units"); + assertEquals(ChronoUnit.YEARS, units.get(0), "Period.getUnits contains ChronoUnit.YEARS"); + assertEquals(ChronoUnit.MONTHS, units.get(1), "Period.getUnits contains ChronoUnit.MONTHS"); + assertEquals(ChronoUnit.DAYS, units.get(2), "Period.getUnits contains ChronoUnit.DAYS"); } - @DataProvider(name="GoodTemporalUnit") Object[][] data_goodTemporalUnit() { return new Object[][] { {2, ChronoUnit.DAYS}, @@ -1152,14 +1203,14 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="GoodTemporalUnit") + @ParameterizedTest + @MethodSource("data_goodTemporalUnit") public void test_good_getUnit(long amount, TemporalUnit unit) { Period period = Period.of(2, 2, 2); long actual = period.get(unit); - assertEquals(actual, amount, "Value of unit: " + unit); + assertEquals(amount, actual, "Value of unit: " + unit); } - @DataProvider(name="BadTemporalUnit") Object[][] data_badTemporalUnit() { return new Object[][] { {ChronoUnit.MICROS}, @@ -1171,64 +1222,71 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="BadTemporalUnit", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_badTemporalUnit") public void test_bad_getUnit(TemporalUnit unit) { - Period period = Period.of(2, 2, 2); - period.get(unit); + Assertions.assertThrows(DateTimeException.class, () -> { + Period period = Period.of(2, 2, 2); + period.get(unit); + }); } //----------------------------------------------------------------------- // equals() / hashCode() //----------------------------------------------------------------------- + @Test public void test_equals() { - assertEquals(Period.of(1, 0, 0).equals(Period.ofYears(1)), true); - assertEquals(Period.of(0, 1, 0).equals(Period.ofMonths(1)), true); - assertEquals(Period.of(0, 0, 1).equals(Period.ofDays(1)), true); - assertEquals(Period.of(1, 2, 3).equals(Period.of(1, 2, 3)), true); + assertEquals(true, Period.of(1, 0, 0).equals(Period.ofYears(1))); + assertEquals(true, Period.of(0, 1, 0).equals(Period.ofMonths(1))); + assertEquals(true, Period.of(0, 0, 1).equals(Period.ofDays(1))); + assertEquals(true, Period.of(1, 2, 3).equals(Period.of(1, 2, 3))); - assertEquals(Period.ofYears(1).equals(Period.ofYears(1)), true); - assertEquals(Period.ofYears(1).equals(Period.ofYears(2)), false); + assertEquals(true, Period.ofYears(1).equals(Period.ofYears(1))); + assertEquals(false, Period.ofYears(1).equals(Period.ofYears(2))); - assertEquals(Period.ofMonths(1).equals(Period.ofMonths(1)), true); - assertEquals(Period.ofMonths(1).equals(Period.ofMonths(2)), false); + assertEquals(true, Period.ofMonths(1).equals(Period.ofMonths(1))); + assertEquals(false, Period.ofMonths(1).equals(Period.ofMonths(2))); - assertEquals(Period.ofDays(1).equals(Period.ofDays(1)), true); - assertEquals(Period.ofDays(1).equals(Period.ofDays(2)), false); + assertEquals(true, Period.ofDays(1).equals(Period.ofDays(1))); + assertEquals(false, Period.ofDays(1).equals(Period.ofDays(2))); - assertEquals(Period.of(1, 2, 3).equals(Period.of(0, 2, 3)), false); - assertEquals(Period.of(1, 2, 3).equals(Period.of(1, 0, 3)), false); - assertEquals(Period.of(1, 2, 3).equals(Period.of(1, 2, 0)), false); + assertEquals(false, Period.of(1, 2, 3).equals(Period.of(0, 2, 3))); + assertEquals(false, Period.of(1, 2, 3).equals(Period.of(1, 0, 3))); + assertEquals(false, Period.of(1, 2, 3).equals(Period.of(1, 2, 0))); } + @Test public void test_equals_self() { Period test = Period.of(1, 2, 3); - assertEquals(test.equals(test), true); + assertEquals(true, test.equals(test)); } + @Test public void test_equals_null() { Period test = Period.of(1, 2, 3); - assertEquals(test.equals(null), false); + assertEquals(false, test.equals(null)); } + @Test public void test_equals_otherClass() { Period test = Period.of(1, 2, 3); - assertEquals(test.equals(""), false); + assertEquals(false, test.equals("")); } //----------------------------------------------------------------------- + @Test public void test_hashCode() { Period test5 = Period.ofDays(5); Period test6 = Period.ofDays(6); Period test5M = Period.ofMonths(5); Period test5Y = Period.ofYears(5); - assertEquals(test5.hashCode() == test5.hashCode(), true); - assertEquals(test5.hashCode() == test6.hashCode(), false); + assertEquals(true, test5.hashCode() == test5.hashCode()); + assertEquals(false, test5.hashCode() == test6.hashCode()); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="toStringAndParse") Object[][] data_toString() { return new Object[][] { {Period.ZERO, "P0D"}, @@ -1242,22 +1300,24 @@ public class TCKPeriod extends AbstractTCKTest { }; } - @Test(dataProvider="toStringAndParse") + @ParameterizedTest + @MethodSource("data_toString") public void test_toString(Period input, String expected) { - assertEquals(input.toString(), expected); + assertEquals(expected, input.toString()); } - @Test(dataProvider="toStringAndParse") + @ParameterizedTest + @MethodSource("data_toString") public void test_parse(Period test, String expected) { - assertEquals(Period.parse(expected), test); + assertEquals(test, Period.parse(expected)); } //----------------------------------------------------------------------- private void assertPeriod(Period test, int y, int m, int d) { - assertEquals(test.getYears(), y, "years"); - assertEquals(test.getMonths(), m, "months"); - assertEquals(test.getDays(), d, "days"); - assertEquals(test.toTotalMonths(), y * 12L + m, "totalMonths"); + assertEquals(y, test.getYears(), "years"); + assertEquals(m, test.getMonths(), "months"); + assertEquals(d, test.getDays(), "days"); + assertEquals(y * 12L + m, test.toTotalMonths(), "totalMonths"); } private static Period pymd(int y, int m, int d) { diff --git a/test/jdk/java/time/tck/java/time/TCKYear.java b/test/jdk/java/time/tck/java/time/TCKYear.java index b86f3b567ac..7e4d15e146d 100644 --- a/test/jdk/java/time/tck/java/time/TCKYear.java +++ b/test/jdk/java/time/tck/java/time/TCKYear.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -68,9 +68,10 @@ import static java.time.temporal.ChronoUnit.DECADES; import static java.time.temporal.ChronoUnit.MILLENNIA; import static java.time.temporal.ChronoUnit.MONTHS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; @@ -107,19 +108,22 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test Year. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKYear extends AbstractDateTimeTest { private static final Year TEST_2008 = Year.of(2008); - @BeforeMethod + @BeforeEach public void setUp() { } @@ -164,15 +168,15 @@ public class TCKYear extends AbstractDateTimeTest { expected = Year.now(Clock.systemDefaultZone()); test = Year.now(); } - assertEquals(test, expected); + assertEquals(expected, test); } //----------------------------------------------------------------------- // now(ZoneId) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_ZoneId_nullZoneId() { - Year.now((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> Year.now((ZoneId) null)); } @Test @@ -187,7 +191,7 @@ public class TCKYear extends AbstractDateTimeTest { expected = Year.now(Clock.system(zone)); test = Year.now(zone); } - assertEquals(test, expected); + assertEquals(expected, test); } //----------------------------------------------------------------------- @@ -198,12 +202,12 @@ public class TCKYear extends AbstractDateTimeTest { Instant instant = OffsetDateTime.of(LocalDate.of(2010, 12, 31), LocalTime.of(0, 0), ZoneOffset.UTC).toInstant(); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); Year test = Year.now(clock); - assertEquals(test.getValue(), 2010); + assertEquals(2010, test.getValue()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullClock() { - Year.now((Clock) null); + Assertions.assertThrows(NullPointerException.class, () -> Year.now((Clock) null)); } //----------------------------------------------------------------------- @@ -211,41 +215,40 @@ public class TCKYear extends AbstractDateTimeTest { public void test_factory_int_singleton() { for (int i = -4; i <= 2104; i++) { Year test = Year.of(i); - assertEquals(test.getValue(), i); - assertEquals(Year.of(i), test); + assertEquals(i, test.getValue()); + assertEquals(test, Year.of(i)); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_tooLow() { - Year.of(Year.MIN_VALUE - 1); + Assertions.assertThrows(DateTimeException.class, () -> Year.of(Year.MIN_VALUE - 1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_tooHigh() { - Year.of(Year.MAX_VALUE + 1); + Assertions.assertThrows(DateTimeException.class, () -> Year.of(Year.MAX_VALUE + 1)); } //----------------------------------------------------------------------- @Test public void test_from_TemporalAccessor() { - assertEquals(Year.from(LocalDate.of(2007, 7, 15)), Year.of(2007)); + assertEquals(Year.of(2007), Year.from(LocalDate.of(2007, 7, 15))); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_from_TemporalAccessor_invalid_noDerive() { - Year.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> Year.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_from_TemporalAccessor_null() { - Year.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> Year.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- // parse() //----------------------------------------------------------------------- - @DataProvider(name="goodParseData") Object[][] provider_goodParseData() { return new Object[][] { {"9999", Year.of(9999)}, @@ -284,13 +287,13 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="goodParseData") + @ParameterizedTest + @MethodSource("provider_goodParseData") public void factory_parse_success(String text, Year expected) { Year year = Year.parse(text); - assertEquals(year, expected); + assertEquals(expected, year); } - @DataProvider(name="badParseData") Object[][] provider_badParseData() { return new Object[][] { {"", 0}, @@ -309,21 +312,24 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="badParseData", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("provider_badParseData") public void factory_parse_fail(String text, int pos) { - try { - Year.parse(text); - fail(String.format("Parse should have failed for %s at position %d", text, pos)); - } catch (DateTimeParseException ex) { - assertEquals(ex.getParsedString(), text); - assertEquals(ex.getErrorIndex(), pos); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + try { + Year.parse(text); + fail(String.format("Parse should have failed for %s at position %d", text, pos)); + } catch (DateTimeParseException ex) { + assertEquals(text, ex.getParsedString()); + assertEquals(pos, ex.getErrorIndex()); + throw ex; + } + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_nullText() { - Year.parse(null); + Assertions.assertThrows(NullPointerException.class, () -> Year.parse(null)); } //----------------------------------------------------------------------- @@ -333,18 +339,20 @@ public class TCKYear extends AbstractDateTimeTest { public void factory_parse_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y"); Year test = Year.parse("2010", f); - assertEquals(test, Year.of(2010)); + assertEquals(Year.of(2010), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullText() { - DateTimeFormatter f = DateTimeFormatter.ofPattern("y"); - Year.parse((String) null, f); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter f = DateTimeFormatter.ofPattern("y"); + Year.parse((String) null, f); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullFormatter() { - Year.parse("ANY", null); + Assertions.assertThrows(NullPointerException.class, () -> Year.parse("ANY", null)); } //----------------------------------------------------------------------- @@ -352,37 +360,37 @@ public class TCKYear extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(TEST_2008.isSupported((TemporalField) null), false); - assertEquals(TEST_2008.isSupported(ChronoField.NANO_OF_SECOND), false); - assertEquals(TEST_2008.isSupported(ChronoField.NANO_OF_DAY), false); - assertEquals(TEST_2008.isSupported(ChronoField.MICRO_OF_SECOND), false); - assertEquals(TEST_2008.isSupported(ChronoField.MICRO_OF_DAY), false); - assertEquals(TEST_2008.isSupported(ChronoField.MILLI_OF_SECOND), false); - assertEquals(TEST_2008.isSupported(ChronoField.MILLI_OF_DAY), false); - assertEquals(TEST_2008.isSupported(ChronoField.SECOND_OF_MINUTE), false); - assertEquals(TEST_2008.isSupported(ChronoField.SECOND_OF_DAY), false); - assertEquals(TEST_2008.isSupported(ChronoField.MINUTE_OF_HOUR), false); - assertEquals(TEST_2008.isSupported(ChronoField.MINUTE_OF_DAY), false); - assertEquals(TEST_2008.isSupported(ChronoField.HOUR_OF_AMPM), false); - assertEquals(TEST_2008.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), false); - assertEquals(TEST_2008.isSupported(ChronoField.HOUR_OF_DAY), false); - assertEquals(TEST_2008.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), false); - assertEquals(TEST_2008.isSupported(ChronoField.AMPM_OF_DAY), false); - assertEquals(TEST_2008.isSupported(ChronoField.DAY_OF_WEEK), false); - assertEquals(TEST_2008.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), false); - assertEquals(TEST_2008.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), false); - assertEquals(TEST_2008.isSupported(ChronoField.DAY_OF_MONTH), false); - assertEquals(TEST_2008.isSupported(ChronoField.DAY_OF_YEAR), false); - assertEquals(TEST_2008.isSupported(ChronoField.EPOCH_DAY), false); - assertEquals(TEST_2008.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), false); - assertEquals(TEST_2008.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), false); - assertEquals(TEST_2008.isSupported(ChronoField.MONTH_OF_YEAR), false); - assertEquals(TEST_2008.isSupported(ChronoField.PROLEPTIC_MONTH), false); - assertEquals(TEST_2008.isSupported(ChronoField.YEAR), true); - assertEquals(TEST_2008.isSupported(ChronoField.YEAR_OF_ERA), true); - assertEquals(TEST_2008.isSupported(ChronoField.ERA), true); - assertEquals(TEST_2008.isSupported(ChronoField.INSTANT_SECONDS), false); - assertEquals(TEST_2008.isSupported(ChronoField.OFFSET_SECONDS), false); + assertEquals(false, TEST_2008.isSupported((TemporalField) null)); + assertEquals(false, TEST_2008.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(false, TEST_2008.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(false, TEST_2008.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(false, TEST_2008.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(false, TEST_2008.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(false, TEST_2008.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(false, TEST_2008.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(false, TEST_2008.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(false, TEST_2008.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(false, TEST_2008.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(false, TEST_2008.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(false, TEST_2008.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(false, TEST_2008.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(false, TEST_2008.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(false, TEST_2008.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(false, TEST_2008.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(false, TEST_2008.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(false, TEST_2008.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(false, TEST_2008.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(false, TEST_2008.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(false, TEST_2008.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(false, TEST_2008.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(false, TEST_2008.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(false, TEST_2008.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(false, TEST_2008.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(true, TEST_2008.isSupported(ChronoField.YEAR)); + assertEquals(true, TEST_2008.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(true, TEST_2008.isSupported(ChronoField.ERA)); + assertEquals(false, TEST_2008.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(false, TEST_2008.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -390,23 +398,23 @@ public class TCKYear extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalUnit() { - assertEquals(TEST_2008.isSupported((TemporalUnit) null), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.NANOS), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.MICROS), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.MILLIS), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.SECONDS), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.MINUTES), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.HOURS), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.HALF_DAYS), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.DAYS), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.WEEKS), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.MONTHS), false); - assertEquals(TEST_2008.isSupported(ChronoUnit.YEARS), true); - assertEquals(TEST_2008.isSupported(ChronoUnit.DECADES), true); - assertEquals(TEST_2008.isSupported(ChronoUnit.CENTURIES), true); - assertEquals(TEST_2008.isSupported(ChronoUnit.MILLENNIA), true); - assertEquals(TEST_2008.isSupported(ChronoUnit.ERAS), true); - assertEquals(TEST_2008.isSupported(ChronoUnit.FOREVER), false); + assertEquals(false, TEST_2008.isSupported((TemporalUnit) null)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.NANOS)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.MICROS)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.MILLIS)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.SECONDS)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.MINUTES)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.HOURS)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.HALF_DAYS)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.DAYS)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.WEEKS)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.MONTHS)); + assertEquals(true, TEST_2008.isSupported(ChronoUnit.YEARS)); + assertEquals(true, TEST_2008.isSupported(ChronoUnit.DECADES)); + assertEquals(true, TEST_2008.isSupported(ChronoUnit.CENTURIES)); + assertEquals(true, TEST_2008.isSupported(ChronoUnit.MILLENNIA)); + assertEquals(true, TEST_2008.isSupported(ChronoUnit.ERAS)); + assertEquals(false, TEST_2008.isSupported(ChronoUnit.FOREVER)); } //----------------------------------------------------------------------- @@ -414,22 +422,21 @@ public class TCKYear extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_get_TemporalField() { - assertEquals(TEST_2008.get(ChronoField.YEAR), 2008); - assertEquals(TEST_2008.get(ChronoField.YEAR_OF_ERA), 2008); - assertEquals(TEST_2008.get(ChronoField.ERA), 1); + assertEquals(2008, TEST_2008.get(ChronoField.YEAR)); + assertEquals(2008, TEST_2008.get(ChronoField.YEAR_OF_ERA)); + assertEquals(1, TEST_2008.get(ChronoField.ERA)); } @Test public void test_getLong_TemporalField() { - assertEquals(TEST_2008.getLong(ChronoField.YEAR), 2008); - assertEquals(TEST_2008.getLong(ChronoField.YEAR_OF_ERA), 2008); - assertEquals(TEST_2008.getLong(ChronoField.ERA), 1); + assertEquals(2008, TEST_2008.getLong(ChronoField.YEAR)); + assertEquals(2008, TEST_2008.getLong(ChronoField.YEAR_OF_ERA)); + assertEquals(1, TEST_2008.getLong(ChronoField.ERA)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {TEST_2008, TemporalQueries.chronology(), IsoChronology.INSTANCE}, @@ -442,19 +449,21 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - TEST_2008.query(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008.query(null)); } //----------------------------------------------------------------------- @@ -462,46 +471,45 @@ public class TCKYear extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isLeap() { - assertEquals(Year.of(1999).isLeap(), false); - assertEquals(Year.of(2000).isLeap(), true); - assertEquals(Year.of(2001).isLeap(), false); + assertEquals(false, Year.of(1999).isLeap()); + assertEquals(true, Year.of(2000).isLeap()); + assertEquals(false, Year.of(2001).isLeap()); - assertEquals(Year.of(2007).isLeap(), false); - assertEquals(Year.of(2008).isLeap(), true); - assertEquals(Year.of(2009).isLeap(), false); - assertEquals(Year.of(2010).isLeap(), false); - assertEquals(Year.of(2011).isLeap(), false); - assertEquals(Year.of(2012).isLeap(), true); + assertEquals(false, Year.of(2007).isLeap()); + assertEquals(true, Year.of(2008).isLeap()); + assertEquals(false, Year.of(2009).isLeap()); + assertEquals(false, Year.of(2010).isLeap()); + assertEquals(false, Year.of(2011).isLeap()); + assertEquals(true, Year.of(2012).isLeap()); - assertEquals(Year.of(2095).isLeap(), false); - assertEquals(Year.of(2096).isLeap(), true); - assertEquals(Year.of(2097).isLeap(), false); - assertEquals(Year.of(2098).isLeap(), false); - assertEquals(Year.of(2099).isLeap(), false); - assertEquals(Year.of(2100).isLeap(), false); - assertEquals(Year.of(2101).isLeap(), false); - assertEquals(Year.of(2102).isLeap(), false); - assertEquals(Year.of(2103).isLeap(), false); - assertEquals(Year.of(2104).isLeap(), true); - assertEquals(Year.of(2105).isLeap(), false); + assertEquals(false, Year.of(2095).isLeap()); + assertEquals(true, Year.of(2096).isLeap()); + assertEquals(false, Year.of(2097).isLeap()); + assertEquals(false, Year.of(2098).isLeap()); + assertEquals(false, Year.of(2099).isLeap()); + assertEquals(false, Year.of(2100).isLeap()); + assertEquals(false, Year.of(2101).isLeap()); + assertEquals(false, Year.of(2102).isLeap()); + assertEquals(false, Year.of(2103).isLeap()); + assertEquals(true, Year.of(2104).isLeap()); + assertEquals(false, Year.of(2105).isLeap()); - assertEquals(Year.of(-500).isLeap(), false); - assertEquals(Year.of(-400).isLeap(), true); - assertEquals(Year.of(-300).isLeap(), false); - assertEquals(Year.of(-200).isLeap(), false); - assertEquals(Year.of(-100).isLeap(), false); - assertEquals(Year.of(0).isLeap(), true); - assertEquals(Year.of(100).isLeap(), false); - assertEquals(Year.of(200).isLeap(), false); - assertEquals(Year.of(300).isLeap(), false); - assertEquals(Year.of(400).isLeap(), true); - assertEquals(Year.of(500).isLeap(), false); + assertEquals(false, Year.of(-500).isLeap()); + assertEquals(true, Year.of(-400).isLeap()); + assertEquals(false, Year.of(-300).isLeap()); + assertEquals(false, Year.of(-200).isLeap()); + assertEquals(false, Year.of(-100).isLeap()); + assertEquals(true, Year.of(0).isLeap()); + assertEquals(false, Year.of(100).isLeap()); + assertEquals(false, Year.of(200).isLeap()); + assertEquals(false, Year.of(300).isLeap()); + assertEquals(true, Year.of(400).isLeap()); + assertEquals(false, Year.of(500).isLeap()); } //----------------------------------------------------------------------- // plus(Period) //----------------------------------------------------------------------- - @DataProvider(name="plusValid") Object[][] data_plusValid() { return new Object[][] { {2012, Period.ofYears(0), 2012}, @@ -511,12 +519,12 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="plusValid") + @ParameterizedTest + @MethodSource("data_plusValid") public void test_plusValid(int year, TemporalAmount amount, int expected) { - assertEquals(Year.of(year).plus(amount), Year.of(expected)); + assertEquals(Year.of(expected), Year.of(year).plus(amount)); } - @DataProvider(name="plusInvalidUnit") Object[][] data_plusInvalidUnit() { return new Object[][] { {Period.of(0, 1, 0)}, @@ -530,14 +538,15 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="plusInvalidUnit", expectedExceptions=UnsupportedTemporalTypeException.class) + @ParameterizedTest + @MethodSource("data_plusInvalidUnit") public void test_plusInvalidUnit(TemporalAmount amount) { - TEST_2008.plus(amount); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> TEST_2008.plus(amount)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_null() { - TEST_2008.plus(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008.plus(null)); } //----------------------------------------------------------------------- @@ -545,54 +554,53 @@ public class TCKYear extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_plusYears() { - assertEquals(Year.of(2007).plusYears(-1), Year.of(2006)); - assertEquals(Year.of(2007).plusYears(0), Year.of(2007)); - assertEquals(Year.of(2007).plusYears(1), Year.of(2008)); - assertEquals(Year.of(2007).plusYears(2), Year.of(2009)); + assertEquals(Year.of(2006), Year.of(2007).plusYears(-1)); + assertEquals(Year.of(2007), Year.of(2007).plusYears(0)); + assertEquals(Year.of(2008), Year.of(2007).plusYears(1)); + assertEquals(Year.of(2009), Year.of(2007).plusYears(2)); - assertEquals(Year.of(Year.MAX_VALUE - 1).plusYears(1), Year.of(Year.MAX_VALUE)); - assertEquals(Year.of(Year.MAX_VALUE).plusYears(0), Year.of(Year.MAX_VALUE)); + assertEquals(Year.of(Year.MAX_VALUE), Year.of(Year.MAX_VALUE - 1).plusYears(1)); + assertEquals(Year.of(Year.MAX_VALUE), Year.of(Year.MAX_VALUE).plusYears(0)); - assertEquals(Year.of(Year.MIN_VALUE + 1).plusYears(-1), Year.of(Year.MIN_VALUE)); - assertEquals(Year.of(Year.MIN_VALUE).plusYears(0), Year.of(Year.MIN_VALUE)); + assertEquals(Year.of(Year.MIN_VALUE), Year.of(Year.MIN_VALUE + 1).plusYears(-1)); + assertEquals(Year.of(Year.MIN_VALUE), Year.of(Year.MIN_VALUE).plusYears(0)); } @Test public void test_plusYear_zero_equals() { Year base = Year.of(2007); - assertEquals(base.plusYears(0), base); + assertEquals(base, base.plusYears(0)); } @Test public void test_plusYears_big() { long years = 20L + Year.MAX_VALUE; - assertEquals(Year.of(-40).plusYears(years), Year.of((int) (-40L + years))); + assertEquals(Year.of((int) (-40L + years)), Year.of(-40).plusYears(years)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_max() { - Year.of(Year.MAX_VALUE).plusYears(1); + Assertions.assertThrows(DateTimeException.class, () -> Year.of(Year.MAX_VALUE).plusYears(1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_maxLots() { - Year.of(Year.MAX_VALUE).plusYears(1000); + Assertions.assertThrows(DateTimeException.class, () -> Year.of(Year.MAX_VALUE).plusYears(1000)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_min() { - Year.of(Year.MIN_VALUE).plusYears(-1); + Assertions.assertThrows(DateTimeException.class, () -> Year.of(Year.MIN_VALUE).plusYears(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_minLots() { - Year.of(Year.MIN_VALUE).plusYears(-1000); + Assertions.assertThrows(DateTimeException.class, () -> Year.of(Year.MIN_VALUE).plusYears(-1000)); } //----------------------------------------------------------------------- // plus(long, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="plus_long_TemporalUnit") Object[][] data_plus_long_TemporalUnit() { return new Object[][] { {Year.of(1), 1, ChronoUnit.YEARS, Year.of(2), null}, @@ -616,10 +624,11 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="plus_long_TemporalUnit") + @ParameterizedTest + @MethodSource("data_plus_long_TemporalUnit") public void test_plus_long_TemporalUnit(Year base, long amount, TemporalUnit unit, Year expectedYear, Class expectedEx) { if (expectedEx == null) { - assertEquals(base.plus(amount, unit), expectedYear); + assertEquals(expectedYear, base.plus(amount, unit)); } else { try { base.plus(amount, unit); @@ -633,7 +642,6 @@ public class TCKYear extends AbstractDateTimeTest { //----------------------------------------------------------------------- // minus(Period) //----------------------------------------------------------------------- - @DataProvider(name="minusValid") Object[][] data_minusValid() { return new Object[][] { {2012, Period.ofYears(0), 2012}, @@ -643,12 +651,12 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="minusValid") + @ParameterizedTest + @MethodSource("data_minusValid") public void test_minusValid(int year, TemporalAmount amount, int expected) { - assertEquals(Year.of(year).minus(amount), Year.of(expected)); + assertEquals(Year.of(expected), Year.of(year).minus(amount)); } - @DataProvider(name="minusInvalidUnit") Object[][] data_minusInvalidUnit() { return new Object[][] { {Period.of(0, 1, 0)}, @@ -662,14 +670,15 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="minusInvalidUnit", expectedExceptions=UnsupportedTemporalTypeException.class) + @ParameterizedTest + @MethodSource("data_minusInvalidUnit") public void test_minusInvalidUnit(TemporalAmount amount) { - TEST_2008.minus(amount); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> TEST_2008.minus(amount)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_minus_null() { - TEST_2008.minus(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008.minus(null)); } //----------------------------------------------------------------------- @@ -677,54 +686,53 @@ public class TCKYear extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_minusYears() { - assertEquals(Year.of(2007).minusYears(-1), Year.of(2008)); - assertEquals(Year.of(2007).minusYears(0), Year.of(2007)); - assertEquals(Year.of(2007).minusYears(1), Year.of(2006)); - assertEquals(Year.of(2007).minusYears(2), Year.of(2005)); + assertEquals(Year.of(2008), Year.of(2007).minusYears(-1)); + assertEquals(Year.of(2007), Year.of(2007).minusYears(0)); + assertEquals(Year.of(2006), Year.of(2007).minusYears(1)); + assertEquals(Year.of(2005), Year.of(2007).minusYears(2)); - assertEquals(Year.of(Year.MAX_VALUE - 1).minusYears(-1), Year.of(Year.MAX_VALUE)); - assertEquals(Year.of(Year.MAX_VALUE).minusYears(0), Year.of(Year.MAX_VALUE)); + assertEquals(Year.of(Year.MAX_VALUE), Year.of(Year.MAX_VALUE - 1).minusYears(-1)); + assertEquals(Year.of(Year.MAX_VALUE), Year.of(Year.MAX_VALUE).minusYears(0)); - assertEquals(Year.of(Year.MIN_VALUE + 1).minusYears(1), Year.of(Year.MIN_VALUE)); - assertEquals(Year.of(Year.MIN_VALUE).minusYears(0), Year.of(Year.MIN_VALUE)); + assertEquals(Year.of(Year.MIN_VALUE), Year.of(Year.MIN_VALUE + 1).minusYears(1)); + assertEquals(Year.of(Year.MIN_VALUE), Year.of(Year.MIN_VALUE).minusYears(0)); } @Test public void test_minusYear_zero_equals() { Year base = Year.of(2007); - assertEquals(base.minusYears(0), base); + assertEquals(base, base.minusYears(0)); } @Test public void test_minusYears_big() { long years = 20L + Year.MAX_VALUE; - assertEquals(Year.of(40).minusYears(years), Year.of((int) (40L - years))); + assertEquals(Year.of((int) (40L - years)), Year.of(40).minusYears(years)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_max() { - Year.of(Year.MAX_VALUE).minusYears(-1); + Assertions.assertThrows(DateTimeException.class, () -> Year.of(Year.MAX_VALUE).minusYears(-1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_maxLots() { - Year.of(Year.MAX_VALUE).minusYears(-1000); + Assertions.assertThrows(DateTimeException.class, () -> Year.of(Year.MAX_VALUE).minusYears(-1000)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_min() { - Year.of(Year.MIN_VALUE).minusYears(1); + Assertions.assertThrows(DateTimeException.class, () -> Year.of(Year.MIN_VALUE).minusYears(1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_minLots() { - Year.of(Year.MIN_VALUE).minusYears(1000); + Assertions.assertThrows(DateTimeException.class, () -> Year.of(Year.MIN_VALUE).minusYears(1000)); } //----------------------------------------------------------------------- // minus(long, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="minus_long_TemporalUnit") Object[][] data_minus_long_TemporalUnit() { return new Object[][] { {Year.of(1), 1, ChronoUnit.YEARS, Year.of(0), null}, @@ -748,10 +756,11 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="minus_long_TemporalUnit") + @ParameterizedTest + @MethodSource("data_minus_long_TemporalUnit") public void test_minus_long_TemporalUnit(Year base, long amount, TemporalUnit unit, Year expectedYear, Class expectedEx) { if (expectedEx == null) { - assertEquals(base.minus(amount, unit), expectedYear); + assertEquals(expectedYear, base.minus(amount, unit)); } else { try { Year result = base.minus(amount, unit); @@ -770,20 +779,22 @@ public class TCKYear extends AbstractDateTimeTest { LocalDate base = LocalDate.of(2007, 2, 12); for (int i = -4; i <= 2104; i++) { Temporal result = Year.of(i).adjustInto(base); - assertEquals(result, LocalDate.of(i, 2, 12)); + assertEquals(LocalDate.of(i, 2, 12), result); } } @Test public void test_adjustDate_resolve() { Year test = Year.of(2011); - assertEquals(test.adjustInto(LocalDate.of(2012, 2, 29)), LocalDate.of(2011, 2, 28)); + assertEquals(LocalDate.of(2011, 2, 28), test.adjustInto(LocalDate.of(2012, 2, 29))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_adjustDate_nullLocalDate() { - Year test = Year.of(1); - test.adjustInto((LocalDate) null); + Assertions.assertThrows(NullPointerException.class, () -> { + Year test = Year.of(1); + test.adjustInto((LocalDate) null); + }); } //----------------------------------------------------------------------- @@ -794,14 +805,16 @@ public class TCKYear extends AbstractDateTimeTest { Year base = Year.of(-10); for (int i = -4; i <= 2104; i++) { Temporal result = base.with(Year.of(i)); - assertEquals(result, Year.of(i)); + assertEquals(Year.of(i), result); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_with_BadTemporalAdjuster() { - Year test = Year.of(1); - test.with(LocalTime.of(18, 1, 2)); + Assertions.assertThrows(DateTimeException.class, () -> { + Year test = Year.of(1); + test.with(LocalTime.of(18, 1, 2)); + }); } //----------------------------------------------------------------------- @@ -811,22 +824,22 @@ public class TCKYear extends AbstractDateTimeTest { public void test_with() { Year base = Year.of(5); Year result = base.with(ChronoField.ERA, 0); - assertEquals(result, base.with(IsoEra.of(0))); + assertEquals(base.with(IsoEra.of(0)), result); int prolepticYear = IsoChronology.INSTANCE.prolepticYear(IsoEra.of(0), 5); - assertEquals(result.get(ChronoField.ERA), 0); - assertEquals(result.get(ChronoField.YEAR), prolepticYear); - assertEquals(result.get(ChronoField.YEAR_OF_ERA), 5); + assertEquals(0, result.get(ChronoField.ERA)); + assertEquals(prolepticYear, result.get(ChronoField.YEAR)); + assertEquals(5, result.get(ChronoField.YEAR_OF_ERA)); result = base.with(ChronoField.YEAR, 10); - assertEquals(result.get(ChronoField.ERA), base.get(ChronoField.ERA)); - assertEquals(result.get(ChronoField.YEAR), 10); - assertEquals(result.get(ChronoField.YEAR_OF_ERA), 10); + assertEquals(base.get(ChronoField.ERA), result.get(ChronoField.ERA)); + assertEquals(10, result.get(ChronoField.YEAR)); + assertEquals(10, result.get(ChronoField.YEAR_OF_ERA)); result = base.with(ChronoField.YEAR_OF_ERA, 20); - assertEquals(result.get(ChronoField.ERA), base.get(ChronoField.ERA)); - assertEquals(result.get(ChronoField.YEAR), 20); - assertEquals(result.get(ChronoField.YEAR_OF_ERA), 20); + assertEquals(base.get(ChronoField.ERA), result.get(ChronoField.ERA)); + assertEquals(20, result.get(ChronoField.YEAR)); + assertEquals(20, result.get(ChronoField.YEAR_OF_ERA)); } //----------------------------------------------------------------------- @@ -834,46 +847,45 @@ public class TCKYear extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_length() { - assertEquals(Year.of(1999).length(), 365); - assertEquals(Year.of(2000).length(), 366); - assertEquals(Year.of(2001).length(), 365); + assertEquals(365, Year.of(1999).length()); + assertEquals(366, Year.of(2000).length()); + assertEquals(365, Year.of(2001).length()); - assertEquals(Year.of(2007).length(), 365); - assertEquals(Year.of(2008).length(), 366); - assertEquals(Year.of(2009).length(), 365); - assertEquals(Year.of(2010).length(), 365); - assertEquals(Year.of(2011).length(), 365); - assertEquals(Year.of(2012).length(), 366); + assertEquals(365, Year.of(2007).length()); + assertEquals(366, Year.of(2008).length()); + assertEquals(365, Year.of(2009).length()); + assertEquals(365, Year.of(2010).length()); + assertEquals(365, Year.of(2011).length()); + assertEquals(366, Year.of(2012).length()); - assertEquals(Year.of(2095).length(), 365); - assertEquals(Year.of(2096).length(), 366); - assertEquals(Year.of(2097).length(), 365); - assertEquals(Year.of(2098).length(), 365); - assertEquals(Year.of(2099).length(), 365); - assertEquals(Year.of(2100).length(), 365); - assertEquals(Year.of(2101).length(), 365); - assertEquals(Year.of(2102).length(), 365); - assertEquals(Year.of(2103).length(), 365); - assertEquals(Year.of(2104).length(), 366); - assertEquals(Year.of(2105).length(), 365); + assertEquals(365, Year.of(2095).length()); + assertEquals(366, Year.of(2096).length()); + assertEquals(365, Year.of(2097).length()); + assertEquals(365, Year.of(2098).length()); + assertEquals(365, Year.of(2099).length()); + assertEquals(365, Year.of(2100).length()); + assertEquals(365, Year.of(2101).length()); + assertEquals(365, Year.of(2102).length()); + assertEquals(365, Year.of(2103).length()); + assertEquals(366, Year.of(2104).length()); + assertEquals(365, Year.of(2105).length()); - assertEquals(Year.of(-500).length(), 365); - assertEquals(Year.of(-400).length(), 366); - assertEquals(Year.of(-300).length(), 365); - assertEquals(Year.of(-200).length(), 365); - assertEquals(Year.of(-100).length(), 365); - assertEquals(Year.of(0).length(), 366); - assertEquals(Year.of(100).length(), 365); - assertEquals(Year.of(200).length(), 365); - assertEquals(Year.of(300).length(), 365); - assertEquals(Year.of(400).length(), 366); - assertEquals(Year.of(500).length(), 365); + assertEquals(365, Year.of(-500).length()); + assertEquals(366, Year.of(-400).length()); + assertEquals(365, Year.of(-300).length()); + assertEquals(365, Year.of(-200).length()); + assertEquals(365, Year.of(-100).length()); + assertEquals(366, Year.of(0).length()); + assertEquals(365, Year.of(100).length()); + assertEquals(365, Year.of(200).length()); + assertEquals(365, Year.of(300).length()); + assertEquals(366, Year.of(400).length()); + assertEquals(365, Year.of(500).length()); } //----------------------------------------------------------------------- // isValidMonthDay(MonthDay) //----------------------------------------------------------------------- - @DataProvider(name="isValidMonthDay") Object[][] data_isValidMonthDay() { return new Object[][] { {Year.of(2007), MonthDay.of(6, 30), true}, @@ -885,15 +897,15 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="isValidMonthDay") + @ParameterizedTest + @MethodSource("data_isValidMonthDay") public void test_isValidMonthDay(Year year, MonthDay monthDay, boolean expected) { - assertEquals(year.isValidMonthDay(monthDay), expected); + assertEquals(expected, year.isValidMonthDay(monthDay)); } //----------------------------------------------------------------------- // until(Temporal, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="periodUntilUnit") Object[][] data_periodUntilUnit() { return new Object[][] { {Year.of(2000), Year.of(-1), YEARS, -2001}, @@ -941,50 +953,55 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit(Year year1, Year year2, TemporalUnit unit, long expected) { long amount = year1.until(year2, unit); - assertEquals(amount, expected); + assertEquals(expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_negated(Year year1, Year year2, TemporalUnit unit, long expected) { long amount = year2.until(year1, unit); - assertEquals(amount, -expected); + assertEquals(-expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_between(Year year1, Year year2, TemporalUnit unit, long expected) { long amount = unit.between(year1, year2); - assertEquals(amount, expected); + assertEquals(expected, amount); } @Test public void test_until_convertedType() { Year start = Year.of(2010); YearMonth end = start.plusYears(2).atMonth(Month.APRIL); - assertEquals(start.until(end, YEARS), 2); + assertEquals(2, start.until(end, YEARS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_invalidType() { - Year start = Year.of(2010); - start.until(LocalTime.of(11, 30), YEARS); + Assertions.assertThrows(DateTimeException.class, () -> { + Year start = Year.of(2010); + start.until(LocalTime.of(11, 30), YEARS); + }); } - @Test(expectedExceptions = UnsupportedTemporalTypeException.class) + @Test public void test_until_TemporalUnit_unsupportedUnit() { - TEST_2008.until(TEST_2008, MONTHS); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> TEST_2008.until(TEST_2008, MONTHS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullEnd() { - TEST_2008.until(null, DAYS); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008.until(null, DAYS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullUnit() { - TEST_2008.until(TEST_2008, null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008.until(TEST_2008, null)); } //----------------------------------------------------------------------- @@ -994,12 +1011,12 @@ public class TCKYear extends AbstractDateTimeTest { public void test_format_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y"); String t = Year.of(2010).format(f); - assertEquals(t, "2010"); + assertEquals("2010", t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_format_formatter_null() { - Year.of(2010).format(null); + Assertions.assertThrows(NullPointerException.class, () -> Year.of(2010).format(null)); } //----------------------------------------------------------------------- @@ -1008,13 +1025,15 @@ public class TCKYear extends AbstractDateTimeTest { @Test public void test_atMonth() { Year test = Year.of(2008); - assertEquals(test.atMonth(Month.JUNE), YearMonth.of(2008, 6)); + assertEquals(YearMonth.of(2008, 6), test.atMonth(Month.JUNE)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atMonth_nullMonth() { - Year test = Year.of(2008); - test.atMonth((Month) null); + Assertions.assertThrows(NullPointerException.class, () -> { + Year test = Year.of(2008); + test.atMonth((Month) null); + }); } //----------------------------------------------------------------------- @@ -1023,19 +1042,20 @@ public class TCKYear extends AbstractDateTimeTest { @Test public void test_atMonth_int() { Year test = Year.of(2008); - assertEquals(test.atMonth(6), YearMonth.of(2008, 6)); + assertEquals(YearMonth.of(2008, 6), test.atMonth(6)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atMonth_int_invalidMonth() { - Year test = Year.of(2008); - test.atMonth(13); + Assertions.assertThrows(DateTimeException.class, () -> { + Year test = Year.of(2008); + test.atMonth(13); + }); } //----------------------------------------------------------------------- // atMonthDay(MonthDay) //----------------------------------------------------------------------- - @DataProvider(name="atMonthDay") Object[][] data_atMonthDay() { return new Object[][] { {Year.of(2008), MonthDay.of(6, 30), LocalDate.of(2008, 6, 30)}, @@ -1044,15 +1064,18 @@ public class TCKYear extends AbstractDateTimeTest { }; } - @Test(dataProvider="atMonthDay") + @ParameterizedTest + @MethodSource("data_atMonthDay") public void test_atMonthDay(Year year, MonthDay monthDay, LocalDate expected) { - assertEquals(year.atMonthDay(monthDay), expected); + assertEquals(expected, year.atMonthDay(monthDay)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_atMonthDay_nullMonthDay() { - Year test = Year.of(2008); - test.atMonthDay((MonthDay) null); + Assertions.assertThrows(NullPointerException.class, () -> { + Year test = Year.of(2008); + test.atMonthDay((MonthDay) null); + }); } //----------------------------------------------------------------------- @@ -1063,15 +1086,17 @@ public class TCKYear extends AbstractDateTimeTest { Year test = Year.of(2007); LocalDate expected = LocalDate.of(2007, 1, 1); for (int i = 1; i <= 365; i++) { - assertEquals(test.atDay(i), expected); + assertEquals(expected, test.atDay(i)); expected = expected.plusDays(1); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atDay_notLeapYear_day366() { - Year test = Year.of(2007); - test.atDay(366); + Assertions.assertThrows(DateTimeException.class, () -> { + Year test = Year.of(2007); + test.atDay(366); + }); } @Test @@ -1079,21 +1104,25 @@ public class TCKYear extends AbstractDateTimeTest { Year test = Year.of(2008); LocalDate expected = LocalDate.of(2008, 1, 1); for (int i = 1; i <= 366; i++) { - assertEquals(test.atDay(i), expected); + assertEquals(expected, test.atDay(i)); expected = expected.plusDays(1); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atDay_day0() { - Year test = Year.of(2007); - test.atDay(0); + Assertions.assertThrows(DateTimeException.class, () -> { + Year test = Year.of(2007); + test.atDay(0); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_atDay_day367() { - Year test = Year.of(2007); - test.atDay(367); + Assertions.assertThrows(DateTimeException.class, () -> { + Year test = Year.of(2007); + test.atDay(367); + }); } //----------------------------------------------------------------------- @@ -1106,36 +1135,38 @@ public class TCKYear extends AbstractDateTimeTest { for (int j = -4; j <= 2104; j++) { Year b = Year.of(j); if (i < j) { - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.isAfter(b), false); - assertEquals(a.isBefore(b), true); - assertEquals(b.isAfter(a), true); - assertEquals(b.isBefore(a), false); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(false, a.isAfter(b)); + assertEquals(true, a.isBefore(b)); + assertEquals(true, b.isAfter(a)); + assertEquals(false, b.isBefore(a)); } else if (i > j) { - assertEquals(a.compareTo(b) > 0, true); - assertEquals(b.compareTo(a) < 0, true); - assertEquals(a.isAfter(b), true); - assertEquals(a.isBefore(b), false); - assertEquals(b.isAfter(a), false); - assertEquals(b.isBefore(a), true); + assertEquals(true, a.compareTo(b) > 0); + assertEquals(true, b.compareTo(a) < 0); + assertEquals(true, a.isAfter(b)); + assertEquals(false, a.isBefore(b)); + assertEquals(false, b.isAfter(a)); + assertEquals(true, b.isBefore(a)); } else { - assertEquals(a.compareTo(b), 0); - assertEquals(b.compareTo(a), 0); - assertEquals(a.isAfter(b), false); - assertEquals(a.isBefore(b), false); - assertEquals(b.isAfter(a), false); - assertEquals(b.isBefore(a), false); + assertEquals(0, a.compareTo(b)); + assertEquals(0, b.compareTo(a)); + assertEquals(false, a.isAfter(b)); + assertEquals(false, a.isBefore(b)); + assertEquals(false, b.isAfter(a)); + assertEquals(false, b.isBefore(a)); } } } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_nullYear() { - Year doy = null; - Year test = Year.of(1); - test.compareTo(doy); + Assertions.assertThrows(NullPointerException.class, () -> { + Year doy = null; + Year test = Year.of(1); + test.compareTo(doy); + }); } //----------------------------------------------------------------------- @@ -1147,8 +1178,8 @@ public class TCKYear extends AbstractDateTimeTest { Year a = Year.of(i); for (int j = -4; j <= 2104; j++) { Year b = Year.of(j); - assertEquals(a.equals(b), i == j); - assertEquals(a.hashCode() == b.hashCode(), i == j); + assertEquals(i == j, a.equals(b)); + assertEquals(i == j, a.hashCode() == b.hashCode()); } } } @@ -1156,20 +1187,20 @@ public class TCKYear extends AbstractDateTimeTest { @Test public void test_equals_same() { Year test = Year.of(2011); - assertEquals(test.equals(test), true); + assertEquals(true, test.equals(test)); } @Test public void test_equals_nullYear() { Year doy = null; Year test = Year.of(1); - assertEquals(test.equals(doy), false); + assertEquals(false, test.equals(doy)); } @Test public void test_equals_incorrectType() { Year test = Year.of(1); - assertEquals(test.equals("Incorrect type"), false); + assertEquals(false, test.equals("Incorrect type")); } //----------------------------------------------------------------------- @@ -1179,7 +1210,7 @@ public class TCKYear extends AbstractDateTimeTest { public void test_toString() { for (int i = -4; i <= 2104; i++) { Year a = Year.of(i); - assertEquals(a.toString(), "" + i); + assertEquals("" + i, a.toString()); } } diff --git a/test/jdk/java/time/tck/java/time/TCKYearMonth.java b/test/jdk/java/time/tck/java/time/TCKYearMonth.java index e922f72323f..e39bbe90cf9 100644 --- a/test/jdk/java/time/tck/java/time/TCKYearMonth.java +++ b/test/jdk/java/time/tck/java/time/TCKYearMonth.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -71,9 +71,10 @@ import static java.time.temporal.ChronoUnit.HOURS; import static java.time.temporal.ChronoUnit.MILLENNIA; import static java.time.temporal.ChronoUnit.MONTHS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; @@ -110,19 +111,22 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test YearMonth. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKYearMonth extends AbstractDateTimeTest { private YearMonth TEST_2008_06; - @BeforeMethod + @BeforeEach public void setUp() { TEST_2008_06 = YearMonth.of(2008, 6); } @@ -130,7 +134,7 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Override protected List samples() { - TemporalAccessor[] array = {TEST_2008_06, }; + TemporalAccessor[] array = {YearMonth.of(2008, 6), }; return Arrays.asList(array); } @@ -158,8 +162,8 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- void check(YearMonth test, int y, int m) { - assertEquals(test.getYear(), y); - assertEquals(test.getMonth().getValue(), m); + assertEquals(y, test.getYear()); + assertEquals(m, test.getMonth().getValue()); } //----------------------------------------------------------------------- @@ -176,15 +180,15 @@ public class TCKYearMonth extends AbstractDateTimeTest { expected = YearMonth.now(Clock.systemDefaultZone()); test = YearMonth.now(); } - assertEquals(test, expected); + assertEquals(expected, test); } //----------------------------------------------------------------------- // now(ZoneId) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_ZoneId_nullZoneId() { - YearMonth.now((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> YearMonth.now((ZoneId) null)); } @Test @@ -199,7 +203,7 @@ public class TCKYearMonth extends AbstractDateTimeTest { expected = YearMonth.now(Clock.system(zone)); test = YearMonth.now(zone); } - assertEquals(test, expected); + assertEquals(expected, test); } //----------------------------------------------------------------------- @@ -210,13 +214,13 @@ public class TCKYearMonth extends AbstractDateTimeTest { Instant instant = LocalDateTime.of(2010, 12, 31, 0, 0).toInstant(ZoneOffset.UTC); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); YearMonth test = YearMonth.now(clock); - assertEquals(test.getYear(), 2010); - assertEquals(test.getMonth(), Month.DECEMBER); + assertEquals(2010, test.getYear()); + assertEquals(Month.DECEMBER, test.getMonth()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullClock() { - YearMonth.now((Clock) null); + Assertions.assertThrows(NullPointerException.class, () -> YearMonth.now((Clock) null)); } //----------------------------------------------------------------------- @@ -226,19 +230,19 @@ public class TCKYearMonth extends AbstractDateTimeTest { check(test, 2008, 2); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_intsMonth_yearTooLow() { - YearMonth.of(Year.MIN_VALUE - 1, Month.JANUARY); + Assertions.assertThrows(DateTimeException.class, () -> YearMonth.of(Year.MIN_VALUE - 1, Month.JANUARY)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_intsMonth_dayTooHigh() { - YearMonth.of(Year.MAX_VALUE + 1, Month.JANUARY); + Assertions.assertThrows(DateTimeException.class, () -> YearMonth.of(Year.MAX_VALUE + 1, Month.JANUARY)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_intsMonth_nullMonth() { - YearMonth.of(2008, null); + Assertions.assertThrows(NullPointerException.class, () -> YearMonth.of(2008, null)); } //----------------------------------------------------------------------- @@ -248,46 +252,45 @@ public class TCKYearMonth extends AbstractDateTimeTest { check(test, 2008, 2); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ints_yearTooLow() { - YearMonth.of(Year.MIN_VALUE - 1, 2); + Assertions.assertThrows(DateTimeException.class, () -> YearMonth.of(Year.MIN_VALUE - 1, 2)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ints_dayTooHigh() { - YearMonth.of(Year.MAX_VALUE + 1, 2); + Assertions.assertThrows(DateTimeException.class, () -> YearMonth.of(Year.MAX_VALUE + 1, 2)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ints_monthTooLow() { - YearMonth.of(2008, 0); + Assertions.assertThrows(DateTimeException.class, () -> YearMonth.of(2008, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ints_monthTooHigh() { - YearMonth.of(2008, 13); + Assertions.assertThrows(DateTimeException.class, () -> YearMonth.of(2008, 13)); } //----------------------------------------------------------------------- @Test public void test_from_TemporalAccessor() { - assertEquals(YearMonth.from(LocalDate.of(2007, 7, 15)), YearMonth.of(2007, 7)); + assertEquals(YearMonth.of(2007, 7), YearMonth.from(LocalDate.of(2007, 7, 15))); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_from_TemporalAccessor_invalid_noDerive() { - YearMonth.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> YearMonth.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_from_TemporalAccessor_null() { - YearMonth.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> YearMonth.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- // parse() //----------------------------------------------------------------------- - @DataProvider(name="goodParseData") Object[][] provider_goodParseData() { return new Object[][] { {"0000-01", YearMonth.of(0, 1)}, @@ -317,14 +320,14 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="goodParseData") + @ParameterizedTest + @MethodSource("provider_goodParseData") public void factory_parse_success(String text, YearMonth expected) { YearMonth yearMonth = YearMonth.parse(text); - assertEquals(yearMonth, expected); + assertEquals(expected, yearMonth); } //----------------------------------------------------------------------- - @DataProvider(name="badParseData") Object[][] provider_badParseData() { return new Object[][] { {"", 0}, @@ -345,27 +348,30 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="badParseData", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("provider_badParseData") public void factory_parse_fail(String text, int pos) { - try { - YearMonth.parse(text); - fail(String.format("Parse should have failed for %s at position %d", text, pos)); - } catch (DateTimeParseException ex) { - assertEquals(ex.getParsedString(), text); - assertEquals(ex.getErrorIndex(), pos); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + try { + YearMonth.parse(text); + fail(String.format("Parse should have failed for %s at position %d", text, pos)); + } catch (DateTimeParseException ex) { + assertEquals(text, ex.getParsedString()); + assertEquals(pos, ex.getErrorIndex()); + throw ex; + } + }); } //----------------------------------------------------------------------- - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_illegalValue_Month() { - YearMonth.parse("2008-13"); + Assertions.assertThrows(DateTimeParseException.class, () -> YearMonth.parse("2008-13")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_nullText() { - YearMonth.parse(null); + Assertions.assertThrows(NullPointerException.class, () -> YearMonth.parse(null)); } //----------------------------------------------------------------------- @@ -375,18 +381,20 @@ public class TCKYearMonth extends AbstractDateTimeTest { public void factory_parse_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y M"); YearMonth test = YearMonth.parse("2010 12", f); - assertEquals(test, YearMonth.of(2010, 12)); + assertEquals(YearMonth.of(2010, 12), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullText() { - DateTimeFormatter f = DateTimeFormatter.ofPattern("y M"); - YearMonth.parse((String) null, f); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter f = DateTimeFormatter.ofPattern("y M"); + YearMonth.parse((String) null, f); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullFormatter() { - YearMonth.parse("ANY", null); + Assertions.assertThrows(NullPointerException.class, () -> YearMonth.parse("ANY", null)); } //----------------------------------------------------------------------- @@ -394,37 +402,37 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(TEST_2008_06.isSupported((TemporalField) null), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.NANO_OF_SECOND), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.NANO_OF_DAY), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.MICRO_OF_SECOND), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.MICRO_OF_DAY), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.MILLI_OF_SECOND), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.MILLI_OF_DAY), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.SECOND_OF_MINUTE), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.SECOND_OF_DAY), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.MINUTE_OF_HOUR), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.MINUTE_OF_DAY), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.HOUR_OF_AMPM), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.HOUR_OF_DAY), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.AMPM_OF_DAY), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.DAY_OF_WEEK), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.DAY_OF_MONTH), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.DAY_OF_YEAR), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.EPOCH_DAY), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.MONTH_OF_YEAR), true); - assertEquals(TEST_2008_06.isSupported(ChronoField.PROLEPTIC_MONTH), true); - assertEquals(TEST_2008_06.isSupported(ChronoField.YEAR), true); - assertEquals(TEST_2008_06.isSupported(ChronoField.YEAR_OF_ERA), true); - assertEquals(TEST_2008_06.isSupported(ChronoField.ERA), true); - assertEquals(TEST_2008_06.isSupported(ChronoField.INSTANT_SECONDS), false); - assertEquals(TEST_2008_06.isSupported(ChronoField.OFFSET_SECONDS), false); + assertEquals(false, TEST_2008_06.isSupported((TemporalField) null)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(true, TEST_2008_06.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(true, TEST_2008_06.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(true, TEST_2008_06.isSupported(ChronoField.YEAR)); + assertEquals(true, TEST_2008_06.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(true, TEST_2008_06.isSupported(ChronoField.ERA)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(false, TEST_2008_06.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -432,23 +440,23 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalUnit() { - assertEquals(TEST_2008_06.isSupported((TemporalUnit) null), false); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.NANOS), false); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.MICROS), false); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.MILLIS), false); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.SECONDS), false); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.MINUTES), false); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.HOURS), false); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.HALF_DAYS), false); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.DAYS), false); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.WEEKS), false); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.MONTHS), true); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.YEARS), true); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.DECADES), true); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.CENTURIES), true); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.MILLENNIA), true); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.ERAS), true); - assertEquals(TEST_2008_06.isSupported(ChronoUnit.FOREVER), false); + assertEquals(false, TEST_2008_06.isSupported((TemporalUnit) null)); + assertEquals(false, TEST_2008_06.isSupported(ChronoUnit.NANOS)); + assertEquals(false, TEST_2008_06.isSupported(ChronoUnit.MICROS)); + assertEquals(false, TEST_2008_06.isSupported(ChronoUnit.MILLIS)); + assertEquals(false, TEST_2008_06.isSupported(ChronoUnit.SECONDS)); + assertEquals(false, TEST_2008_06.isSupported(ChronoUnit.MINUTES)); + assertEquals(false, TEST_2008_06.isSupported(ChronoUnit.HOURS)); + assertEquals(false, TEST_2008_06.isSupported(ChronoUnit.HALF_DAYS)); + assertEquals(false, TEST_2008_06.isSupported(ChronoUnit.DAYS)); + assertEquals(false, TEST_2008_06.isSupported(ChronoUnit.WEEKS)); + assertEquals(true, TEST_2008_06.isSupported(ChronoUnit.MONTHS)); + assertEquals(true, TEST_2008_06.isSupported(ChronoUnit.YEARS)); + assertEquals(true, TEST_2008_06.isSupported(ChronoUnit.DECADES)); + assertEquals(true, TEST_2008_06.isSupported(ChronoUnit.CENTURIES)); + assertEquals(true, TEST_2008_06.isSupported(ChronoUnit.MILLENNIA)); + assertEquals(true, TEST_2008_06.isSupported(ChronoUnit.ERAS)); + assertEquals(false, TEST_2008_06.isSupported(ChronoUnit.FOREVER)); } //----------------------------------------------------------------------- @@ -456,25 +464,24 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_get_TemporalField() { - assertEquals(TEST_2008_06.get(YEAR), 2008); - assertEquals(TEST_2008_06.get(MONTH_OF_YEAR), 6); - assertEquals(TEST_2008_06.get(YEAR_OF_ERA), 2008); - assertEquals(TEST_2008_06.get(ERA), 1); + assertEquals(2008, TEST_2008_06.get(YEAR)); + assertEquals(6, TEST_2008_06.get(MONTH_OF_YEAR)); + assertEquals(2008, TEST_2008_06.get(YEAR_OF_ERA)); + assertEquals(1, TEST_2008_06.get(ERA)); } @Test public void test_getLong_TemporalField() { - assertEquals(TEST_2008_06.getLong(YEAR), 2008); - assertEquals(TEST_2008_06.getLong(MONTH_OF_YEAR), 6); - assertEquals(TEST_2008_06.getLong(YEAR_OF_ERA), 2008); - assertEquals(TEST_2008_06.getLong(ERA), 1); - assertEquals(TEST_2008_06.getLong(PROLEPTIC_MONTH), 2008 * 12 + 6 - 1); + assertEquals(2008, TEST_2008_06.getLong(YEAR)); + assertEquals(6, TEST_2008_06.getLong(MONTH_OF_YEAR)); + assertEquals(2008, TEST_2008_06.getLong(YEAR_OF_ERA)); + assertEquals(1, TEST_2008_06.getLong(ERA)); + assertEquals(2008 * 12 + 6 - 1, TEST_2008_06.getLong(PROLEPTIC_MONTH)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {TEST_2008_06, TemporalQueries.chronology(), IsoChronology.INSTANCE}, @@ -487,25 +494,26 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - TEST_2008_06.query(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_06.query(null)); } //----------------------------------------------------------------------- // get*() //----------------------------------------------------------------------- - @DataProvider(name="sampleDates") Object[][] provider_sampleDates() { return new Object[][] { {2008, 1}, @@ -515,12 +523,13 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_get(int y, int m) { YearMonth a = YearMonth.of(y, m); - assertEquals(a.getYear(), y); - assertEquals(a.getMonth(), Month.of(m)); - assertEquals(a.getMonthValue(), m); + assertEquals(y, a.getYear()); + assertEquals(Month.of(m), a.getMonth()); + assertEquals(m, a.getMonthValue()); } //----------------------------------------------------------------------- @@ -529,19 +538,21 @@ public class TCKYearMonth extends AbstractDateTimeTest { @Test public void test_with_Year() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.with(Year.of(2000)), YearMonth.of(2000, 6)); + assertEquals(YearMonth.of(2000, 6), test.with(Year.of(2000))); } @Test public void test_with_Year_noChange_equal() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.with(Year.of(2008)), test); + assertEquals(test, test.with(Year.of(2008))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_with_Year_null() { - YearMonth test = YearMonth.of(2008, 6); - test.with((Year) null); + Assertions.assertThrows(NullPointerException.class, () -> { + YearMonth test = YearMonth.of(2008, 6); + test.with((Year) null); + }); } //----------------------------------------------------------------------- @@ -550,19 +561,21 @@ public class TCKYearMonth extends AbstractDateTimeTest { @Test public void test_with_Month() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.with(Month.JANUARY), YearMonth.of(2008, 1)); + assertEquals(YearMonth.of(2008, 1), test.with(Month.JANUARY)); } @Test public void test_with_Month_noChange_equal() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.with(Month.JUNE), test); + assertEquals(test, test.with(Month.JUNE)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_with_Month_null() { - YearMonth test = YearMonth.of(2008, 6); - test.with((Month) null); + Assertions.assertThrows(NullPointerException.class, () -> { + YearMonth test = YearMonth.of(2008, 6); + test.with((Month) null); + }); } //----------------------------------------------------------------------- @@ -571,25 +584,29 @@ public class TCKYearMonth extends AbstractDateTimeTest { @Test public void test_withYear() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.withYear(1999), YearMonth.of(1999, 6)); + assertEquals(YearMonth.of(1999, 6), test.withYear(1999)); } @Test public void test_withYear_int_noChange_equal() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.withYear(2008), test); + assertEquals(test, test.withYear(2008)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withYear_tooLow() { - YearMonth test = YearMonth.of(2008, 6); - test.withYear(Year.MIN_VALUE - 1); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(2008, 6); + test.withYear(Year.MIN_VALUE - 1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withYear_tooHigh() { - YearMonth test = YearMonth.of(2008, 6); - test.withYear(Year.MAX_VALUE + 1); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(2008, 6); + test.withYear(Year.MAX_VALUE + 1); + }); } //----------------------------------------------------------------------- @@ -598,25 +615,29 @@ public class TCKYearMonth extends AbstractDateTimeTest { @Test public void test_withMonth() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.withMonth(1), YearMonth.of(2008, 1)); + assertEquals(YearMonth.of(2008, 1), test.withMonth(1)); } @Test public void test_withMonth_int_noChange_equal() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.withMonth(6), test); + assertEquals(test, test.withMonth(6)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMonth_tooLow() { - YearMonth test = YearMonth.of(2008, 6); - test.withMonth(0); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(2008, 6); + test.withMonth(0); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMonth_tooHigh() { - YearMonth test = YearMonth.of(2008, 6); - test.withMonth(13); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(2008, 6); + test.withMonth(13); + }); } //----------------------------------------------------------------------- @@ -625,49 +646,57 @@ public class TCKYearMonth extends AbstractDateTimeTest { @Test public void test_plusYears_long() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.plusYears(1), YearMonth.of(2009, 6)); + assertEquals(YearMonth.of(2009, 6), test.plusYears(1)); } @Test public void test_plusYears_long_noChange_equal() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.plusYears(0), test); + assertEquals(test, test.plusYears(0)); } @Test public void test_plusYears_long_negative() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.plusYears(-1), YearMonth.of(2007, 6)); + assertEquals(YearMonth.of(2007, 6), test.plusYears(-1)); } @Test public void test_plusYears_long_big() { YearMonth test = YearMonth.of(-40, 6); - assertEquals(test.plusYears(20L + Year.MAX_VALUE), YearMonth.of((int) (-40L + 20L + Year.MAX_VALUE), 6)); + assertEquals(YearMonth.of((int) (-40L + 20L + Year.MAX_VALUE), 6), test.plusYears(20L + Year.MAX_VALUE)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_long_invalidTooLarge() { - YearMonth test = YearMonth.of(Year.MAX_VALUE, 6); - test.plusYears(1); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MAX_VALUE, 6); + test.plusYears(1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_long_invalidTooLargeMaxAddMax() { - YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); - test.plusYears(Long.MAX_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); + test.plusYears(Long.MAX_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_long_invalidTooLargeMaxAddMin() { - YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); - test.plusYears(Long.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); + test.plusYears(Long.MIN_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusYears_long_invalidTooSmall() { - YearMonth test = YearMonth.of(Year.MIN_VALUE, 6); - test.plusYears(-1); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MIN_VALUE, 6); + test.plusYears(-1); + }); } //----------------------------------------------------------------------- @@ -676,68 +705,75 @@ public class TCKYearMonth extends AbstractDateTimeTest { @Test public void test_plusMonths_long() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.plusMonths(1), YearMonth.of(2008, 7)); + assertEquals(YearMonth.of(2008, 7), test.plusMonths(1)); } @Test public void test_plusMonths_long_noChange_equal() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.plusMonths(0), test); + assertEquals(test, test.plusMonths(0)); } @Test public void test_plusMonths_long_overYears() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.plusMonths(7), YearMonth.of(2009, 1)); + assertEquals(YearMonth.of(2009, 1), test.plusMonths(7)); } @Test public void test_plusMonths_long_negative() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.plusMonths(-1), YearMonth.of(2008, 5)); + assertEquals(YearMonth.of(2008, 5), test.plusMonths(-1)); } @Test public void test_plusMonths_long_negativeOverYear() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.plusMonths(-6), YearMonth.of(2007, 12)); + assertEquals(YearMonth.of(2007, 12), test.plusMonths(-6)); } @Test public void test_plusMonths_long_big() { YearMonth test = YearMonth.of(-40, 6); long months = 20L + Integer.MAX_VALUE; - assertEquals(test.plusMonths(months), YearMonth.of((int) (-40L + months / 12), 6 + (int) (months % 12))); + assertEquals(YearMonth.of((int) (-40L + months / 12), 6 + (int) (months % 12)), test.plusMonths(months)); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_plusMonths_long_invalidTooLarge() { - YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); - test.plusMonths(1); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); + test.plusMonths(1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusMonths_long_invalidTooLargeMaxAddMax() { - YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); - test.plusMonths(Long.MAX_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); + test.plusMonths(Long.MAX_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_plusMonths_long_invalidTooLargeMaxAddMin() { - YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); - test.plusMonths(Long.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); + test.plusMonths(Long.MIN_VALUE); + }); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_plusMonths_long_invalidTooSmall() { - YearMonth test = YearMonth.of(Year.MIN_VALUE, 1); - test.plusMonths(-1); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MIN_VALUE, 1); + test.plusMonths(-1); + }); } //----------------------------------------------------------------------- // plus(long, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="plus_long_TemporalUnit") Object[][] data_plus_long_TemporalUnit() { return new Object[][] { {YearMonth.of(1, 10), 1, ChronoUnit.YEARS, YearMonth.of(2, 10), null}, @@ -768,10 +804,11 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="plus_long_TemporalUnit") + @ParameterizedTest + @MethodSource("data_plus_long_TemporalUnit") public void test_plus_long_TemporalUnit(YearMonth base, long amount, TemporalUnit unit, YearMonth expectedYearMonth, Class expectedEx) { if (expectedEx == null) { - assertEquals(base.plus(amount, unit), expectedYearMonth); + assertEquals(expectedYearMonth, base.plus(amount, unit)); } else { try { YearMonth result = base.plus(amount, unit); @@ -785,7 +822,6 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- // plus(TemporalAmount) //----------------------------------------------------------------------- - @DataProvider(name="plus_TemporalAmount") Object[][] data_plus_TemporalAmount() { return new Object[][] { {YearMonth.of(1, 1), Period.ofYears(1), YearMonth.of(2, 1), null}, @@ -820,10 +856,11 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="plus_TemporalAmount") + @ParameterizedTest + @MethodSource("data_plus_TemporalAmount") public void test_plus_TemporalAmount(YearMonth base, TemporalAmount temporalAmount, YearMonth expectedYearMonth, Class expectedEx) { if (expectedEx == null) { - assertEquals(base.plus(temporalAmount), expectedYearMonth); + assertEquals(expectedYearMonth, base.plus(temporalAmount)); } else { try { YearMonth result = base.plus(temporalAmount); @@ -840,49 +877,57 @@ public class TCKYearMonth extends AbstractDateTimeTest { @Test public void test_minusYears_long() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.minusYears(1), YearMonth.of(2007, 6)); + assertEquals(YearMonth.of(2007, 6), test.minusYears(1)); } @Test public void test_minusYears_long_noChange_equal() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.minusYears(0), test); + assertEquals(test, test.minusYears(0)); } @Test public void test_minusYears_long_negative() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.minusYears(-1), YearMonth.of(2009, 6)); + assertEquals(YearMonth.of(2009, 6), test.minusYears(-1)); } @Test public void test_minusYears_long_big() { YearMonth test = YearMonth.of(40, 6); - assertEquals(test.minusYears(20L + Year.MAX_VALUE), YearMonth.of((int) (40L - 20L - Year.MAX_VALUE), 6)); + assertEquals(YearMonth.of((int) (40L - 20L - Year.MAX_VALUE), 6), test.minusYears(20L + Year.MAX_VALUE)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_long_invalidTooLarge() { - YearMonth test = YearMonth.of(Year.MAX_VALUE, 6); - test.minusYears(-1); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MAX_VALUE, 6); + test.minusYears(-1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_long_invalidTooLargeMaxSubtractMax() { - YearMonth test = YearMonth.of(Year.MIN_VALUE, 12); - test.minusYears(Long.MAX_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MIN_VALUE, 12); + test.minusYears(Long.MAX_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_long_invalidTooLargeMaxSubtractMin() { - YearMonth test = YearMonth.of(Year.MIN_VALUE, 12); - test.minusYears(Long.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MIN_VALUE, 12); + test.minusYears(Long.MIN_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusYears_long_invalidTooSmall() { - YearMonth test = YearMonth.of(Year.MIN_VALUE, 6); - test.minusYears(1); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MIN_VALUE, 6); + test.minusYears(1); + }); } //----------------------------------------------------------------------- @@ -891,68 +936,75 @@ public class TCKYearMonth extends AbstractDateTimeTest { @Test public void test_minusMonths_long() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.minusMonths(1), YearMonth.of(2008, 5)); + assertEquals(YearMonth.of(2008, 5), test.minusMonths(1)); } @Test public void test_minusMonths_long_noChange_equal() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.minusMonths(0), test); + assertEquals(test, test.minusMonths(0)); } @Test public void test_minusMonths_long_overYears() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.minusMonths(6), YearMonth.of(2007, 12)); + assertEquals(YearMonth.of(2007, 12), test.minusMonths(6)); } @Test public void test_minusMonths_long_negative() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.minusMonths(-1), YearMonth.of(2008, 7)); + assertEquals(YearMonth.of(2008, 7), test.minusMonths(-1)); } @Test public void test_minusMonths_long_negativeOverYear() { YearMonth test = YearMonth.of(2008, 6); - assertEquals(test.minusMonths(-7), YearMonth.of(2009, 1)); + assertEquals(YearMonth.of(2009, 1), test.minusMonths(-7)); } @Test public void test_minusMonths_long_big() { YearMonth test = YearMonth.of(40, 6); long months = 20L + Integer.MAX_VALUE; - assertEquals(test.minusMonths(months), YearMonth.of((int) (40L - months / 12), 6 - (int) (months % 12))); + assertEquals(YearMonth.of((int) (40L - months / 12), 6 - (int) (months % 12)), test.minusMonths(months)); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_minusMonths_long_invalidTooLarge() { - YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); - test.minusMonths(-1); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); + test.minusMonths(-1); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusMonths_long_invalidTooLargeMaxSubtractMax() { - YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); - test.minusMonths(Long.MAX_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); + test.minusMonths(Long.MAX_VALUE); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_minusMonths_long_invalidTooLargeMaxSubtractMin() { - YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); - test.minusMonths(Long.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MAX_VALUE, 12); + test.minusMonths(Long.MIN_VALUE); + }); } - @Test(expectedExceptions={DateTimeException.class}) + @Test public void test_minusMonths_long_invalidTooSmall() { - YearMonth test = YearMonth.of(Year.MIN_VALUE, 1); - test.minusMonths(1); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth test = YearMonth.of(Year.MIN_VALUE, 1); + test.minusMonths(1); + }); } //----------------------------------------------------------------------- // minus(long, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="minus_long_TemporalUnit") Object[][] data_minus_long_TemporalUnit() { return new Object[][] { {YearMonth.of(1, 10), 1, ChronoUnit.YEARS, YearMonth.of(0, 10), null}, @@ -983,10 +1035,11 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="minus_long_TemporalUnit") + @ParameterizedTest + @MethodSource("data_minus_long_TemporalUnit") public void test_minus_long_TemporalUnit(YearMonth base, long amount, TemporalUnit unit, YearMonth expectedYearMonth, Class expectedEx) { if (expectedEx == null) { - assertEquals(base.minus(amount, unit), expectedYearMonth); + assertEquals(expectedYearMonth, base.minus(amount, unit)); } else { try { YearMonth result = base.minus(amount, unit); @@ -1000,7 +1053,6 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- // minus(TemporalAmount) //----------------------------------------------------------------------- - @DataProvider(name="minus_TemporalAmount") Object[][] data_minus_TemporalAmount() { return new Object[][] { {YearMonth.of(1, 1), Period.ofYears(1), YearMonth.of(0, 1), null}, @@ -1035,10 +1087,11 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="minus_TemporalAmount") + @ParameterizedTest + @MethodSource("data_minus_TemporalAmount") public void test_minus_TemporalAmount(YearMonth base, TemporalAmount temporalAmount, YearMonth expectedYearMonth, Class expectedEx) { if (expectedEx == null) { - assertEquals(base.minus(temporalAmount), expectedYearMonth); + assertEquals(expectedYearMonth, base.minus(temporalAmount)); } else { try { YearMonth result = base.minus(temporalAmount); @@ -1056,33 +1109,33 @@ public class TCKYearMonth extends AbstractDateTimeTest { public void test_adjustDate() { YearMonth test = YearMonth.of(2008, 6); LocalDate date = LocalDate.of(2007, 1, 1); - assertEquals(test.adjustInto(date), LocalDate.of(2008, 6, 1)); + assertEquals(LocalDate.of(2008, 6, 1), test.adjustInto(date)); } @Test public void test_adjustDate_preserveDoM() { YearMonth test = YearMonth.of(2011, 3); LocalDate date = LocalDate.of(2008, 2, 29); - assertEquals(test.adjustInto(date), LocalDate.of(2011, 3, 29)); + assertEquals(LocalDate.of(2011, 3, 29), test.adjustInto(date)); } @Test public void test_adjustDate_resolve() { YearMonth test = YearMonth.of(2007, 2); LocalDate date = LocalDate.of(2008, 3, 31); - assertEquals(test.adjustInto(date), LocalDate.of(2007, 2, 28)); + assertEquals(LocalDate.of(2007, 2, 28), test.adjustInto(date)); } @Test public void test_adjustDate_equal() { YearMonth test = YearMonth.of(2008, 6); LocalDate date = LocalDate.of(2008, 6, 30); - assertEquals(test.adjustInto(date), date); + assertEquals(date, test.adjustInto(date)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_adjustDate_null() { - TEST_2008_06.adjustInto((LocalDate) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_06.adjustInto((LocalDate) null)); } //----------------------------------------------------------------------- @@ -1090,8 +1143,8 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isLeapYear() { - assertEquals(YearMonth.of(2007, 6).isLeapYear(), false); - assertEquals(YearMonth.of(2008, 6).isLeapYear(), true); + assertEquals(false, YearMonth.of(2007, 6).isLeapYear()); + assertEquals(true, YearMonth.of(2008, 6).isLeapYear()); } //----------------------------------------------------------------------- @@ -1100,19 +1153,19 @@ public class TCKYearMonth extends AbstractDateTimeTest { @Test public void test_lengthOfMonth_june() { YearMonth test = YearMonth.of(2007, 6); - assertEquals(test.lengthOfMonth(), 30); + assertEquals(30, test.lengthOfMonth()); } @Test public void test_lengthOfMonth_febNonLeap() { YearMonth test = YearMonth.of(2007, 2); - assertEquals(test.lengthOfMonth(), 28); + assertEquals(28, test.lengthOfMonth()); } @Test public void test_lengthOfMonth_febLeap() { YearMonth test = YearMonth.of(2008, 2); - assertEquals(test.lengthOfMonth(), 29); + assertEquals(29, test.lengthOfMonth()); } //----------------------------------------------------------------------- @@ -1120,8 +1173,8 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_lengthOfYear() { - assertEquals(YearMonth.of(2007, 6).lengthOfYear(), 365); - assertEquals(YearMonth.of(2008, 6).lengthOfYear(), 366); + assertEquals(365, YearMonth.of(2007, 6).lengthOfYear()); + assertEquals(366, YearMonth.of(2008, 6).lengthOfYear()); } //----------------------------------------------------------------------- @@ -1130,43 +1183,42 @@ public class TCKYearMonth extends AbstractDateTimeTest { @Test public void test_isValidDay_int_june() { YearMonth test = YearMonth.of(2007, 6); - assertEquals(test.isValidDay(1), true); - assertEquals(test.isValidDay(30), true); + assertEquals(true, test.isValidDay(1)); + assertEquals(true, test.isValidDay(30)); - assertEquals(test.isValidDay(-1), false); - assertEquals(test.isValidDay(0), false); - assertEquals(test.isValidDay(31), false); - assertEquals(test.isValidDay(32), false); + assertEquals(false, test.isValidDay(-1)); + assertEquals(false, test.isValidDay(0)); + assertEquals(false, test.isValidDay(31)); + assertEquals(false, test.isValidDay(32)); } @Test public void test_isValidDay_int_febNonLeap() { YearMonth test = YearMonth.of(2007, 2); - assertEquals(test.isValidDay(1), true); - assertEquals(test.isValidDay(28), true); + assertEquals(true, test.isValidDay(1)); + assertEquals(true, test.isValidDay(28)); - assertEquals(test.isValidDay(-1), false); - assertEquals(test.isValidDay(0), false); - assertEquals(test.isValidDay(29), false); - assertEquals(test.isValidDay(32), false); + assertEquals(false, test.isValidDay(-1)); + assertEquals(false, test.isValidDay(0)); + assertEquals(false, test.isValidDay(29)); + assertEquals(false, test.isValidDay(32)); } @Test public void test_isValidDay_int_febLeap() { YearMonth test = YearMonth.of(2008, 2); - assertEquals(test.isValidDay(1), true); - assertEquals(test.isValidDay(29), true); + assertEquals(true, test.isValidDay(1)); + assertEquals(true, test.isValidDay(29)); - assertEquals(test.isValidDay(-1), false); - assertEquals(test.isValidDay(0), false); - assertEquals(test.isValidDay(30), false); - assertEquals(test.isValidDay(32), false); + assertEquals(false, test.isValidDay(-1)); + assertEquals(false, test.isValidDay(0)); + assertEquals(false, test.isValidDay(30)); + assertEquals(false, test.isValidDay(32)); } //----------------------------------------------------------------------- // until(Temporal, TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name="periodUntilUnit") Object[][] data_periodUntilUnit() { return new Object[][] { {ym(2000, 1), ym(-1, 12), MONTHS, -2000 * 12 - 1}, @@ -1242,50 +1294,55 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit(YearMonth ym1, YearMonth ym2, TemporalUnit unit, long expected) { long amount = ym1.until(ym2, unit); - assertEquals(amount, expected); + assertEquals(expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_negated(YearMonth ym1, YearMonth ym2, TemporalUnit unit, long expected) { long amount = ym2.until(ym1, unit); - assertEquals(amount, -expected); + assertEquals(-expected, amount); } - @Test(dataProvider="periodUntilUnit") + @ParameterizedTest + @MethodSource("data_periodUntilUnit") public void test_until_TemporalUnit_between(YearMonth ym1, YearMonth ym2, TemporalUnit unit, long expected) { long amount = unit.between(ym1, ym2); - assertEquals(amount, expected); + assertEquals(expected, amount); } @Test public void test_until_convertedType() { YearMonth start = YearMonth.of(2010, 6); LocalDate end = start.plusMonths(2).atDay(12); - assertEquals(start.until(end, MONTHS), 2); + assertEquals(2, start.until(end, MONTHS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_invalidType() { - YearMonth start = YearMonth.of(2010, 6); - start.until(LocalTime.of(11, 30), MONTHS); + Assertions.assertThrows(DateTimeException.class, () -> { + YearMonth start = YearMonth.of(2010, 6); + start.until(LocalTime.of(11, 30), MONTHS); + }); } - @Test(expectedExceptions = UnsupportedTemporalTypeException.class) + @Test public void test_until_TemporalUnit_unsupportedUnit() { - TEST_2008_06.until(TEST_2008_06, HOURS); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> TEST_2008_06.until(TEST_2008_06, HOURS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullEnd() { - TEST_2008_06.until(null, DAYS); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_06.until(null, DAYS)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_until_TemporalUnit_nullUnit() { - TEST_2008_06.until(TEST_2008_06, null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_06.until(TEST_2008_06, null)); } //----------------------------------------------------------------------- @@ -1295,18 +1352,17 @@ public class TCKYearMonth extends AbstractDateTimeTest { public void test_format_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y M"); String t = YearMonth.of(2010, 12).format(f); - assertEquals(t, "2010 12"); + assertEquals("2010 12", t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_format_formatter_null() { - YearMonth.of(2010, 12).format(null); + Assertions.assertThrows(NullPointerException.class, () -> YearMonth.of(2010, 12).format(null)); } //----------------------------------------------------------------------- // atDay(int) //----------------------------------------------------------------------- - @DataProvider(name="atDay") Object[][] data_atDay() { return new Object[][] { {YearMonth.of(2008, 6), 8, LocalDate.of(2008, 6, 8)}, @@ -1325,10 +1381,11 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="atDay") + @ParameterizedTest + @MethodSource("data_atDay") public void test_atDay(YearMonth test, int day, LocalDate expected) { if (expected != null) { - assertEquals(test.atDay(day), expected); + assertEquals(expected, test.atDay(day)); } else { try { test.atDay(day); @@ -1342,7 +1399,6 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- // atEndOfMonth() //----------------------------------------------------------------------- - @DataProvider(name="atEndOfMonth") Object[][] data_atEndOfMonth() { return new Object[][] { {YearMonth.of(2008, 1), LocalDate.of(2008, 1, 31)}, @@ -1363,9 +1419,10 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="atEndOfMonth") + @ParameterizedTest + @MethodSource("data_atEndOfMonth") public void test_atEndOfMonth(YearMonth test, LocalDate expected) { - assertEquals(test.atEndOfMonth(), expected); + assertEquals(expected, test.atEndOfMonth()); } //----------------------------------------------------------------------- @@ -1393,37 +1450,37 @@ public class TCKYearMonth extends AbstractDateTimeTest { YearMonth b = localDates[j]; if (i < j) { assertTrue(a.compareTo(b) < 0, a + " <=> " + b); - assertEquals(a.isBefore(b), true, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { assertTrue(a.compareTo(b) > 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(true, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_ObjectNull() { - TEST_2008_06.compareTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_06.compareTo(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isBefore_ObjectNull() { - TEST_2008_06.isBefore(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_06.isBefore(null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isAfter_ObjectNull() { - TEST_2008_06.isAfter(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_2008_06.isAfter(null)); } //----------------------------------------------------------------------- @@ -1436,51 +1493,52 @@ public class TCKYearMonth extends AbstractDateTimeTest { YearMonth c = YearMonth.of(2007, 6); YearMonth d = YearMonth.of(2008, 5); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), true); - assertEquals(a.equals(c), false); - assertEquals(a.equals(d), false); + assertEquals(true, a.equals(a)); + assertEquals(true, a.equals(b)); + assertEquals(false, a.equals(c)); + assertEquals(false, a.equals(d)); - assertEquals(b.equals(a), true); - assertEquals(b.equals(b), true); - assertEquals(b.equals(c), false); - assertEquals(b.equals(d), false); + assertEquals(true, b.equals(a)); + assertEquals(true, b.equals(b)); + assertEquals(false, b.equals(c)); + assertEquals(false, b.equals(d)); - assertEquals(c.equals(a), false); - assertEquals(c.equals(b), false); - assertEquals(c.equals(c), true); - assertEquals(c.equals(d), false); + assertEquals(false, c.equals(a)); + assertEquals(false, c.equals(b)); + assertEquals(true, c.equals(c)); + assertEquals(false, c.equals(d)); - assertEquals(d.equals(a), false); - assertEquals(d.equals(b), false); - assertEquals(d.equals(c), false); - assertEquals(d.equals(d), true); + assertEquals(false, d.equals(a)); + assertEquals(false, d.equals(b)); + assertEquals(false, d.equals(c)); + assertEquals(true, d.equals(d)); } @Test public void test_equals_itself_true() { - assertEquals(TEST_2008_06.equals(TEST_2008_06), true); + assertEquals(true, TEST_2008_06.equals(TEST_2008_06)); } @Test public void test_equals_string_false() { - assertEquals(TEST_2008_06.equals("2007-07-15"), false); + assertEquals(false, TEST_2008_06.equals("2007-07-15")); } @Test public void test_equals_null_false() { - assertEquals(TEST_2008_06.equals(null), false); + assertEquals(false, TEST_2008_06.equals(null)); } //----------------------------------------------------------------------- // hashCode() //----------------------------------------------------------------------- - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_hashCode(int y, int m) { YearMonth a = YearMonth.of(y, m); assertEquals(a.hashCode(), a.hashCode()); YearMonth b = YearMonth.of(y, m); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); } @Test @@ -1496,7 +1554,6 @@ public class TCKYearMonth extends AbstractDateTimeTest { //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="sampleToString") Object[][] provider_sampleToString() { return new Object[][] { {2008, 1, "2008-01"}, @@ -1507,11 +1564,12 @@ public class TCKYearMonth extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_toString(int y, int m, String expected) { YearMonth test = YearMonth.of(y, m); String str = test.toString(); - assertEquals(str, expected); + assertEquals(expected, str); } private YearMonth ym(int year, int month) { diff --git a/test/jdk/java/time/tck/java/time/TCKZoneId.java b/test/jdk/java/time/tck/java/time/TCKZoneId.java index 1e2d3872451..4958a45dccf 100644 --- a/test/jdk/java/time/tck/java/time/TCKZoneId.java +++ b/test/jdk/java/time/tck/java/time/TCKZoneId.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,8 @@ */ package tck.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -84,13 +84,16 @@ import java.util.Locale; import java.util.Map; import java.util.Set; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test ZoneId. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKZoneId extends AbstractTCKTest { //----------------------------------------------------------------------- @@ -99,40 +102,42 @@ public class TCKZoneId extends AbstractTCKTest { @Test public void test_constant_OLD_IDS_POST_2024b() { Map ids = ZoneId.SHORT_IDS; - assertEquals(ids.get("EST"), "America/Panama"); - assertEquals(ids.get("MST"), "America/Phoenix"); - assertEquals(ids.get("HST"), "Pacific/Honolulu"); - assertEquals(ids.get("ACT"), "Australia/Darwin"); - assertEquals(ids.get("AET"), "Australia/Sydney"); - assertEquals(ids.get("AGT"), "America/Argentina/Buenos_Aires"); - assertEquals(ids.get("ART"), "Africa/Cairo"); - assertEquals(ids.get("AST"), "America/Anchorage"); - assertEquals(ids.get("BET"), "America/Sao_Paulo"); - assertEquals(ids.get("BST"), "Asia/Dhaka"); - assertEquals(ids.get("CAT"), "Africa/Harare"); - assertEquals(ids.get("CNT"), "America/St_Johns"); - assertEquals(ids.get("CST"), "America/Chicago"); - assertEquals(ids.get("CTT"), "Asia/Shanghai"); - assertEquals(ids.get("EAT"), "Africa/Addis_Ababa"); - assertEquals(ids.get("ECT"), "Europe/Paris"); - assertEquals(ids.get("IET"), "America/Indiana/Indianapolis"); - assertEquals(ids.get("IST"), "Asia/Kolkata"); - assertEquals(ids.get("JST"), "Asia/Tokyo"); - assertEquals(ids.get("MIT"), "Pacific/Apia"); - assertEquals(ids.get("NET"), "Asia/Yerevan"); - assertEquals(ids.get("NST"), "Pacific/Auckland"); - assertEquals(ids.get("PLT"), "Asia/Karachi"); - assertEquals(ids.get("PNT"), "America/Phoenix"); - assertEquals(ids.get("PRT"), "America/Puerto_Rico"); - assertEquals(ids.get("PST"), "America/Los_Angeles"); - assertEquals(ids.get("SST"), "Pacific/Guadalcanal"); - assertEquals(ids.get("VST"), "Asia/Ho_Chi_Minh"); + assertEquals("America/Panama", ids.get("EST")); + assertEquals("America/Phoenix", ids.get("MST")); + assertEquals("Pacific/Honolulu", ids.get("HST")); + assertEquals("Australia/Darwin", ids.get("ACT")); + assertEquals("Australia/Sydney", ids.get("AET")); + assertEquals("America/Argentina/Buenos_Aires", ids.get("AGT")); + assertEquals("Africa/Cairo", ids.get("ART")); + assertEquals("America/Anchorage", ids.get("AST")); + assertEquals("America/Sao_Paulo", ids.get("BET")); + assertEquals("Asia/Dhaka", ids.get("BST")); + assertEquals("Africa/Harare", ids.get("CAT")); + assertEquals("America/St_Johns", ids.get("CNT")); + assertEquals("America/Chicago", ids.get("CST")); + assertEquals("Asia/Shanghai", ids.get("CTT")); + assertEquals("Africa/Addis_Ababa", ids.get("EAT")); + assertEquals("Europe/Paris", ids.get("ECT")); + assertEquals("America/Indiana/Indianapolis", ids.get("IET")); + assertEquals("Asia/Kolkata", ids.get("IST")); + assertEquals("Asia/Tokyo", ids.get("JST")); + assertEquals("Pacific/Apia", ids.get("MIT")); + assertEquals("Asia/Yerevan", ids.get("NET")); + assertEquals("Pacific/Auckland", ids.get("NST")); + assertEquals("Asia/Karachi", ids.get("PLT")); + assertEquals("America/Phoenix", ids.get("PNT")); + assertEquals("America/Puerto_Rico", ids.get("PRT")); + assertEquals("America/Los_Angeles", ids.get("PST")); + assertEquals("Pacific/Guadalcanal", ids.get("SST")); + assertEquals("Asia/Ho_Chi_Minh", ids.get("VST")); } - @Test(expectedExceptions=UnsupportedOperationException.class) + @Test public void test_constant_OLD_IDS_POST_2024b_immutable() { - Map ids = ZoneId.SHORT_IDS; - ids.clear(); + Assertions.assertThrows(UnsupportedOperationException.class, () -> { + Map ids = ZoneId.SHORT_IDS; + ids.clear(); + }); } //----------------------------------------------------------------------- @@ -141,11 +146,11 @@ public class TCKZoneId extends AbstractTCKTest { @Test public void test_getAvailableGroupIds() { Set zoneIds = ZoneId.getAvailableZoneIds(); - assertEquals(zoneIds.contains("Europe/London"), true); + assertEquals(true, zoneIds.contains("Europe/London")); zoneIds.clear(); - assertEquals(zoneIds.size(), 0); + assertEquals(0, zoneIds.size()); Set zoneIds2 = ZoneId.getAvailableZoneIds(); - assertEquals(zoneIds2.contains("Europe/London"), true); + assertEquals(true, zoneIds2.contains("Europe/London")); } //----------------------------------------------------------------------- @@ -157,7 +162,7 @@ public class TCKZoneId extends AbstractTCKTest { map.put("LONDON", "Europe/London"); map.put("PARIS", "Europe/Paris"); ZoneId test = ZoneId.of("LONDON", map); - assertEquals(test.getId(), "Europe/London"); + assertEquals("Europe/London", test.getId()); } @Test @@ -166,32 +171,35 @@ public class TCKZoneId extends AbstractTCKTest { map.put("LONDON", "Europe/London"); map.put("PARIS", "Europe/Paris"); ZoneId test = ZoneId.of("Europe/Madrid", map); - assertEquals(test.getId(), "Europe/Madrid"); + assertEquals("Europe/Madrid", test.getId()); } @Test public void test_of_string_Map_emptyMap() { Map map = new HashMap<>(); ZoneId test = ZoneId.of("Europe/Madrid", map); - assertEquals(test.getId(), "Europe/Madrid"); + assertEquals("Europe/Madrid", test.getId()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_of_string_Map_badFormat() { - Map map = new HashMap<>(); - ZoneId.of("Not known", map); + Assertions.assertThrows(DateTimeException.class, () -> { + Map map = new HashMap<>(); + ZoneId.of("Not known", map); + }); } - @Test(expectedExceptions=ZoneRulesException.class) + @Test public void test_of_string_Map_unknown() { - Map map = new HashMap<>(); - ZoneId.of("Unknown", map); + Assertions.assertThrows(ZoneRulesException.class, () -> { + Map map = new HashMap<>(); + ZoneId.of("Unknown", map); + }); } //----------------------------------------------------------------------- // regular factory and .normalized() //----------------------------------------------------------------------- - @DataProvider(name="offsetBasedValid") Object[][] data_offsetBasedValid() { return new Object[][] { {"Z", "Z"}, @@ -227,19 +235,19 @@ public class TCKZoneId extends AbstractTCKTest { }; } - @Test(dataProvider="offsetBasedValid") + @ParameterizedTest + @MethodSource("data_offsetBasedValid") public void factory_of_String_offsetBasedValid_noPrefix(String input, String id) { ZoneId test = ZoneId.of(input); - assertEquals(test.getId(), id); - assertEquals(test, ZoneOffset.of(id)); - assertEquals(test.normalized(), ZoneOffset.of(id)); - assertEquals(test.getDisplayName(TextStyle.FULL, Locale.UK), id); - assertEquals(test.getRules().isFixedOffset(), true); - assertEquals(test.getRules().getOffset(Instant.EPOCH), ZoneOffset.of(id)); + assertEquals(id, test.getId()); + assertEquals(ZoneOffset.of(id), test); + assertEquals(ZoneOffset.of(id), test.normalized()); + assertEquals(id, test.getDisplayName(TextStyle.FULL, Locale.UK)); + assertEquals(true, test.getRules().isFixedOffset()); + assertEquals(ZoneOffset.of(id), test.getRules().getOffset(Instant.EPOCH)); } //----------------------------------------------------------------------- - @DataProvider(name="offsetBasedValidPrefix") Object[][] data_offsetBasedValidPrefix() { return new Object[][] { {"", "", "Z"}, @@ -275,37 +283,40 @@ public class TCKZoneId extends AbstractTCKTest { }; } - @Test(dataProvider="offsetBasedValidPrefix") + @ParameterizedTest + @MethodSource("data_offsetBasedValidPrefix") public void factory_of_String_offsetBasedValid_prefixUTC(String input, String id, String offsetId) { ZoneId test = ZoneId.of("UTC" + input); - assertEquals(test.getId(), "UTC" + id); - assertEquals(test.getRules(), ZoneOffset.of(offsetId).getRules()); - assertEquals(test.normalized(), ZoneOffset.of(offsetId)); - assertEquals(test.getDisplayName(TextStyle.FULL, Locale.UK), displayName("UTC" + id)); - assertEquals(test.getRules().isFixedOffset(), true); - assertEquals(test.getRules().getOffset(Instant.EPOCH), ZoneOffset.of(offsetId)); + assertEquals("UTC" + id, test.getId()); + assertEquals(ZoneOffset.of(offsetId).getRules(), test.getRules()); + assertEquals(ZoneOffset.of(offsetId), test.normalized()); + assertEquals(displayName("UTC" + id), test.getDisplayName(TextStyle.FULL, Locale.UK)); + assertEquals(true, test.getRules().isFixedOffset()); + assertEquals(ZoneOffset.of(offsetId), test.getRules().getOffset(Instant.EPOCH)); } - @Test(dataProvider="offsetBasedValidPrefix") + @ParameterizedTest + @MethodSource("data_offsetBasedValidPrefix") public void factory_of_String_offsetBasedValid_prefixGMT(String input, String id, String offsetId) { ZoneId test = ZoneId.of("GMT" + input); - assertEquals(test.getId(), "GMT" + id); - assertEquals(test.getRules(), ZoneOffset.of(offsetId).getRules()); - assertEquals(test.normalized(), ZoneOffset.of(offsetId)); - assertEquals(test.getDisplayName(TextStyle.FULL, Locale.UK), displayName("GMT" + id)); - assertEquals(test.getRules().isFixedOffset(), true); - assertEquals(test.getRules().getOffset(Instant.EPOCH), ZoneOffset.of(offsetId)); + assertEquals("GMT" + id, test.getId()); + assertEquals(ZoneOffset.of(offsetId).getRules(), test.getRules()); + assertEquals(ZoneOffset.of(offsetId), test.normalized()); + assertEquals(displayName("GMT" + id), test.getDisplayName(TextStyle.FULL, Locale.UK)); + assertEquals(true, test.getRules().isFixedOffset()); + assertEquals(ZoneOffset.of(offsetId), test.getRules().getOffset(Instant.EPOCH)); } - @Test(dataProvider="offsetBasedValidPrefix") + @ParameterizedTest + @MethodSource("data_offsetBasedValidPrefix") public void factory_of_String_offsetBasedValid_prefixUT(String input, String id, String offsetId) { ZoneId test = ZoneId.of("UT" + input); - assertEquals(test.getId(), "UT" + id); - assertEquals(test.getRules(), ZoneOffset.of(offsetId).getRules()); - assertEquals(test.normalized(), ZoneOffset.of(offsetId)); - assertEquals(test.getDisplayName(TextStyle.FULL, Locale.UK), displayName("UT" + id)); - assertEquals(test.getRules().isFixedOffset(), true); - assertEquals(test.getRules().getOffset(Instant.EPOCH), ZoneOffset.of(offsetId)); + assertEquals("UT" + id, test.getId()); + assertEquals(ZoneOffset.of(offsetId).getRules(), test.getRules()); + assertEquals(ZoneOffset.of(offsetId), test.normalized()); + assertEquals(displayName("UT" + id), test.getDisplayName(TextStyle.FULL, Locale.UK)); + assertEquals(true, test.getRules().isFixedOffset()); + assertEquals(ZoneOffset.of(offsetId), test.getRules().getOffset(Instant.EPOCH)); } private String displayName(String id) { @@ -322,7 +333,6 @@ public class TCKZoneId extends AbstractTCKTest { } //----------------------------------------------------------------------- - @DataProvider(name="prefixValid") Object[][] data_prefixValid() { return new Object[][] { {"GMT", "+01:00"}, @@ -332,16 +342,16 @@ public class TCKZoneId extends AbstractTCKTest { }; } - @Test(dataProvider="prefixValid") + @ParameterizedTest + @MethodSource("data_prefixValid") public void test_prefixOfOffset(String prefix, String offset) { ZoneOffset zoff = ZoneOffset.of(offset); ZoneId zoneId = ZoneId.ofOffset(prefix, zoff); - assertEquals(zoneId.getId(), prefix + zoff.getId(), "in correct id for : " + prefix + ", zoff: " + zoff); + assertEquals(prefix + zoff.getId(), zoneId.getId(), "in correct id for : " + prefix + ", zoff: " + zoff); } //----------------------------------------------------------------------- - @DataProvider(name="prefixInvalid") Object[][] data_prefixInvalid() { return new Object[][] { {"GM", "+01:00"}, @@ -351,25 +361,27 @@ public class TCKZoneId extends AbstractTCKTest { }; } - @Test(dataProvider="prefixInvalid", expectedExceptions=java.lang.IllegalArgumentException.class) + @ParameterizedTest + @MethodSource("data_prefixInvalid") public void test_invalidPrefixOfOffset(String prefix, String offset) { - ZoneOffset zoff = ZoneOffset.of(offset); - ZoneId zoneId = ZoneId.ofOffset(prefix, zoff); - fail("should have thrown an exception for prefix: " + prefix); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + ZoneOffset zoff = ZoneOffset.of(offset); + ZoneId zoneId = ZoneId.ofOffset(prefix, zoff); + fail("should have thrown an exception for prefix: " + prefix); + }); } - @Test(expectedExceptions=java.lang.NullPointerException.class) + @Test public void test_nullPrefixOfOffset() { - ZoneId.ofOffset(null, ZoneOffset.ofTotalSeconds(1)); + Assertions.assertThrows(NullPointerException.class, () -> ZoneId.ofOffset(null, ZoneOffset.ofTotalSeconds(1))); } - @Test(expectedExceptions=java.lang.NullPointerException.class) + @Test public void test_nullOffsetOfOffset() { - ZoneId.ofOffset("GMT", null); + Assertions.assertThrows(NullPointerException.class, () -> ZoneId.ofOffset("GMT", null)); } //----------------------------------------------------------------------- - @DataProvider(name="offsetBasedValidOther") Object[][] data_offsetBasedValidOther() { return new Object[][] { {"GMT", "Z"}, @@ -393,16 +405,16 @@ public class TCKZoneId extends AbstractTCKTest { }; } - @Test(dataProvider="offsetBasedValidOther") + @ParameterizedTest + @MethodSource("data_offsetBasedValidOther") public void factory_of_String_offsetBasedValidOther(String input, String offsetId) { ZoneId test = ZoneId.of(input); - assertEquals(test.getId(), input); - assertEquals(test.getRules(), ZoneOffset.of(offsetId).getRules()); - assertEquals(test.normalized(), ZoneOffset.of(offsetId)); + assertEquals(input, test.getId()); + assertEquals(ZoneOffset.of(offsetId).getRules(), test.getRules()); + assertEquals(ZoneOffset.of(offsetId), test.normalized()); } //----------------------------------------------------------------------- - @DataProvider(name="offsetBasedInvalid") Object[][] data_offsetBasedInvalid() { return new Object[][] { {"A"}, {"B"}, {"C"}, {"D"}, {"E"}, {"F"}, {"G"}, {"H"}, {"I"}, {"J"}, {"K"}, {"L"}, {"M"}, @@ -427,37 +439,46 @@ public class TCKZoneId extends AbstractTCKTest { }; } - @Test(dataProvider="offsetBasedInvalid", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_offsetBasedInvalid") public void factory_of_String_offsetBasedInvalid_noPrefix(String id) { - if (id.equals("Z")) { - throw new DateTimeException("Fake exception: Z alone is valid, not invalid"); - } - ZoneId.of(id); + Assertions.assertThrows(DateTimeException.class, () -> { + if (id.equals("Z")) { + throw new DateTimeException("Fake exception: Z alone is valid, not invalid"); + } + ZoneId.of(id); + }); } - @Test(dataProvider="offsetBasedInvalid", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_offsetBasedInvalid") public void factory_of_String_offsetBasedInvalid_prefixUTC(String id) { - ZoneId.of("UTC" + id); + Assertions.assertThrows(DateTimeException.class, () -> ZoneId.of("UTC" + id)); } - @Test(dataProvider="offsetBasedInvalid", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_offsetBasedInvalid") public void factory_of_String_offsetBasedInvalid_prefixGMT(String id) { - if (id.equals("0")) { - throw new DateTimeException("Fake exception: GMT0 is valid, not invalid"); - } - ZoneId.of("GMT" + id); + Assertions.assertThrows(DateTimeException.class, () -> { + if (id.equals("0")) { + throw new DateTimeException("Fake exception: GMT0 is valid, not invalid"); + } + ZoneId.of("GMT" + id); + }); } - @Test(dataProvider="offsetBasedInvalid", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_offsetBasedInvalid") public void factory_of_String_offsetBasedInvalid_prefixUT(String id) { - if (id.equals("C")) { - throw new DateTimeException("Fake exception: UT + C = UTC, thus it is valid, not invalid"); - } - ZoneId.of("UT" + id); + Assertions.assertThrows(DateTimeException.class, () -> { + if (id.equals("C")) { + throw new DateTimeException("Fake exception: UT + C = UTC, thus it is valid, not invalid"); + } + ZoneId.of("UT" + id); + }); } //----------------------------------------------------------------------- - @DataProvider(name="regionBasedInvalid") Object[][] data_regionBasedInvalid() { // \u00ef is a random unicode character return new Object[][] { @@ -473,34 +494,35 @@ public class TCKZoneId extends AbstractTCKTest { }; } - @Test(dataProvider="regionBasedInvalid", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_regionBasedInvalid") public void factory_of_String_regionBasedInvalid(String id) { - ZoneId.of(id); + Assertions.assertThrows(DateTimeException.class, () -> ZoneId.of(id)); } //----------------------------------------------------------------------- @Test public void factory_of_String_region_EuropeLondon() { ZoneId test = ZoneId.of("Europe/London"); - assertEquals(test.getId(), "Europe/London"); - assertEquals(test.getRules().isFixedOffset(), false); - assertEquals(test.normalized(), test); + assertEquals("Europe/London", test.getId()); + assertEquals(false, test.getRules().isFixedOffset()); + assertEquals(test, test.normalized()); } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_String_null() { - ZoneId.of(null); + Assertions.assertThrows(NullPointerException.class, () -> ZoneId.of(null)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_of_String_badFormat() { - ZoneId.of("Unknown rule"); + Assertions.assertThrows(DateTimeException.class, () -> ZoneId.of("Unknown rule")); } - @Test(expectedExceptions=ZoneRulesException.class) + @Test public void factory_of_String_unknown() { - ZoneId.of("Unknown"); + Assertions.assertThrows(ZoneRulesException.class, () -> ZoneId.of("Unknown")); } //----------------------------------------------------------------------- @@ -526,23 +548,23 @@ public class TCKZoneId extends AbstractTCKTest { return TemporalAccessor.super.query(query); } }; - assertEquals(ZoneId.from(mock), ZoneId.of("Europe/Paris")); + assertEquals(ZoneId.of("Europe/Paris"), ZoneId.from(mock)); } @Test public void factory_from_TemporalAccessor_offset() { ZoneOffset offset = ZoneOffset.ofHours(1); - assertEquals(ZoneId.from(offset), offset); + assertEquals(offset, ZoneId.from(offset)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_from_TemporalAccessor_invalid_noDerive() { - ZoneId.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> ZoneId.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_from_TemporalAccessor_null() { - ZoneId.from(null); + Assertions.assertThrows(NullPointerException.class, () -> ZoneId.from(null)); } //----------------------------------------------------------------------- @@ -553,32 +575,31 @@ public class TCKZoneId extends AbstractTCKTest { ZoneId test1 = ZoneId.of("Europe/London"); ZoneId test2 = ZoneId.of("Europe/Paris"); ZoneId test2b = ZoneId.of("Europe/Paris"); - assertEquals(test1.equals(test2), false); - assertEquals(test2.equals(test1), false); + assertEquals(false, test1.equals(test2)); + assertEquals(false, test2.equals(test1)); - assertEquals(test1.equals(test1), true); - assertEquals(test2.equals(test2), true); - assertEquals(test2.equals(test2b), true); + assertEquals(true, test1.equals(test1)); + assertEquals(true, test2.equals(test2)); + assertEquals(true, test2.equals(test2b)); - assertEquals(test1.hashCode() == test1.hashCode(), true); - assertEquals(test2.hashCode() == test2.hashCode(), true); - assertEquals(test2.hashCode() == test2b.hashCode(), true); + assertEquals(true, test1.hashCode() == test1.hashCode()); + assertEquals(true, test2.hashCode() == test2.hashCode()); + assertEquals(true, test2.hashCode() == test2b.hashCode()); } @Test public void test_equals_null() { - assertEquals(ZoneId.of("Europe/London").equals(null), false); + assertEquals(false, ZoneId.of("Europe/London").equals(null)); } @Test public void test_equals_notEqualWrongType() { - assertEquals(ZoneId.of("Europe/London").equals("Europe/London"), false); + assertEquals(false, ZoneId.of("Europe/London").equals("Europe/London")); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="toString") Object[][] data_toString() { return new Object[][] { {"Europe/London", "Europe/London"}, @@ -591,10 +612,11 @@ public class TCKZoneId extends AbstractTCKTest { }; } - @Test(dataProvider="toString") + @ParameterizedTest + @MethodSource("data_toString") public void test_toString(String id, String expected) { ZoneId test = ZoneId.of(id); - assertEquals(test.toString(), expected); + assertEquals(expected, test.toString()); } } diff --git a/test/jdk/java/time/tck/java/time/TCKZoneOffset.java b/test/jdk/java/time/tck/java/time/TCKZoneOffset.java index 76466431033..d8a8376fa80 100644 --- a/test/jdk/java/time/tck/java/time/TCKZoneOffset.java +++ b/test/jdk/java/time/tck/java/time/TCKZoneOffset.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -60,10 +60,11 @@ package tck.java.time; import static java.time.temporal.ChronoField.OFFSET_SECONDS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; @@ -87,13 +88,16 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test ZoneOffset. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKZoneOffset extends AbstractDateTimeTest { //----------------------------------------------------------------------- @@ -185,9 +189,9 @@ public class TCKZoneOffset extends AbstractDateTimeTest { } } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_string_null() { - ZoneOffset.of((String) null); + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffset.of((String) null)); } //----------------------------------------------------------------------- @@ -302,14 +306,14 @@ public class TCKZoneOffset extends AbstractDateTimeTest { } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_tooBig() { - ZoneOffset.ofHours(19); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHours(19)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_tooSmall() { - ZoneOffset.ofHours(-19); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHours(-19)); } //----------------------------------------------------------------------- @@ -329,14 +333,14 @@ public class TCKZoneOffset extends AbstractDateTimeTest { doTestOffset(test2, 18, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_tooBig() { - ZoneOffset.ofHoursMinutes(19, 0); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutes(19, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_tooSmall() { - ZoneOffset.ofHoursMinutes(-19, 0); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutes(-19, 0)); } //----------------------------------------------------------------------- @@ -359,102 +363,102 @@ public class TCKZoneOffset extends AbstractDateTimeTest { doTestOffset(test2, 18, 0, 0); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_plusHoursMinusMinutes() { - ZoneOffset.ofHoursMinutesSeconds(1, -1, 0); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(1, -1, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_plusHoursMinusSeconds() { - ZoneOffset.ofHoursMinutesSeconds(1, 0, -1); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(1, 0, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_minusHoursPlusMinutes() { - ZoneOffset.ofHoursMinutesSeconds(-1, 1, 0); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(-1, 1, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_minusHoursPlusSeconds() { - ZoneOffset.ofHoursMinutesSeconds(-1, 0, 1); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(-1, 0, 1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_zeroHoursMinusMinutesPlusSeconds() { - ZoneOffset.ofHoursMinutesSeconds(0, -1, 1); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(0, -1, 1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_zeroHoursPlusMinutesMinusSeconds() { - ZoneOffset.ofHoursMinutesSeconds(0, 1, -1); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(0, 1, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_minutesTooLarge() { - ZoneOffset.ofHoursMinutesSeconds(0, 60, 0); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(0, 60, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_minutesTooSmall() { - ZoneOffset.ofHoursMinutesSeconds(0, -60, 0); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(0, -60, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_secondsTooLarge() { - ZoneOffset.ofHoursMinutesSeconds(0, 0, 60); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(0, 0, 60)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_secondsTooSmall() { - ZoneOffset.ofHoursMinutesSeconds(0, 0, 60); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(0, 0, 60)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_hoursTooBig() { - ZoneOffset.ofHoursMinutesSeconds(19, 0, 0); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(19, 0, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_hoursTooSmall() { - ZoneOffset.ofHoursMinutesSeconds(-19, 0, 0); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(-19, 0, 0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_minutesMinValue() { - ZoneOffset.ofHoursMinutesSeconds(0, Integer.MIN_VALUE, -1); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(0, Integer.MIN_VALUE, -1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_secondsMinValue() { - ZoneOffset.ofHoursMinutesSeconds(0, 0, Integer.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(0, 0, Integer.MIN_VALUE)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_int_hours_minutes_seconds_minutesAndSecondsMinValue() { - ZoneOffset.ofHoursMinutesSeconds(0, Integer.MIN_VALUE, Integer.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofHoursMinutesSeconds(0, Integer.MIN_VALUE, Integer.MIN_VALUE)); } //----------------------------------------------------------------------- @Test public void test_factory_ofTotalSeconds() { - assertEquals(ZoneOffset.ofTotalSeconds(60 * 60 + 1), ZoneOffset.ofHoursMinutesSeconds(1, 0, 1)); - assertEquals(ZoneOffset.ofTotalSeconds(18 * 60 * 60), ZoneOffset.ofHours(18)); - assertEquals(ZoneOffset.ofTotalSeconds(-18 * 60 * 60), ZoneOffset.ofHours(-18)); + assertEquals(ZoneOffset.ofHoursMinutesSeconds(1, 0, 1), ZoneOffset.ofTotalSeconds(60 * 60 + 1)); + assertEquals(ZoneOffset.ofHours(18), ZoneOffset.ofTotalSeconds(18 * 60 * 60)); + assertEquals(ZoneOffset.ofHours(-18), ZoneOffset.ofTotalSeconds(-18 * 60 * 60)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ofTotalSeconds_tooLarge() { - ZoneOffset.ofTotalSeconds(18 * 60 * 60 + 1); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofTotalSeconds(18 * 60 * 60 + 1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ofTotalSeconds_tooSmall() { - ZoneOffset.ofTotalSeconds(-18 * 60 * 60 - 1); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofTotalSeconds(-18 * 60 * 60 - 1)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_ofTotalSeconds_minValue() { - ZoneOffset.ofTotalSeconds(Integer.MIN_VALUE); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.ofTotalSeconds(Integer.MIN_VALUE)); } //----------------------------------------------------------------------- @@ -462,18 +466,18 @@ public class TCKZoneOffset extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_factory_CalendricalObject() { - assertEquals(ZoneOffset.from(ZonedDateTime.of(LocalDateTime.of(LocalDate.of(2007, 7, 15), - LocalTime.of(17, 30)), ZoneOffset.ofHours(2))), ZoneOffset.ofHours(2)); + assertEquals(ZoneOffset.ofHours(2), ZoneOffset.from(ZonedDateTime.of(LocalDateTime.of(LocalDate.of(2007, 7, 15), + LocalTime.of(17, 30)), ZoneOffset.ofHours(2)))); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_factory_CalendricalObject_invalid_noDerive() { - ZoneOffset.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> ZoneOffset.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_CalendricalObject_null() { - ZoneOffset.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffset.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- @@ -482,7 +486,7 @@ public class TCKZoneOffset extends AbstractDateTimeTest { @Test public void test_getTotalSeconds() { ZoneOffset offset = ZoneOffset.ofTotalSeconds(60 * 60 + 1); - assertEquals(offset.getTotalSeconds(), 60 * 60 + 1); + assertEquals(60 * 60 + 1, offset.getTotalSeconds()); } //----------------------------------------------------------------------- @@ -491,11 +495,11 @@ public class TCKZoneOffset extends AbstractDateTimeTest { @Test public void test_getId() { ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(1, 0, 0); - assertEquals(offset.getId(), "+01:00"); + assertEquals("+01:00", offset.getId()); offset = ZoneOffset.ofHoursMinutesSeconds(1, 2, 3); - assertEquals(offset.getId(), "+01:02:03"); + assertEquals("+01:02:03", offset.getId()); offset = ZoneOffset.UTC; - assertEquals(offset.getId(), "Z"); + assertEquals("Z", offset.getId()); } //----------------------------------------------------------------------- @@ -504,21 +508,21 @@ public class TCKZoneOffset extends AbstractDateTimeTest { @Test public void test_getRules() { ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(1, 2, 3); - assertEquals(offset.getRules().isFixedOffset(), true); - assertEquals(offset.getRules().getOffset((Instant) null), offset); - assertEquals(offset.getRules().getDaylightSavings((Instant) null), Duration.ZERO); - assertEquals(offset.getRules().getStandardOffset((Instant) null), offset); - assertEquals(offset.getRules().nextTransition((Instant) null), null); - assertEquals(offset.getRules().previousTransition((Instant) null), null); + assertEquals(true, offset.getRules().isFixedOffset()); + assertEquals(offset, offset.getRules().getOffset((Instant) null)); + assertEquals(Duration.ZERO, offset.getRules().getDaylightSavings((Instant) null)); + assertEquals(offset, offset.getRules().getStandardOffset((Instant) null)); + assertEquals(null, offset.getRules().nextTransition((Instant) null)); + assertEquals(null, offset.getRules().previousTransition((Instant) null)); - assertEquals(offset.getRules().isValidOffset((LocalDateTime) null, offset), true); - assertEquals(offset.getRules().isValidOffset((LocalDateTime) null, ZoneOffset.UTC), false); - assertEquals(offset.getRules().isValidOffset((LocalDateTime) null, null), false); - assertEquals(offset.getRules().getOffset((LocalDateTime) null), offset); - assertEquals(offset.getRules().getValidOffsets((LocalDateTime) null), Arrays.asList(offset)); - assertEquals(offset.getRules().getTransition((LocalDateTime) null), null); - assertEquals(offset.getRules().getTransitions().size(), 0); - assertEquals(offset.getRules().getTransitionRules().size(), 0); + assertEquals(true, offset.getRules().isValidOffset((LocalDateTime) null, offset)); + assertEquals(false, offset.getRules().isValidOffset((LocalDateTime) null, ZoneOffset.UTC)); + assertEquals(false, offset.getRules().isValidOffset((LocalDateTime) null, null)); + assertEquals(offset, offset.getRules().getOffset((LocalDateTime) null)); + assertEquals(Arrays.asList(offset), offset.getRules().getValidOffsets((LocalDateTime) null)); + assertEquals(null, offset.getRules().getTransition((LocalDateTime) null)); + assertEquals(0, offset.getRules().getTransitions().size()); + assertEquals(0, offset.getRules().getTransitionRules().size()); } //----------------------------------------------------------------------- @@ -526,22 +530,21 @@ public class TCKZoneOffset extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_get_TemporalField() { - assertEquals(ZoneOffset.UTC.get(OFFSET_SECONDS), 0); - assertEquals(ZoneOffset.ofHours(-2).get(OFFSET_SECONDS), -7200); - assertEquals(ZoneOffset.ofHoursMinutesSeconds(0, 1, 5).get(OFFSET_SECONDS), 65); + assertEquals(0, ZoneOffset.UTC.get(OFFSET_SECONDS)); + assertEquals(-7200, ZoneOffset.ofHours(-2).get(OFFSET_SECONDS)); + assertEquals(65, ZoneOffset.ofHoursMinutesSeconds(0, 1, 5).get(OFFSET_SECONDS)); } @Test public void test_getLong_TemporalField() { - assertEquals(ZoneOffset.UTC.getLong(OFFSET_SECONDS), 0); - assertEquals(ZoneOffset.ofHours(-2).getLong(OFFSET_SECONDS), -7200); - assertEquals(ZoneOffset.ofHoursMinutesSeconds(0, 1, 5).getLong(OFFSET_SECONDS), 65); + assertEquals(0, ZoneOffset.UTC.getLong(OFFSET_SECONDS)); + assertEquals(-7200, ZoneOffset.ofHours(-2).getLong(OFFSET_SECONDS)); + assertEquals(65, ZoneOffset.ofHoursMinutesSeconds(0, 1, 5).getLong(OFFSET_SECONDS)); } //----------------------------------------------------------------------- // query(TemporalQuery) //----------------------------------------------------------------------- - @DataProvider(name="query") Object[][] data_query() { return new Object[][] { {ZoneOffset.UTC, TemporalQueries.chronology(), null}, @@ -554,19 +557,21 @@ public class TCKZoneOffset extends AbstractDateTimeTest { }; } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_query(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(temporal.query(query), expected); + assertEquals(expected, temporal.query(query)); } - @Test(dataProvider="query") + @ParameterizedTest + @MethodSource("data_query") public void test_queryFrom(TemporalAccessor temporal, TemporalQuery query, T expected) { - assertEquals(query.queryFrom(temporal), expected); + assertEquals(expected, query.queryFrom(temporal)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - ZoneOffset.UTC.query(null); + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffset.UTC.query(null)); } //----------------------------------------------------------------------- @@ -590,16 +595,16 @@ public class TCKZoneOffset extends AbstractDateTimeTest { ZoneOffset offset1 = ZoneOffset.ofHoursMinutesSeconds(1, 2, 3); ZoneOffset offset2 = ZoneOffset.ofHoursMinutesSeconds(2, 3, 4); ZoneOffset offset2b = ZoneOffset.ofHoursMinutesSeconds(2, 3, 4); - assertEquals(offset1.equals(offset2), false); - assertEquals(offset2.equals(offset1), false); + assertEquals(false, offset1.equals(offset2)); + assertEquals(false, offset2.equals(offset1)); - assertEquals(offset1.equals(offset1), true); - assertEquals(offset2.equals(offset2), true); - assertEquals(offset2.equals(offset2b), true); + assertEquals(true, offset1.equals(offset1)); + assertEquals(true, offset2.equals(offset2)); + assertEquals(true, offset2.equals(offset2b)); - assertEquals(offset1.hashCode() == offset1.hashCode(), true); - assertEquals(offset2.hashCode() == offset2.hashCode(), true); - assertEquals(offset2.hashCode() == offset2b.hashCode(), true); + assertEquals(true, offset1.hashCode() == offset1.hashCode()); + assertEquals(true, offset2.hashCode() == offset2.hashCode()); + assertEquals(true, offset2.hashCode() == offset2b.hashCode()); } //----------------------------------------------------------------------- @@ -612,11 +617,11 @@ public class TCKZoneOffset extends AbstractDateTimeTest { //Do not change offset of ZonedDateTime after adjustInto() ZonedDateTime zonedDateTime_target = ZonedDateTime.of(LocalDate.of(1909, 2, 2), LocalTime.of(10, 10, 10), ZoneId.of(zoneId)); ZonedDateTime zonedDateTime_result = (ZonedDateTime)(base.adjustInto(zonedDateTime_target)); - assertEquals(zonedDateTime_target.getOffset(), zonedDateTime_result.getOffset()); + assertEquals(zonedDateTime_result.getOffset(), zonedDateTime_target.getOffset()); OffsetDateTime offsetDateTime_target = zonedDateTime_target.toOffsetDateTime(); OffsetDateTime offsetDateTime_result = (OffsetDateTime)(base.adjustInto(offsetDateTime_target)); - assertEquals(base, offsetDateTime_result.getOffset()); + assertEquals(offsetDateTime_result.getOffset(), base); } } @@ -626,19 +631,21 @@ public class TCKZoneOffset extends AbstractDateTimeTest { for (int i=-18; i<=18; i++) { OffsetDateTime offsetDateTime_target = OffsetDateTime.of(LocalDate.of(1909, 2, 2), LocalTime.of(10, 10, 10), ZoneOffset.ofHours(i)); OffsetDateTime offsetDateTime_result = (OffsetDateTime)base.adjustInto(offsetDateTime_target); - assertEquals(base, offsetDateTime_result.getOffset()); + assertEquals(offsetDateTime_result.getOffset(), base); //Do not change offset of ZonedDateTime after adjustInto() ZonedDateTime zonedDateTime_target = offsetDateTime_target.toZonedDateTime(); ZonedDateTime zonedDateTime_result = (ZonedDateTime)(base.adjustInto(zonedDateTime_target)); - assertEquals(zonedDateTime_target.getOffset(), zonedDateTime_result.getOffset()); + assertEquals(zonedDateTime_result.getOffset(), zonedDateTime_target.getOffset()); } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_adjustInto_dateOnly() { - ZoneOffset base = ZoneOffset.ofHoursMinutesSeconds(1, 1, 1); - base.adjustInto((LocalDate.of(1909, 2, 2))); + Assertions.assertThrows(DateTimeException.class, () -> { + ZoneOffset base = ZoneOffset.ofHoursMinutesSeconds(1, 1, 1); + base.adjustInto((LocalDate.of(1909, 2, 2))); + }); } //----------------------------------------------------------------------- @@ -647,18 +654,18 @@ public class TCKZoneOffset extends AbstractDateTimeTest { @Test public void test_toString() { ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(1, 0, 0); - assertEquals(offset.toString(), "+01:00"); + assertEquals("+01:00", offset.toString()); offset = ZoneOffset.ofHoursMinutesSeconds(1, 2, 3); - assertEquals(offset.toString(), "+01:02:03"); + assertEquals("+01:02:03", offset.toString()); offset = ZoneOffset.UTC; - assertEquals(offset.toString(), "Z"); + assertEquals("Z", offset.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- private void doTestOffset(ZoneOffset offset, int hours, int minutes, int seconds) { - assertEquals(offset.getTotalSeconds(), hours * 60 * 60 + minutes * 60 + seconds); + assertEquals(hours * 60 * 60 + minutes * 60 + seconds, offset.getTotalSeconds()); final String id; if (hours == 0 && minutes == 0 && seconds == 0) { id = "Z"; @@ -673,16 +680,16 @@ public class TCKZoneOffset extends AbstractDateTimeTest { } id = str; } - assertEquals(offset.getId(), id); - assertEquals(offset, ZoneOffset.ofHoursMinutesSeconds(hours, minutes, seconds)); + assertEquals(id, offset.getId()); + assertEquals(ZoneOffset.ofHoursMinutesSeconds(hours, minutes, seconds), offset); if (seconds == 0) { - assertEquals(offset, ZoneOffset.ofHoursMinutes(hours, minutes)); + assertEquals(ZoneOffset.ofHoursMinutes(hours, minutes), offset); if (minutes == 0) { - assertEquals(offset, ZoneOffset.ofHours(hours)); + assertEquals(ZoneOffset.ofHours(hours), offset); } } - assertEquals(ZoneOffset.of(id), offset); - assertEquals(offset.toString(), id); + assertEquals(offset, ZoneOffset.of(id)); + assertEquals(id, offset.toString()); } } diff --git a/test/jdk/java/time/tck/java/time/TCKZonedDateTime.java b/test/jdk/java/time/tck/java/time/TCKZonedDateTime.java index 8ca935c04e5..73adbbba88c 100644 --- a/test/jdk/java/time/tck/java/time/TCKZonedDateTime.java +++ b/test/jdk/java/time/tck/java/time/TCKZonedDateTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -95,8 +95,9 @@ import static java.time.temporal.ChronoUnit.HOURS; import static java.time.temporal.ChronoUnit.MINUTES; import static java.time.temporal.ChronoUnit.NANOS; import static java.time.temporal.ChronoUnit.SECONDS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; @@ -133,14 +134,17 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test ZonedDateTime. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKZonedDateTime extends AbstractDateTimeTest { private static final ZoneOffset OFFSET_0100 = ZoneOffset.ofHours(1); @@ -160,7 +164,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { private ZonedDateTime TEST_DATE_TIME; private ZonedDateTime TEST_DATE_TIME_PARIS; - @BeforeMethod + @BeforeEach public void setUp() { TEST_LOCAL_2008_06_30_11_30_59_500 = LocalDateTime.of(2008, 6, 30, 11, 30, 59, 500); TEST_DATE_TIME = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); @@ -172,7 +176,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Override protected List samples() { - TemporalAccessor[] array = {TEST_DATE_TIME, }; + TemporalAccessor[] array = {ZonedDateTime.of(LocalDateTime.of(2008, 6, 30, 11, 30, 59, 500), ZONE_0100), }; return Arrays.asList(array); } @@ -243,9 +247,9 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- // now(ZoneId) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_ZoneId_nullZoneId() { - ZonedDateTime.now((ZoneId) null); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.now((ZoneId) null)); } @Test @@ -253,16 +257,15 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZoneId zone = ZoneId.of("UTC+01:02:03"); ZonedDateTime expected = ZonedDateTime.now(Clock.system(zone)); ZonedDateTime test = ZonedDateTime.now(zone); - assertEquals(Duration.between(expected, test).truncatedTo(ChronoUnit.SECONDS), - Duration.ZERO); + assertEquals(Duration.ZERO, Duration.between(expected, test).truncatedTo(ChronoUnit.SECONDS)); } //----------------------------------------------------------------------- // now(Clock) //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void now_Clock_nullClock() { - ZonedDateTime.now((Clock) null); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.now((Clock) null)); } @Test @@ -271,15 +274,15 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); ZonedDateTime test = ZonedDateTime.now(clock); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60 ? 1 : 2)); - assertEquals(test.getHour(), (i / (60 * 60)) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); - assertEquals(test.getNano(), 123456789); - assertEquals(test.getOffset(), ZoneOffset.UTC); - assertEquals(test.getZone(), ZoneOffset.UTC); + assertEquals(1970, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals((i < 24 * 60 * 60 ? 1 : 2), test.getDayOfMonth()); + assertEquals((i / (60 * 60)) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); + assertEquals(123456789, test.getNano()); + assertEquals(ZoneOffset.UTC, test.getOffset()); + assertEquals(ZoneOffset.UTC, test.getZone()); } } @@ -291,7 +294,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZonedDateTime expected = ZonedDateTime.ofInstant(instant, zone); Clock clock = Clock.fixed(expected.toInstant(), zone); ZonedDateTime test = ZonedDateTime.now(clock); - assertEquals(test, expected); + assertEquals(expected, test); } } @@ -302,13 +305,13 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); ZonedDateTime test = ZonedDateTime.now(clock); - assertEquals(test.getYear(), 1969); - assertEquals(test.getMonth(), Month.DECEMBER); - assertEquals(test.getDayOfMonth(), 31); + assertEquals(1969, test.getYear()); + assertEquals(Month.DECEMBER, test.getMonth()); + assertEquals(31, test.getDayOfMonth()); expected = expected.minusSeconds(1); - assertEquals(test.toLocalTime(), expected); - assertEquals(test.getOffset(), ZoneOffset.UTC); - assertEquals(test.getZone(), ZoneOffset.UTC); + assertEquals(expected, test.toLocalTime()); + assertEquals(ZoneOffset.UTC, test.getOffset()); + assertEquals(ZoneOffset.UTC, test.getZone()); } } @@ -319,12 +322,12 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZoneOffset offset = ZoneOffset.ofHours(i); Clock clock = Clock.fixed(base.toInstant(), offset); ZonedDateTime test = ZonedDateTime.now(clock); - assertEquals(test.getHour(), (12 + i) % 24); - assertEquals(test.getMinute(), 0); - assertEquals(test.getSecond(), 0); - assertEquals(test.getNano(), 0); - assertEquals(test.getOffset(), offset); - assertEquals(test.getZone(), offset); + assertEquals((12 + i) % 24, test.getHour()); + assertEquals(0, test.getMinute()); + assertEquals(0, test.getSecond()); + assertEquals(0, test.getNano()); + assertEquals(offset, test.getOffset()); + assertEquals(offset, test.getZone()); } } @@ -332,15 +335,15 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { // dateTime factories //----------------------------------------------------------------------- void check(ZonedDateTime test, int y, int m, int d, int h, int min, int s, int n, ZoneOffset offset, ZoneId zone) { - assertEquals(test.getYear(), y); - assertEquals(test.getMonth().getValue(), m); - assertEquals(test.getDayOfMonth(), d); - assertEquals(test.getHour(), h); - assertEquals(test.getMinute(), min); - assertEquals(test.getSecond(), s); - assertEquals(test.getNano(), n); - assertEquals(test.getOffset(), offset); - assertEquals(test.getZone(), zone); + assertEquals(y, test.getYear()); + assertEquals(m, test.getMonth().getValue()); + assertEquals(d, test.getDayOfMonth()); + assertEquals(h, test.getHour()); + assertEquals(min, test.getMinute()); + assertEquals(s, test.getSecond()); + assertEquals(n, test.getNano()); + assertEquals(offset, test.getOffset()); + assertEquals(zone, test.getZone()); } //----------------------------------------------------------------------- @@ -364,19 +367,19 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { check(test, 2008, 10, 26, 2, 30, 0, 0, OFFSET_0200, ZONE_PARIS); // same time in summer offset } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDateLocalTime_nullDate() { - ZonedDateTime.of((LocalDate) null, LocalTime.of(11, 30, 10, 500), ZONE_PARIS); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.of((LocalDate) null, LocalTime.of(11, 30, 10, 500), ZONE_PARIS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDateLocalTime_nullTime() { - ZonedDateTime.of(LocalDate.of(2008, 6, 30), (LocalTime) null, ZONE_PARIS); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.of(LocalDate.of(2008, 6, 30), (LocalTime) null, ZONE_PARIS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDateLocalTime_nullZone() { - ZonedDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 10, 500), null); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 10, 500), null)); } //----------------------------------------------------------------------- @@ -401,15 +404,17 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { check(test, 2008, 10, 26, 2, 30, 0, 0, OFFSET_0200, ZONE_PARIS); // same time in summer offset } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDateTime_nullDateTime() { - ZonedDateTime.of((LocalDateTime) null, ZONE_PARIS); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.of((LocalDateTime) null, ZONE_PARIS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_of_LocalDateTime_nullZone() { - LocalDateTime base = LocalDateTime.of(2008, 6, 30, 11, 30, 10, 500); - ZonedDateTime.of(base, null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDateTime base = LocalDateTime.of(2008, 6, 30, 11, 30, 10, 500); + ZonedDateTime.of(base, null); + }); } //----------------------------------------------------------------------- @@ -471,12 +476,12 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { for (int i = 0; i < (24 * 60 * 60); i++) { Instant instant = Instant.ofEpochSecond(i); ZonedDateTime test = ZonedDateTime.ofInstant(instant, OFFSET_0100); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), 1 + (i >= 23 * 60 * 60 ? 1 : 0)); - assertEquals(test.getHour(), ((i / (60 * 60)) + 1) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); + assertEquals(1970, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals(1 + (i >= 23 * 60 * 60 ? 1 : 0), test.getDayOfMonth()); + assertEquals(((i / (60 * 60)) + 1) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); } } @@ -487,7 +492,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { for (long i = 0; i < 146097; i++) { Instant instant = Instant.ofEpochSecond(i * 24L * 60L * 60L); ZonedDateTime test = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); - assertEquals(test, expected); + assertEquals(expected, test); expected = expected.plusDays(1); } } @@ -499,14 +504,14 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L - OFFSET_MIN.getTotalSeconds()); ZonedDateTime test = ZonedDateTime.ofInstant(instant, OFFSET_MIN); - assertEquals(test.getYear(), Year.MIN_VALUE); - assertEquals(test.getMonth().getValue(), 1); - assertEquals(test.getDayOfMonth(), 1); - assertEquals(test.getOffset(), OFFSET_MIN); - assertEquals(test.getHour(), 0); - assertEquals(test.getMinute(), 0); - assertEquals(test.getSecond(), 0); - assertEquals(test.getNano(), 0); + assertEquals(Year.MIN_VALUE, test.getYear()); + assertEquals(1, test.getMonth().getValue()); + assertEquals(1, test.getDayOfMonth()); + assertEquals(OFFSET_MIN, test.getOffset()); + assertEquals(0, test.getHour()); + assertEquals(0, test.getMinute()); + assertEquals(0, test.getSecond()); + assertEquals(0, test.getNano()); } @Test @@ -516,14 +521,14 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L - OFFSET_MAX.getTotalSeconds()); ZonedDateTime test = ZonedDateTime.ofInstant(instant, OFFSET_MAX); - assertEquals(test.getYear(), Year.MIN_VALUE); - assertEquals(test.getMonth().getValue(), 1); - assertEquals(test.getDayOfMonth(), 1); - assertEquals(test.getOffset(), OFFSET_MAX); - assertEquals(test.getHour(), 0); - assertEquals(test.getMinute(), 0); - assertEquals(test.getSecond(), 0); - assertEquals(test.getNano(), 0); + assertEquals(Year.MIN_VALUE, test.getYear()); + assertEquals(1, test.getMonth().getValue()); + assertEquals(1, test.getDayOfMonth()); + assertEquals(OFFSET_MAX, test.getOffset()); + assertEquals(0, test.getHour()); + assertEquals(0, test.getMinute()); + assertEquals(0, test.getSecond()); + assertEquals(0, test.getNano()); } @Test @@ -533,14 +538,14 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { long days = (year * 365L + (year / 4 - year / 100 + year / 400)) + 365 - days_0000_to_1970; Instant instant = Instant.ofEpochSecond((days + 1) * 24L * 60L * 60L - 1 - OFFSET_MIN.getTotalSeconds()); ZonedDateTime test = ZonedDateTime.ofInstant(instant, OFFSET_MIN); - assertEquals(test.getYear(), Year.MAX_VALUE); - assertEquals(test.getMonth().getValue(), 12); - assertEquals(test.getDayOfMonth(), 31); - assertEquals(test.getOffset(), OFFSET_MIN); - assertEquals(test.getHour(), 23); - assertEquals(test.getMinute(), 59); - assertEquals(test.getSecond(), 59); - assertEquals(test.getNano(), 0); + assertEquals(Year.MAX_VALUE, test.getYear()); + assertEquals(12, test.getMonth().getValue()); + assertEquals(31, test.getDayOfMonth()); + assertEquals(OFFSET_MIN, test.getOffset()); + assertEquals(23, test.getHour()); + assertEquals(59, test.getMinute()); + assertEquals(59, test.getSecond()); + assertEquals(0, test.getNano()); } @Test @@ -550,55 +555,63 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { long days = (year * 365L + (year / 4 - year / 100 + year / 400)) + 365 - days_0000_to_1970; Instant instant = Instant.ofEpochSecond((days + 1) * 24L * 60L * 60L - 1 - OFFSET_MAX.getTotalSeconds()); ZonedDateTime test = ZonedDateTime.ofInstant(instant, OFFSET_MAX); - assertEquals(test.getYear(), Year.MAX_VALUE); - assertEquals(test.getMonth().getValue(), 12); - assertEquals(test.getDayOfMonth(), 31); - assertEquals(test.getOffset(), OFFSET_MAX); - assertEquals(test.getHour(), 23); - assertEquals(test.getMinute(), 59); - assertEquals(test.getSecond(), 59); - assertEquals(test.getNano(), 0); + assertEquals(Year.MAX_VALUE, test.getYear()); + assertEquals(12, test.getMonth().getValue()); + assertEquals(31, test.getDayOfMonth()); + assertEquals(OFFSET_MAX, test.getOffset()); + assertEquals(23, test.getHour()); + assertEquals(59, test.getMinute()); + assertEquals(59, test.getSecond()); + assertEquals(0, test.getNano()); } //----------------------------------------------------------------------- - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_maxInstantWithMaxOffset() { - Instant instant = Instant.ofEpochSecond(Long.MAX_VALUE); - ZonedDateTime.ofInstant(instant, OFFSET_MAX); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant instant = Instant.ofEpochSecond(Long.MAX_VALUE); + ZonedDateTime.ofInstant(instant, OFFSET_MAX); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_maxInstantWithMinOffset() { - Instant instant = Instant.ofEpochSecond(Long.MAX_VALUE); - ZonedDateTime.ofInstant(instant, OFFSET_MIN); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant instant = Instant.ofEpochSecond(Long.MAX_VALUE); + ZonedDateTime.ofInstant(instant, OFFSET_MIN); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_tooBig() { - long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); - long year = Year.MAX_VALUE + 1L; - long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; - Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L); - ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); + Assertions.assertThrows(DateTimeException.class, () -> { + long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); + long year = Year.MAX_VALUE + 1L; + long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; + Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L); + ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_tooLow() { - long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); - int year = Year.MIN_VALUE - 1; - long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; - Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L); - ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); + Assertions.assertThrows(DateTimeException.class, () -> { + long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); + int year = Year.MIN_VALUE - 1; + long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; + Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L); + ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_Instant_nullInstant() { - ZonedDateTime.ofInstant((Instant) null, ZONE_0100); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.ofInstant((Instant) null, ZONE_0100)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_Instant_nullZone() { - ZonedDateTime.ofInstant(Instant.EPOCH, null); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.ofInstant(Instant.EPOCH, null)); } //----------------------------------------------------------------------- @@ -611,49 +624,55 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { check(test, 2008, 6, 30, 11, 30, 10, 500, OFFSET_0200, ZONE_PARIS); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofStrict_LDT_ZI_ZO_inGap() { - try { - ZonedDateTime.ofStrict(TEST_PARIS_GAP_2008_03_30_02_30, OFFSET_0100, ZONE_PARIS); - } catch (DateTimeException ex) { - assertEquals(ex.getMessage().contains(" gap"), true); - throw ex; - } + Assertions.assertThrows(DateTimeException.class, () -> { + try { + ZonedDateTime.ofStrict(TEST_PARIS_GAP_2008_03_30_02_30, OFFSET_0100, ZONE_PARIS); + } catch (DateTimeException ex) { + assertEquals(true, ex.getMessage().contains(" gap")); + throw ex; + } + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofStrict_LDT_ZI_ZO_inOverlap_invalidOfset() { - try { - ZonedDateTime.ofStrict(TEST_PARIS_OVERLAP_2008_10_26_02_30, OFFSET_0130, ZONE_PARIS); - } catch (DateTimeException ex) { - assertEquals(ex.getMessage().contains(" is not valid for "), true); - throw ex; - } + Assertions.assertThrows(DateTimeException.class, () -> { + try { + ZonedDateTime.ofStrict(TEST_PARIS_OVERLAP_2008_10_26_02_30, OFFSET_0130, ZONE_PARIS); + } catch (DateTimeException ex) { + assertEquals(true, ex.getMessage().contains(" is not valid for ")); + throw ex; + } + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofStrict_LDT_ZI_ZO_invalidOffset() { - try { - ZonedDateTime.ofStrict(TEST_LOCAL_2008_06_30_11_30_59_500, OFFSET_0130, ZONE_PARIS); - } catch (DateTimeException ex) { - assertEquals(ex.getMessage().contains(" is not valid for "), true); - throw ex; - } + Assertions.assertThrows(DateTimeException.class, () -> { + try { + ZonedDateTime.ofStrict(TEST_LOCAL_2008_06_30_11_30_59_500, OFFSET_0130, ZONE_PARIS); + } catch (DateTimeException ex) { + assertEquals(true, ex.getMessage().contains(" is not valid for ")); + throw ex; + } + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofStrict_LDT_ZI_ZO_nullLDT() { - ZonedDateTime.ofStrict((LocalDateTime) null, OFFSET_0100, ZONE_PARIS); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.ofStrict((LocalDateTime) null, OFFSET_0100, ZONE_PARIS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofStrict_LDT_ZI_ZO_nullZO() { - ZonedDateTime.ofStrict(TEST_LOCAL_2008_06_30_11_30_59_500, null, ZONE_PARIS); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.ofStrict(TEST_LOCAL_2008_06_30_11_30_59_500, null, ZONE_PARIS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofStrict_LDT_ZI_ZO_nullZI() { - ZonedDateTime.ofStrict(TEST_LOCAL_2008_06_30_11_30_59_500, OFFSET_0100, null); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.ofStrict(TEST_LOCAL_2008_06_30_11_30_59_500, OFFSET_0100, null)); } //----------------------------------------------------------------------- @@ -661,12 +680,12 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void factory_from_TemporalAccessor_ZDT() { - assertEquals(ZonedDateTime.from(TEST_DATE_TIME_PARIS), TEST_DATE_TIME_PARIS); + assertEquals(TEST_DATE_TIME_PARIS, ZonedDateTime.from(TEST_DATE_TIME_PARIS)); } @Test public void factory_from_TemporalAccessor_LDT_ZoneId() { - assertEquals(ZonedDateTime.from(new TemporalAccessor() { + assertEquals(TEST_DATE_TIME_PARIS, ZonedDateTime.from(new TemporalAccessor() { @Override public boolean isSupported(TemporalField field) { return TEST_DATE_TIME_PARIS.toLocalDateTime().isSupported(field); @@ -685,12 +704,12 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { } return TemporalAccessor.super.query(query); } - }), TEST_DATE_TIME_PARIS); + })); } @Test public void factory_from_TemporalAccessor_Instant_ZoneId() { - assertEquals(ZonedDateTime.from(new TemporalAccessor() { + assertEquals(TEST_DATE_TIME_PARIS, ZonedDateTime.from(new TemporalAccessor() { @Override public boolean isSupported(TemporalField field) { return field == INSTANT_SECONDS || field == NANO_OF_SECOND; @@ -709,36 +728,36 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { } return TemporalAccessor.super.query(query); } - }), TEST_DATE_TIME_PARIS); + })); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_from_TemporalAccessor_invalid_noDerive() { - ZonedDateTime.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> ZonedDateTime.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_from_TemporalAccessor_null() { - ZonedDateTime.from((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.from((TemporalAccessor) null)); } //----------------------------------------------------------------------- // parse() //----------------------------------------------------------------------- - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_parse(int y, int month, int d, int h, int m, int s, int n, String zoneId, String text) { ZonedDateTime t = ZonedDateTime.parse(text); - assertEquals(t.getYear(), y); - assertEquals(t.getMonth().getValue(), month); - assertEquals(t.getDayOfMonth(), d); - assertEquals(t.getHour(), h); - assertEquals(t.getMinute(), m); - assertEquals(t.getSecond(), s); - assertEquals(t.getNano(), n); - assertEquals(t.getZone().getId(), zoneId); + assertEquals(y, t.getYear()); + assertEquals(month, t.getMonth().getValue()); + assertEquals(d, t.getDayOfMonth()); + assertEquals(h, t.getHour()); + assertEquals(m, t.getMinute()); + assertEquals(s, t.getSecond()); + assertEquals(n, t.getNano()); + assertEquals(zoneId, t.getZone().getId()); } - @DataProvider(name="parseAdditional") Object[][] data_parseAdditional() { return new Object[][] { {"2012-06-30T12:30:40Z[GMT]", 2012, 6, 30, 12, 30, 40, 0, "GMT"}, @@ -758,32 +777,33 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="parseAdditional") + @ParameterizedTest + @MethodSource("data_parseAdditional") public void test_parseAdditional(String text, int y, int month, int d, int h, int m, int s, int n, String zoneId) { ZonedDateTime t = ZonedDateTime.parse(text); - assertEquals(t.getYear(), y); - assertEquals(t.getMonth().getValue(), month); - assertEquals(t.getDayOfMonth(), d); - assertEquals(t.getHour(), h); - assertEquals(t.getMinute(), m); - assertEquals(t.getSecond(), s); - assertEquals(t.getNano(), n); - assertEquals(t.getZone().getId(), zoneId); + assertEquals(y, t.getYear()); + assertEquals(month, t.getMonth().getValue()); + assertEquals(d, t.getDayOfMonth()); + assertEquals(h, t.getHour()); + assertEquals(m, t.getMinute()); + assertEquals(s, t.getSecond()); + assertEquals(n, t.getNano()); + assertEquals(zoneId, t.getZone().getId()); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_illegalValue() { - ZonedDateTime.parse("2008-06-32T11:15+01:00[Europe/Paris]"); + Assertions.assertThrows(DateTimeParseException.class, () -> ZonedDateTime.parse("2008-06-32T11:15+01:00[Europe/Paris]")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void factory_parse_invalidValue() { - ZonedDateTime.parse("2008-06-31T11:15+01:00[Europe/Paris]"); + Assertions.assertThrows(DateTimeParseException.class, () -> ZonedDateTime.parse("2008-06-31T11:15+01:00[Europe/Paris]")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_nullText() { - ZonedDateTime.parse((String) null); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.parse((String) null)); } //----------------------------------------------------------------------- @@ -793,24 +813,25 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void factory_parse_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s VV"); ZonedDateTime test = ZonedDateTime.parse("2010 12 3 11 30 0 Europe/London", f); - assertEquals(test, ZonedDateTime.of(LocalDateTime.of(2010, 12, 3, 11, 30), ZoneId.of("Europe/London"))); + assertEquals(ZonedDateTime.of(LocalDateTime.of(2010, 12, 3, 11, 30), ZoneId.of("Europe/London")), test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullText() { - DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); - ZonedDateTime.parse((String) null, f); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); + ZonedDateTime.parse((String) null, f); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_parse_formatter_nullFormatter() { - ZonedDateTime.parse("ANY", null); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.parse("ANY", null)); } //----------------------------------------------------------------------- // basics //----------------------------------------------------------------------- - @DataProvider(name="sampleTimes") Object[][] provider_sampleTimes() { return new Object[][] { {2008, 6, 30, 11, 30, 20, 500, ZONE_0100}, @@ -822,7 +843,8 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_get(int y, int o, int d, int h, int m, int s, int n, ZoneId zone) { LocalDate localDate = LocalDate.of(y, o, d); LocalTime localTime = LocalTime.of(h, m, s, n); @@ -830,24 +852,24 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZoneOffset offset = zone.getRules().getOffset(localDateTime); ZonedDateTime a = ZonedDateTime.of(localDateTime, zone); - assertEquals(a.getYear(), localDate.getYear()); - assertEquals(a.getMonth(), localDate.getMonth()); - assertEquals(a.getDayOfMonth(), localDate.getDayOfMonth()); - assertEquals(a.getDayOfYear(), localDate.getDayOfYear()); - assertEquals(a.getDayOfWeek(), localDate.getDayOfWeek()); + assertEquals(localDate.getYear(), a.getYear()); + assertEquals(localDate.getMonth(), a.getMonth()); + assertEquals(localDate.getDayOfMonth(), a.getDayOfMonth()); + assertEquals(localDate.getDayOfYear(), a.getDayOfYear()); + assertEquals(localDate.getDayOfWeek(), a.getDayOfWeek()); - assertEquals(a.getHour(), localTime.getHour()); - assertEquals(a.getMinute(), localTime.getMinute()); - assertEquals(a.getSecond(), localTime.getSecond()); - assertEquals(a.getNano(), localTime.getNano()); + assertEquals(localTime.getHour(), a.getHour()); + assertEquals(localTime.getMinute(), a.getMinute()); + assertEquals(localTime.getSecond(), a.getSecond()); + assertEquals(localTime.getNano(), a.getNano()); - assertEquals(a.toLocalDate(), localDate); - assertEquals(a.toLocalTime(), localTime); - assertEquals(a.toLocalDateTime(), localDateTime); + assertEquals(localDate, a.toLocalDate()); + assertEquals(localTime, a.toLocalTime()); + assertEquals(localDateTime, a.toLocalDateTime()); if (zone instanceof ZoneOffset) { - assertEquals(a.toString(), localDateTime.toString() + offset.toString()); + assertEquals(localDateTime.toString() + offset.toString(), a.toString()); } else { - assertEquals(a.toString(), localDateTime.toString() + offset.toString() + "[" + zone.toString() + "]"); + assertEquals(localDateTime.toString() + offset.toString() + "[" + zone.toString() + "]", a.toString()); } } @@ -856,37 +878,37 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalField() { - assertEquals(TEST_DATE_TIME.isSupported((TemporalField) null), false); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.NANO_OF_SECOND), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.NANO_OF_DAY), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.MICRO_OF_SECOND), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.MICRO_OF_DAY), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.MILLI_OF_SECOND), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.MILLI_OF_DAY), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.SECOND_OF_MINUTE), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.SECOND_OF_DAY), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.MINUTE_OF_HOUR), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.MINUTE_OF_DAY), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.HOUR_OF_AMPM), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.HOUR_OF_DAY), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.CLOCK_HOUR_OF_DAY), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.AMPM_OF_DAY), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.DAY_OF_WEEK), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.DAY_OF_MONTH), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.DAY_OF_YEAR), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.EPOCH_DAY), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.MONTH_OF_YEAR), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.PROLEPTIC_MONTH), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.YEAR), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.YEAR_OF_ERA), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.ERA), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.INSTANT_SECONDS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoField.OFFSET_SECONDS), true); + assertEquals(false, TEST_DATE_TIME.isSupported((TemporalField) null)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.NANO_OF_SECOND)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.NANO_OF_DAY)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.MICRO_OF_SECOND)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.MICRO_OF_DAY)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.MILLI_OF_SECOND)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.MILLI_OF_DAY)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.SECOND_OF_MINUTE)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.SECOND_OF_DAY)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.MINUTE_OF_HOUR)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.MINUTE_OF_DAY)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.HOUR_OF_AMPM)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.CLOCK_HOUR_OF_AMPM)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.HOUR_OF_DAY)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.CLOCK_HOUR_OF_DAY)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.AMPM_OF_DAY)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.DAY_OF_WEEK)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.DAY_OF_MONTH)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.DAY_OF_YEAR)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.EPOCH_DAY)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.MONTH_OF_YEAR)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.PROLEPTIC_MONTH)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.YEAR)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.YEAR_OF_ERA)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.ERA)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.INSTANT_SECONDS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoField.OFFSET_SECONDS)); } //----------------------------------------------------------------------- @@ -894,23 +916,23 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_isSupported_TemporalUnit() { - assertEquals(TEST_DATE_TIME.isSupported((TemporalUnit) null), false); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.NANOS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.MICROS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.MILLIS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.SECONDS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.MINUTES), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.HOURS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.HALF_DAYS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.DAYS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.WEEKS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.MONTHS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.YEARS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.DECADES), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.CENTURIES), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.MILLENNIA), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.ERAS), true); - assertEquals(TEST_DATE_TIME.isSupported(ChronoUnit.FOREVER), false); + assertEquals(false, TEST_DATE_TIME.isSupported((TemporalUnit) null)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.NANOS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.MICROS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.MILLIS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.SECONDS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.MINUTES)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.HOURS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.HALF_DAYS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.DAYS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.WEEKS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.MONTHS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.YEARS)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.DECADES)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.CENTURIES)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.MILLENNIA)); + assertEquals(true, TEST_DATE_TIME.isSupported(ChronoUnit.ERAS)); + assertEquals(false, TEST_DATE_TIME.isSupported(ChronoUnit.FOREVER)); } //----------------------------------------------------------------------- @@ -919,40 +941,40 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { @Test public void test_get_TemporalField() { ZonedDateTime test = ZonedDateTime.of(LocalDateTime.of(2008, 6, 30, 12, 30, 40, 987654321), ZONE_0100); - assertEquals(test.get(ChronoField.YEAR), 2008); - assertEquals(test.get(ChronoField.MONTH_OF_YEAR), 6); - assertEquals(test.get(ChronoField.DAY_OF_MONTH), 30); - assertEquals(test.get(ChronoField.DAY_OF_WEEK), 1); - assertEquals(test.get(ChronoField.DAY_OF_YEAR), 182); + assertEquals(2008, test.get(ChronoField.YEAR)); + assertEquals(6, test.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(30, test.get(ChronoField.DAY_OF_MONTH)); + assertEquals(1, test.get(ChronoField.DAY_OF_WEEK)); + assertEquals(182, test.get(ChronoField.DAY_OF_YEAR)); - assertEquals(test.get(ChronoField.HOUR_OF_DAY), 12); - assertEquals(test.get(ChronoField.MINUTE_OF_HOUR), 30); - assertEquals(test.get(ChronoField.SECOND_OF_MINUTE), 40); - assertEquals(test.get(ChronoField.NANO_OF_SECOND), 987654321); - assertEquals(test.get(ChronoField.HOUR_OF_AMPM), 0); - assertEquals(test.get(ChronoField.AMPM_OF_DAY), 1); + assertEquals(12, test.get(ChronoField.HOUR_OF_DAY)); + assertEquals(30, test.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(40, test.get(ChronoField.SECOND_OF_MINUTE)); + assertEquals(987654321, test.get(ChronoField.NANO_OF_SECOND)); + assertEquals(0, test.get(ChronoField.HOUR_OF_AMPM)); + assertEquals(1, test.get(ChronoField.AMPM_OF_DAY)); - assertEquals(test.get(ChronoField.OFFSET_SECONDS), 3600); + assertEquals(3600, test.get(ChronoField.OFFSET_SECONDS)); } @Test public void test_getLong_TemporalField() { ZonedDateTime test = ZonedDateTime.of(LocalDateTime.of(2008, 6, 30, 12, 30, 40, 987654321), ZONE_0100); - assertEquals(test.getLong(ChronoField.YEAR), 2008); - assertEquals(test.getLong(ChronoField.MONTH_OF_YEAR), 6); - assertEquals(test.getLong(ChronoField.DAY_OF_MONTH), 30); - assertEquals(test.getLong(ChronoField.DAY_OF_WEEK), 1); - assertEquals(test.getLong(ChronoField.DAY_OF_YEAR), 182); + assertEquals(2008, test.getLong(ChronoField.YEAR)); + assertEquals(6, test.getLong(ChronoField.MONTH_OF_YEAR)); + assertEquals(30, test.getLong(ChronoField.DAY_OF_MONTH)); + assertEquals(1, test.getLong(ChronoField.DAY_OF_WEEK)); + assertEquals(182, test.getLong(ChronoField.DAY_OF_YEAR)); - assertEquals(test.getLong(ChronoField.HOUR_OF_DAY), 12); - assertEquals(test.getLong(ChronoField.MINUTE_OF_HOUR), 30); - assertEquals(test.getLong(ChronoField.SECOND_OF_MINUTE), 40); - assertEquals(test.getLong(ChronoField.NANO_OF_SECOND), 987654321); - assertEquals(test.getLong(ChronoField.HOUR_OF_AMPM), 0); - assertEquals(test.getLong(ChronoField.AMPM_OF_DAY), 1); + assertEquals(12, test.getLong(ChronoField.HOUR_OF_DAY)); + assertEquals(30, test.getLong(ChronoField.MINUTE_OF_HOUR)); + assertEquals(40, test.getLong(ChronoField.SECOND_OF_MINUTE)); + assertEquals(987654321, test.getLong(ChronoField.NANO_OF_SECOND)); + assertEquals(0, test.getLong(ChronoField.HOUR_OF_AMPM)); + assertEquals(1, test.getLong(ChronoField.AMPM_OF_DAY)); - assertEquals(test.getLong(ChronoField.OFFSET_SECONDS), 3600); - assertEquals(test.getLong(ChronoField.INSTANT_SECONDS), test.toEpochSecond()); + assertEquals(3600, test.getLong(ChronoField.OFFSET_SECONDS)); + assertEquals(test.toEpochSecond(), test.getLong(ChronoField.INSTANT_SECONDS)); } //----------------------------------------------------------------------- @@ -960,37 +982,37 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_query_chrono() { - assertEquals(TEST_DATE_TIME.query(TemporalQueries.chronology()), IsoChronology.INSTANCE); - assertEquals(TemporalQueries.chronology().queryFrom(TEST_DATE_TIME), IsoChronology.INSTANCE); + assertEquals(IsoChronology.INSTANCE, TEST_DATE_TIME.query(TemporalQueries.chronology())); + assertEquals(IsoChronology.INSTANCE, TemporalQueries.chronology().queryFrom(TEST_DATE_TIME)); } @Test public void test_query_zoneId() { - assertEquals(TEST_DATE_TIME.query(TemporalQueries.zoneId()), TEST_DATE_TIME.getZone()); - assertEquals(TemporalQueries.zoneId().queryFrom(TEST_DATE_TIME), TEST_DATE_TIME.getZone()); + assertEquals(TEST_DATE_TIME.getZone(), TEST_DATE_TIME.query(TemporalQueries.zoneId())); + assertEquals(TEST_DATE_TIME.getZone(), TemporalQueries.zoneId().queryFrom(TEST_DATE_TIME)); } @Test public void test_query_precision() { - assertEquals(TEST_DATE_TIME.query(TemporalQueries.precision()), NANOS); - assertEquals(TemporalQueries.precision().queryFrom(TEST_DATE_TIME), NANOS); + assertEquals(NANOS, TEST_DATE_TIME.query(TemporalQueries.precision())); + assertEquals(NANOS, TemporalQueries.precision().queryFrom(TEST_DATE_TIME)); } @Test public void test_query_offset() { - assertEquals(TEST_DATE_TIME.query(TemporalQueries.offset()), TEST_DATE_TIME.getOffset()); - assertEquals(TemporalQueries.offset().queryFrom(TEST_DATE_TIME), TEST_DATE_TIME.getOffset()); + assertEquals(TEST_DATE_TIME.getOffset(), TEST_DATE_TIME.query(TemporalQueries.offset())); + assertEquals(TEST_DATE_TIME.getOffset(), TemporalQueries.offset().queryFrom(TEST_DATE_TIME)); } @Test public void test_query_zone() { - assertEquals(TEST_DATE_TIME.query(TemporalQueries.zone()), TEST_DATE_TIME.getZone()); - assertEquals(TemporalQueries.zone().queryFrom(TEST_DATE_TIME), TEST_DATE_TIME.getZone()); + assertEquals(TEST_DATE_TIME.getZone(), TEST_DATE_TIME.query(TemporalQueries.zone())); + assertEquals(TEST_DATE_TIME.getZone(), TemporalQueries.zone().queryFrom(TEST_DATE_TIME)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_query_null() { - TEST_DATE_TIME.query(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_DATE_TIME.query(null)); } //----------------------------------------------------------------------- @@ -1000,22 +1022,22 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withEarlierOffsetAtOverlap_notAtOverlap() { ZonedDateTime base = ZonedDateTime.ofStrict(TEST_LOCAL_2008_06_30_11_30_59_500, OFFSET_0200, ZONE_PARIS); ZonedDateTime test = base.withEarlierOffsetAtOverlap(); - assertEquals(test, base); // not changed + assertEquals(base, test); // not changed } @Test public void test_withEarlierOffsetAtOverlap_atOverlap() { ZonedDateTime base = ZonedDateTime.ofStrict(TEST_PARIS_OVERLAP_2008_10_26_02_30, OFFSET_0100, ZONE_PARIS); ZonedDateTime test = base.withEarlierOffsetAtOverlap(); - assertEquals(test.getOffset(), OFFSET_0200); // offset changed to earlier - assertEquals(test.toLocalDateTime(), base.toLocalDateTime()); // date-time not changed + assertEquals(OFFSET_0200, test.getOffset()); // offset changed to earlier + assertEquals(base.toLocalDateTime(), test.toLocalDateTime()); // date-time not changed } @Test public void test_withEarlierOffsetAtOverlap_atOverlap_noChange() { ZonedDateTime base = ZonedDateTime.ofStrict(TEST_PARIS_OVERLAP_2008_10_26_02_30, OFFSET_0200, ZONE_PARIS); ZonedDateTime test = base.withEarlierOffsetAtOverlap(); - assertEquals(test, base); // not changed + assertEquals(base, test); // not changed } //----------------------------------------------------------------------- @@ -1025,22 +1047,22 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withLaterOffsetAtOverlap_notAtOverlap() { ZonedDateTime base = ZonedDateTime.ofStrict(TEST_LOCAL_2008_06_30_11_30_59_500, OFFSET_0200, ZONE_PARIS); ZonedDateTime test = base.withLaterOffsetAtOverlap(); - assertEquals(test, base); // not changed + assertEquals(base, test); // not changed } @Test public void test_withLaterOffsetAtOverlap_atOverlap() { ZonedDateTime base = ZonedDateTime.ofStrict(TEST_PARIS_OVERLAP_2008_10_26_02_30, OFFSET_0200, ZONE_PARIS); ZonedDateTime test = base.withLaterOffsetAtOverlap(); - assertEquals(test.getOffset(), OFFSET_0100); // offset changed to later - assertEquals(test.toLocalDateTime(), base.toLocalDateTime()); // date-time not changed + assertEquals(OFFSET_0100, test.getOffset()); // offset changed to later + assertEquals(base.toLocalDateTime(), test.toLocalDateTime()); // date-time not changed } @Test public void test_withLaterOffsetAtOverlap_atOverlap_noChange() { ZonedDateTime base = ZonedDateTime.ofStrict(TEST_PARIS_OVERLAP_2008_10_26_02_30, OFFSET_0100, ZONE_PARIS); ZonedDateTime test = base.withLaterOffsetAtOverlap(); - assertEquals(test, base); // not changed + assertEquals(base, test); // not changed } //----------------------------------------------------------------------- @@ -1051,7 +1073,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.withZoneSameLocal(ZONE_0200); - assertEquals(test.toLocalDateTime(), base.toLocalDateTime()); + assertEquals(base.toLocalDateTime(), test.toLocalDateTime()); } @Test @@ -1059,7 +1081,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.withZoneSameLocal(ZONE_0100); - assertEquals(test, base); + assertEquals(base, test); } @Test @@ -1067,8 +1089,8 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 11, 2, 1, 30, 59, 0); // overlap ZonedDateTime base = ZonedDateTime.of(ldt, ZoneId.of("UTC-04:00") ); ZonedDateTime test = base.withZoneSameLocal(ZoneId.of("America/New_York")); - assertEquals(base.getOffset(), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(), ZoneOffset.ofHours(-4)); + assertEquals(ZoneOffset.ofHours(-4), base.getOffset()); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset()); } @Test @@ -1076,15 +1098,17 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 11, 2, 1, 30, 59, 0); // overlap ZonedDateTime base = ZonedDateTime.of(ldt, ZoneId.of("UTC-05:00") ); ZonedDateTime test = base.withZoneSameLocal(ZoneId.of("America/New_York")); - assertEquals(base.getOffset(), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(), ZoneOffset.ofHours(-5)); + assertEquals(ZoneOffset.ofHours(-5), base.getOffset()); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_withZoneSameLocal_null() { - LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); - ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); - base.withZoneSameLocal(null); + Assertions.assertThrows(NullPointerException.class, () -> { + LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); + ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); + base.withZoneSameLocal(null); + }); } //----------------------------------------------------------------------- @@ -1095,20 +1119,22 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withZoneSameInstant(ZONE_0200); ZonedDateTime expected = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.plusHours(1), ZONE_0200); - assertEquals(test, expected); + assertEquals(expected, test); } @Test public void test_withZoneSameInstant_noChange() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withZoneSameInstant(ZONE_0100); - assertEquals(test, base); + assertEquals(base, test); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_withZoneSameInstant_null() { - ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); - base.withZoneSameInstant(null); + Assertions.assertThrows(NullPointerException.class, () -> { + ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); + base.withZoneSameInstant(null); + }); } //----------------------------------------------------------------------- @@ -1119,7 +1145,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_PARIS); ZonedDateTime test = base.withFixedOffsetZone(); ZonedDateTime expected = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0200); - assertEquals(test, expected); + assertEquals(expected, test); } //----------------------------------------------------------------------- @@ -1158,7 +1184,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.with(Year.of(2007)); - assertEquals(test, ZonedDateTime.of(ldt.withYear(2007), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.withYear(2007), ZONE_0100), test); } @Test @@ -1187,9 +1213,9 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZoneId newYork = ZoneId.of("America/New_York"); LocalDateTime ldt = LocalDateTime.of(2008, 11, 1, 1, 30); ZonedDateTime base = ZonedDateTime.of(ldt, newYork); - assertEquals(base.getOffset(), ZoneOffset.ofHours(-4)); + assertEquals(ZoneOffset.ofHours(-4), base.getOffset()); ZonedDateTime test = base.with(LocalDate.of(2008, 11, 2)); - assertEquals(test.getOffset(), ZoneOffset.ofHours(-4)); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset()); } @Test @@ -1197,9 +1223,9 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZoneId newYork = ZoneId.of("America/New_York"); LocalDateTime ldt = LocalDateTime.of(2008, 11, 3, 1, 30); ZonedDateTime base = ZonedDateTime.of(ldt, newYork); - assertEquals(base.getOffset(), ZoneOffset.ofHours(-5)); + assertEquals(ZoneOffset.ofHours(-5), base.getOffset()); ZonedDateTime test = base.with(LocalDate.of(2008, 11, 2)); - assertEquals(test.getOffset(), ZoneOffset.ofHours(-5)); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset()); } @Test @@ -1208,7 +1234,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { OffsetDateTime odt = TEST_LOCAL_2008_06_30_11_30_59_500.atOffset(OFFSET_0200); ZonedDateTime zdt = TEST_PARIS_OVERLAP_2008_10_26_02_30.atZone(ZONE_PARIS); ZonedDateTime test = zdt.with(odt); - assertEquals(test.toOffsetDateTime(), odt); + assertEquals(odt, test.toOffsetDateTime()); } @Test @@ -1217,8 +1243,8 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { OffsetDateTime odt = TEST_LOCAL_2008_06_30_11_30_59_500.atOffset(OFFSET_0130); ZonedDateTime zdt = TEST_PARIS_OVERLAP_2008_10_26_02_30.atZone(ZONE_PARIS); ZonedDateTime test = zdt.with(odt); - assertEquals(test.toLocalDateTime(), TEST_LOCAL_2008_06_30_11_30_59_500); - assertEquals(test.getOffset(), zdt.getOffset()); + assertEquals(TEST_LOCAL_2008_06_30_11_30_59_500, test.toLocalDateTime()); + assertEquals(zdt.getOffset(), test.getOffset()); } @Test @@ -1227,7 +1253,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { OffsetDateTime odt = TEST_PARIS_OVERLAP_2008_10_26_02_30.atOffset(OFFSET_0100); ZonedDateTime zdt = TEST_LOCAL_2008_06_30_11_30_59_500.atZone(ZONE_PARIS); ZonedDateTime test = zdt.with(odt); - assertEquals(test.toOffsetDateTime(), odt); + assertEquals(odt, test.toOffsetDateTime()); } @Test @@ -1236,7 +1262,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { OffsetDateTime odt = TEST_PARIS_OVERLAP_2008_10_26_02_30.atOffset(OFFSET_0200); ZonedDateTime zdt = TEST_LOCAL_2008_06_30_11_30_59_500.atZone(ZONE_PARIS); ZonedDateTime test = zdt.with(odt); - assertEquals(test.toOffsetDateTime(), odt); + assertEquals(odt, test.toOffsetDateTime()); } @Test @@ -1245,8 +1271,8 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { OffsetTime ot = OffsetTime.of(15, 50, 30, 40, OFFSET_0100); ZonedDateTime zdt = TEST_PARIS_OVERLAP_2008_10_26_02_30.atZone(ZONE_PARIS); ZonedDateTime test = zdt.with(ot); - assertEquals(test.toLocalDateTime(), dateTime(2008, 10, 26, 15, 50, 30, 40)); - assertEquals(test.getOffset(), OFFSET_0100); + assertEquals(dateTime(2008, 10, 26, 15, 50, 30, 40), test.toLocalDateTime()); + assertEquals(OFFSET_0100, test.getOffset()); } @Test @@ -1255,8 +1281,8 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { OffsetTime ot = OffsetTime.of(0, 50, 30, 40, OFFSET_0130); ZonedDateTime zdt = dateTime(2008, 10, 26, 2, 30, 0, 0, OFFSET_0200, ZONE_PARIS); // earlier part of overlap ZonedDateTime test = zdt.with(ot); - assertEquals(test.toLocalDateTime(), dateTime(2008, 10, 26, 0, 50, 30, 40)); - assertEquals(test.getOffset(), OFFSET_0200); // offset not adjusted + assertEquals(dateTime(2008, 10, 26, 0, 50, 30, 40), test.toLocalDateTime()); + assertEquals(OFFSET_0200, test.getOffset()); // offset not adjusted } @Test @@ -1265,8 +1291,8 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { OffsetTime ot = OffsetTime.of(15, 50, 30, 40, OFFSET_0130); ZonedDateTime zdt = dateTime(2008, 10, 26, 2, 30, 0, 0, OFFSET_0200, ZONE_PARIS); // earlier part of overlap ZonedDateTime test = zdt.with(ot); - assertEquals(test.toLocalDateTime(), dateTime(2008, 10, 26, 15, 50, 30, 40)); - assertEquals(test.getOffset(), OFFSET_0100); // offset adjusted because of time change + assertEquals(dateTime(2008, 10, 26, 15, 50, 30, 40), test.toLocalDateTime()); + assertEquals(OFFSET_0100, test.getOffset()); // offset adjusted because of time change } @Test @@ -1275,8 +1301,8 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { OffsetTime ot = OffsetTime.of(2, 30, 30, 40, OFFSET_0100); // valid offset in overlap ZonedDateTime zdt = dateTime(2008, 10, 26, 0, 0, 0, 0, OFFSET_0200, ZONE_PARIS); // just before overlap ZonedDateTime test = zdt.with(ot); - assertEquals(test.toLocalDateTime(), dateTime(2008, 10, 26, 2, 30, 30, 40)); - assertEquals(test.getOffset(), OFFSET_0100); + assertEquals(dateTime(2008, 10, 26, 2, 30, 30, 40), test.toLocalDateTime()); + assertEquals(OFFSET_0100, test.getOffset()); } @Test @@ -1285,20 +1311,21 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { OffsetTime ot = OffsetTime.of(2, 30, 30, 40, OFFSET_0200); // valid offset in overlap ZonedDateTime zdt = dateTime(2008, 10, 26, 0, 0, 0, 0, OFFSET_0200, ZONE_PARIS); // just before overlap ZonedDateTime test = zdt.with(ot); - assertEquals(test.toLocalDateTime(), dateTime(2008, 10, 26, 2, 30, 30, 40)); - assertEquals(test.getOffset(), OFFSET_0200); + assertEquals(dateTime(2008, 10, 26, 2, 30, 30, 40), test.toLocalDateTime()); + assertEquals(OFFSET_0200, test.getOffset()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_with_adjuster_null() { - ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); - base.with((TemporalAdjuster) null); + Assertions.assertThrows(NullPointerException.class, () -> { + ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); + base.with((TemporalAdjuster) null); + }); } //----------------------------------------------------------------------- // with(long,TemporalUnit) //----------------------------------------------------------------------- - @DataProvider(name = "withFieldLong") Object[][] data_withFieldLong() { return new Object[][] { // set simple fields @@ -1341,23 +1368,26 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { }; }; - @Test(dataProvider = "withFieldLong") + @ParameterizedTest + @MethodSource("data_withFieldLong") public void test_with_fieldLong(ZonedDateTime base, TemporalField setField, int setValue, ZonedDateTime expected) { - assertEquals(base.with(setField, setValue), expected); + assertEquals(expected, base.with(setField, setValue)); } - @Test(dataProvider = "withFieldLong") + @ParameterizedTest + @MethodSource("data_withFieldLong") public void test_with_adjuster_ensureZoneOffsetConsistent(ZonedDateTime base, TemporalField setField, int setValue, ZonedDateTime expected) { if (setField == OFFSET_SECONDS) { - assertEquals(base.with(ZoneOffset.ofTotalSeconds(setValue)), expected); + assertEquals(expected, base.with(ZoneOffset.ofTotalSeconds(setValue))); } } - @Test(dataProvider = "withFieldLong") + @ParameterizedTest + @MethodSource("data_withFieldLong") public void test_with_adjuster_ensureOffsetDateTimeConsistent(ZonedDateTime base, TemporalField setField, int setValue, ZonedDateTime expected) { if (setField == OFFSET_SECONDS) { OffsetDateTime odt = base.toOffsetDateTime().with(setField, setValue); - assertEquals(base.with(odt), expected); + assertEquals(expected, base.with(odt)); } } @@ -1368,14 +1398,14 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withYear_normal() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withYear(2007); - assertEquals(test, ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withYear(2007), ZONE_0100)); + assertEquals(ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withYear(2007), ZONE_0100), test); } @Test public void test_withYear_noChange() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withYear(2008); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1385,13 +1415,15 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withMonth_Month_normal() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.with(JANUARY); - assertEquals(test, ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withMonth(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withMonth(1), ZONE_0100), test); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_withMonth_Month_null() { - ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); - base.with((Month) null); + Assertions.assertThrows(NullPointerException.class, () -> { + ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); + base.with((Month) null); + }); } //----------------------------------------------------------------------- @@ -1401,24 +1433,24 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withMonth_normal() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withMonth(1); - assertEquals(test, ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withMonth(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withMonth(1), ZONE_0100), test); } @Test public void test_withMonth_noChange() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withMonth(6); - assertEquals(test, base); + assertEquals(base, test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMonth_tooBig() { - TEST_DATE_TIME.withMonth(13); + Assertions.assertThrows(DateTimeException.class, () -> TEST_DATE_TIME.withMonth(13)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withMonth_tooSmall() { - TEST_DATE_TIME.withMonth(0); + Assertions.assertThrows(DateTimeException.class, () -> TEST_DATE_TIME.withMonth(0)); } //----------------------------------------------------------------------- @@ -1428,29 +1460,29 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withDayOfMonth_normal() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withDayOfMonth(15); - assertEquals(test, ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withDayOfMonth(15), ZONE_0100)); + assertEquals(ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withDayOfMonth(15), ZONE_0100), test); } @Test public void test_withDayOfMonth_noChange() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withDayOfMonth(30); - assertEquals(test, base); + assertEquals(base, test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfMonth_tooBig() { - LocalDateTime.of(2007, 7, 2, 11, 30).atZone(ZONE_PARIS).withDayOfMonth(32); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 7, 2, 11, 30).atZone(ZONE_PARIS).withDayOfMonth(32)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfMonth_tooSmall() { - TEST_DATE_TIME.withDayOfMonth(0); + Assertions.assertThrows(DateTimeException.class, () -> TEST_DATE_TIME.withDayOfMonth(0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfMonth_invalid31() { - LocalDateTime.of(2007, 6, 2, 11, 30).atZone(ZONE_PARIS).withDayOfMonth(31); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 6, 2, 11, 30).atZone(ZONE_PARIS).withDayOfMonth(31)); } //----------------------------------------------------------------------- @@ -1460,7 +1492,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withDayOfYear_normal() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withDayOfYear(33); - assertEquals(test, ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withDayOfYear(33), ZONE_0100)); + assertEquals(ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withDayOfYear(33), ZONE_0100), test); } @Test @@ -1468,22 +1500,22 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 2, 5, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.withDayOfYear(36); - assertEquals(test, base); + assertEquals(base, test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfYear_tooBig() { - TEST_DATE_TIME.withDayOfYear(367); + Assertions.assertThrows(DateTimeException.class, () -> TEST_DATE_TIME.withDayOfYear(367)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfYear_tooSmall() { - TEST_DATE_TIME.withDayOfYear(0); + Assertions.assertThrows(DateTimeException.class, () -> TEST_DATE_TIME.withDayOfYear(0)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_withDayOfYear_invalid366() { - LocalDateTime.of(2007, 2, 2, 11, 30).atZone(ZONE_PARIS).withDayOfYear(366); + Assertions.assertThrows(DateTimeException.class, () -> LocalDateTime.of(2007, 2, 2, 11, 30).atZone(ZONE_PARIS).withDayOfYear(366)); } //----------------------------------------------------------------------- @@ -1493,14 +1525,14 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withHour_normal() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withHour(15); - assertEquals(test, ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withHour(15), ZONE_0100)); + assertEquals(ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withHour(15), ZONE_0100), test); } @Test public void test_withHour_noChange() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withHour(11); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1510,14 +1542,14 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withMinute_normal() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withMinute(15); - assertEquals(test, ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withMinute(15), ZONE_0100)); + assertEquals(ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withMinute(15), ZONE_0100), test); } @Test public void test_withMinute_noChange() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withMinute(30); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1527,14 +1559,14 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withSecond_normal() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withSecond(12); - assertEquals(test, ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withSecond(12), ZONE_0100)); + assertEquals(ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withSecond(12), ZONE_0100), test); } @Test public void test_withSecond_noChange() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withSecond(59); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1544,14 +1576,14 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_withNanoOfSecond_normal() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withNano(15); - assertEquals(test, ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withNano(15), ZONE_0100)); + assertEquals(ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500.withNano(15), ZONE_0100), test); } @Test public void test_withNanoOfSecond_noChange() { ZonedDateTime base = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); ZonedDateTime test = base.withNano(500); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1559,20 +1591,19 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_truncatedTo_normal() { - assertEquals(TEST_DATE_TIME.truncatedTo(NANOS), TEST_DATE_TIME); - assertEquals(TEST_DATE_TIME.truncatedTo(SECONDS), TEST_DATE_TIME.withNano(0)); - assertEquals(TEST_DATE_TIME.truncatedTo(DAYS), TEST_DATE_TIME.with(LocalTime.MIDNIGHT)); + assertEquals(TEST_DATE_TIME, TEST_DATE_TIME.truncatedTo(NANOS)); + assertEquals(TEST_DATE_TIME.withNano(0), TEST_DATE_TIME.truncatedTo(SECONDS)); + assertEquals(TEST_DATE_TIME.with(LocalTime.MIDNIGHT), TEST_DATE_TIME.truncatedTo(DAYS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_truncatedTo_null() { - TEST_DATE_TIME.truncatedTo(null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_DATE_TIME.truncatedTo(null)); } //----------------------------------------------------------------------- // plus/minus //----------------------------------------------------------------------- - @DataProvider(name="plusDays") Object[][] data_plusDays() { return new Object[][] { // normal @@ -1594,7 +1625,6 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { }; } - @DataProvider(name="plusTime") Object[][] data_plusTime() { return new Object[][] { // normal @@ -1616,19 +1646,22 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- // plus(TemporalAmount) //----------------------------------------------------------------------- - @Test(dataProvider="plusDays") + @ParameterizedTest + @MethodSource("data_plusDays") public void test_plus_TemporalAmount_Period_days(ZonedDateTime base, int amount, ZonedDateTime expected) { - assertEquals(base.plus(Period.ofDays(amount)), expected); + assertEquals(expected, base.plus(Period.ofDays(amount))); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_plus_TemporalAmount_Period_hours(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plus(MockSimplePeriod.of(amount, HOURS)), expected); + assertEquals(expected, base.plus(MockSimplePeriod.of(amount, HOURS))); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_plus_TemporalAmount_Duration_hours(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plus(Duration.ofHours(amount)), expected); + assertEquals(expected, base.plus(Duration.ofHours(amount))); } @Test @@ -1636,7 +1669,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.MONTHS); ZonedDateTime t = ZonedDateTime.of(LocalDateTime.of(2008, 6, 1, 12, 30, 59, 500), ZONE_0100); ZonedDateTime expected = ZonedDateTime.of(LocalDateTime.of(2009, 1, 1, 12, 30, 59, 500), ZONE_0100); - assertEquals(t.plus(period), expected); + assertEquals(expected, t.plus(period)); } @Test @@ -1644,57 +1677,62 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { Duration duration = Duration.ofSeconds(4L * 60 * 60 + 5L * 60 + 6L); ZonedDateTime t = ZonedDateTime.of(LocalDateTime.of(2008, 6, 1, 12, 30, 59, 500), ZONE_0100); ZonedDateTime expected = ZonedDateTime.of(LocalDateTime.of(2008, 6, 1, 16, 36, 5, 500), ZONE_0100); - assertEquals(t.plus(duration), expected); + assertEquals(expected, t.plus(duration)); } @Test public void test_plus_TemporalAmount_Period_zero() { ZonedDateTime t = TEST_DATE_TIME.plus(MockSimplePeriod.ZERO_DAYS); - assertEquals(t, TEST_DATE_TIME); + assertEquals(TEST_DATE_TIME, t); } @Test public void test_plus_TemporalAmount_Duration_zero() { ZonedDateTime t = TEST_DATE_TIME.plus(Duration.ZERO); - assertEquals(t, TEST_DATE_TIME); + assertEquals(TEST_DATE_TIME, t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_TemporalAmount_null() { - TEST_DATE_TIME.plus((TemporalAmount) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_DATE_TIME.plus((TemporalAmount) null)); } //----------------------------------------------------------------------- // plus(long,TemporalUnit) //----------------------------------------------------------------------- - @Test(dataProvider="plusDays") + @ParameterizedTest + @MethodSource("data_plusDays") public void test_plus_longUnit_days(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plus(amount, DAYS), expected); + assertEquals(expected, base.plus(amount, DAYS)); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_plus_longUnit_hours(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plus(amount, HOURS), expected); + assertEquals(expected, base.plus(amount, HOURS)); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_plus_longUnit_minutes(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plus(amount * 60, MINUTES), expected); + assertEquals(expected, base.plus(amount * 60, MINUTES)); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_plus_longUnit_seconds(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plus(amount * 3600, SECONDS), expected); + assertEquals(expected, base.plus(amount * 3600, SECONDS)); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_plus_longUnit_nanos(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plus(amount * 3600_000_000_000L, NANOS), expected); + assertEquals(expected, base.plus(amount * 3600_000_000_000L, NANOS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_plus_longUnit_null() { - TEST_DATE_TIME_PARIS.plus(0, null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_DATE_TIME_PARIS.plus(0, null)); } //----------------------------------------------------------------------- @@ -1705,7 +1743,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.plusYears(1); - assertEquals(test, ZonedDateTime.of(ldt.plusYears(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.plusYears(1), ZONE_0100), test); } @Test @@ -1713,7 +1751,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.plusYears(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1724,7 +1762,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.plusMonths(1); - assertEquals(test, ZonedDateTime.of(ldt.plusMonths(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.plusMonths(1), ZONE_0100), test); } @Test @@ -1732,7 +1770,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.plusMonths(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1743,7 +1781,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.plusWeeks(1); - assertEquals(test, ZonedDateTime.of(ldt.plusWeeks(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.plusWeeks(1), ZONE_0100), test); } @Test @@ -1751,31 +1789,34 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.plusWeeks(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- // plusDays() //----------------------------------------------------------------------- - @Test(dataProvider="plusDays") + @ParameterizedTest + @MethodSource("data_plusDays") public void test_plusDays(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plusDays(amount), expected); + assertEquals(expected, base.plusDays(amount)); } //----------------------------------------------------------------------- // plusHours() //----------------------------------------------------------------------- - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_plusHours(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plusHours(amount), expected); + assertEquals(expected, base.plusHours(amount)); } //----------------------------------------------------------------------- // plusMinutes() //----------------------------------------------------------------------- - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_plusMinutes(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plusMinutes(amount * 60), expected); + assertEquals(expected, base.plusMinutes(amount * 60)); } @Test @@ -1783,15 +1824,16 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.plusMinutes(30); - assertEquals(test, ZonedDateTime.of(ldt.plusMinutes(30), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.plusMinutes(30), ZONE_0100), test); } //----------------------------------------------------------------------- // plusSeconds() //----------------------------------------------------------------------- - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_plusSeconds(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plusSeconds(amount * 3600), expected); + assertEquals(expected, base.plusSeconds(amount * 3600)); } @Test @@ -1799,15 +1841,16 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.plusSeconds(1); - assertEquals(test, ZonedDateTime.of(ldt.plusSeconds(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.plusSeconds(1), ZONE_0100), test); } //----------------------------------------------------------------------- // plusNanos() //----------------------------------------------------------------------- - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_plusNanos(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.plusNanos(amount * 3600_000_000_000L), expected); + assertEquals(expected, base.plusNanos(amount * 3600_000_000_000L)); } @Test @@ -1815,25 +1858,28 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.plusNanos(1); - assertEquals(test, ZonedDateTime.of(ldt.plusNanos(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.plusNanos(1), ZONE_0100), test); } //----------------------------------------------------------------------- // minus(TemporalAmount) //----------------------------------------------------------------------- - @Test(dataProvider="plusDays") + @ParameterizedTest + @MethodSource("data_plusDays") public void test_minus_TemporalAmount_Period_days(ZonedDateTime base, int amount, ZonedDateTime expected) { - assertEquals(base.minus(Period.ofDays(-amount)), expected); + assertEquals(expected, base.minus(Period.ofDays(-amount))); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_minus_TemporalAmount_Period_hours(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.minus(MockSimplePeriod.of(-amount, HOURS)), expected); + assertEquals(expected, base.minus(MockSimplePeriod.of(-amount, HOURS))); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_minus_TemporalAmount_Duration_hours(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.minus(Duration.ofHours(-amount)), expected); + assertEquals(expected, base.minus(Duration.ofHours(-amount))); } @Test @@ -1841,7 +1887,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { MockSimplePeriod period = MockSimplePeriod.of(7, ChronoUnit.MONTHS); ZonedDateTime t = ZonedDateTime.of(LocalDateTime.of(2008, 6, 1, 12, 30, 59, 500), ZONE_0100); ZonedDateTime expected = ZonedDateTime.of(LocalDateTime.of(2007, 11, 1, 12, 30, 59, 500), ZONE_0100); - assertEquals(t.minus(period), expected); + assertEquals(expected, t.minus(period)); } @Test @@ -1849,24 +1895,24 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { Duration duration = Duration.ofSeconds(4L * 60 * 60 + 5L * 60 + 6L); ZonedDateTime t = ZonedDateTime.of(LocalDateTime.of(2008, 6, 1, 12, 30, 59, 500), ZONE_0100); ZonedDateTime expected = ZonedDateTime.of(LocalDateTime.of(2008, 6, 1, 8, 25, 53, 500), ZONE_0100); - assertEquals(t.minus(duration), expected); + assertEquals(expected, t.minus(duration)); } @Test public void test_minus_TemporalAmount_Period_zero() { ZonedDateTime t = TEST_DATE_TIME.minus(MockSimplePeriod.ZERO_DAYS); - assertEquals(t, TEST_DATE_TIME); + assertEquals(TEST_DATE_TIME, t); } @Test public void test_minus_TemporalAmount_Duration_zero() { ZonedDateTime t = TEST_DATE_TIME.minus(Duration.ZERO); - assertEquals(t, TEST_DATE_TIME); + assertEquals(TEST_DATE_TIME, t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_minus_TemporalAmount_null() { - TEST_DATE_TIME.minus((TemporalAmount) null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_DATE_TIME.minus((TemporalAmount) null)); } //----------------------------------------------------------------------- @@ -1877,7 +1923,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.minusYears(1); - assertEquals(test, ZonedDateTime.of(ldt.minusYears(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.minusYears(1), ZONE_0100), test); } @Test @@ -1885,7 +1931,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.minusYears(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1896,7 +1942,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.minusMonths(1); - assertEquals(test, ZonedDateTime.of(ldt.minusMonths(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.minusMonths(1), ZONE_0100), test); } @Test @@ -1904,7 +1950,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.minusMonths(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- @@ -1915,7 +1961,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.minusWeeks(1); - assertEquals(test, ZonedDateTime.of(ldt.minusWeeks(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.minusWeeks(1), ZONE_0100), test); } @Test @@ -1923,31 +1969,34 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.minusWeeks(0); - assertEquals(test, base); + assertEquals(base, test); } //----------------------------------------------------------------------- // minusDays() //----------------------------------------------------------------------- - @Test(dataProvider="plusDays") + @ParameterizedTest + @MethodSource("data_plusDays") public void test_minusDays(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.minusDays(-amount), expected); + assertEquals(expected, base.minusDays(-amount)); } //----------------------------------------------------------------------- // minusHours() //----------------------------------------------------------------------- - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_minusHours(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.minusHours(-amount), expected); + assertEquals(expected, base.minusHours(-amount)); } //----------------------------------------------------------------------- // minusMinutes() //----------------------------------------------------------------------- - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_minusMinutes(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.minusMinutes(-amount * 60), expected); + assertEquals(expected, base.minusMinutes(-amount * 60)); } @Test @@ -1955,15 +2004,16 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.minusMinutes(30); - assertEquals(test, ZonedDateTime.of(ldt.minusMinutes(30), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.minusMinutes(30), ZONE_0100), test); } //----------------------------------------------------------------------- // minusSeconds() //----------------------------------------------------------------------- - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_minusSeconds(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.minusSeconds(-amount * 3600), expected); + assertEquals(expected, base.minusSeconds(-amount * 3600)); } @Test @@ -1971,15 +2021,16 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.minusSeconds(1); - assertEquals(test, ZonedDateTime.of(ldt.minusSeconds(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.minusSeconds(1), ZONE_0100), test); } //----------------------------------------------------------------------- // minusNanos() //----------------------------------------------------------------------- - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_minusNanos(ZonedDateTime base, long amount, ZonedDateTime expected) { - assertEquals(base.minusNanos(-amount * 3600_000_000_000L), expected); + assertEquals(expected, base.minusNanos(-amount * 3600_000_000_000L)); } @Test @@ -1987,7 +2038,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.minusNanos(1); - assertEquals(test, ZonedDateTime.of(ldt.minusNanos(1), ZONE_0100)); + assertEquals(ZonedDateTime.of(ldt.minusNanos(1), ZONE_0100), test); } //----------------------------------------------------------------------- @@ -1996,32 +2047,37 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { // TODO: more tests for period between two different zones // compare results to OffsetDateTime.until, especially wrt dates - @Test(dataProvider="plusDays") + @ParameterizedTest + @MethodSource("data_plusDays") public void test_until_days(ZonedDateTime base, long expected, ZonedDateTime end) { if (base.toLocalTime().equals(end.toLocalTime()) == false) { return; // avoid DST gap input values } - assertEquals(base.until(end, DAYS), expected); + assertEquals(expected, base.until(end, DAYS)); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_until_hours(ZonedDateTime base, long expected, ZonedDateTime end) { - assertEquals(base.until(end, HOURS), expected); + assertEquals(expected, base.until(end, HOURS)); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_until_minutes(ZonedDateTime base, long expected, ZonedDateTime end) { - assertEquals(base.until(end, MINUTES), expected * 60); + assertEquals(expected * 60, base.until(end, MINUTES)); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_until_seconds(ZonedDateTime base, long expected, ZonedDateTime end) { - assertEquals(base.until(end, SECONDS), expected * 3600); + assertEquals(expected * 3600, base.until(end, SECONDS)); } - @Test(dataProvider="plusTime") + @ParameterizedTest + @MethodSource("data_plusTime") public void test_until_nanos(ZonedDateTime base, long expected, ZonedDateTime end) { - assertEquals(base.until(end, NANOS), expected * 3600_000_000_000L); + assertEquals(expected * 3600_000_000_000L, base.until(end, NANOS)); } @Test @@ -2031,13 +2087,13 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZonedDateTime oneAm1 = LocalDateTime.of(2012, 6, 29, 1, 0).atZone(ZONE_PARIS); ZonedDateTime midnightParis2 = LocalDate.of(2012, 6, 30).atStartOfDay(ZONE_PARIS); - assertEquals(midnightLondon.until(midnightParis1, HOURS), 23); - assertEquals(midnightLondon.until(oneAm1, HOURS), 24); - assertEquals(midnightLondon.until(midnightParis2, HOURS), 23 + 24); + assertEquals(23, midnightLondon.until(midnightParis1, HOURS)); + assertEquals(24, midnightLondon.until(oneAm1, HOURS)); + assertEquals(23 + 24, midnightLondon.until(midnightParis2, HOURS)); - assertEquals(midnightLondon.until(midnightParis1, DAYS), 0); - assertEquals(midnightLondon.until(oneAm1, DAYS), 1); - assertEquals(midnightLondon.until(midnightParis2, DAYS), 1); + assertEquals(0, midnightLondon.until(midnightParis1, DAYS)); + assertEquals(1, midnightLondon.until(oneAm1, DAYS)); + assertEquals(1, midnightLondon.until(midnightParis2, DAYS)); } @Test @@ -2045,8 +2101,8 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZonedDateTime before = TEST_PARIS_GAP_2008_03_30_02_30.withHour(0).withMinute(0).atZone(ZONE_PARIS); ZonedDateTime after = TEST_PARIS_GAP_2008_03_30_02_30.withHour(0).withMinute(0).plusDays(1).atZone(ZONE_PARIS); - assertEquals(before.until(after, HOURS), 23); - assertEquals(before.until(after, DAYS), 1); + assertEquals(23, before.until(after, HOURS)); + assertEquals(1, before.until(after, DAYS)); } @Test @@ -2054,23 +2110,23 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { ZonedDateTime before = TEST_PARIS_OVERLAP_2008_10_26_02_30.withHour(0).withMinute(0).atZone(ZONE_PARIS); ZonedDateTime after = TEST_PARIS_OVERLAP_2008_10_26_02_30.withHour(0).withMinute(0).plusDays(1).atZone(ZONE_PARIS); - assertEquals(before.until(after, HOURS), 25); - assertEquals(before.until(after, DAYS), 1); + assertEquals(25, before.until(after, HOURS)); + assertEquals(1, before.until(after, DAYS)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_until_differentType() { - TEST_DATE_TIME_PARIS.until(TEST_LOCAL_2008_06_30_11_30_59_500, DAYS); + Assertions.assertThrows(DateTimeException.class, () -> TEST_DATE_TIME_PARIS.until(TEST_LOCAL_2008_06_30_11_30_59_500, DAYS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_until_nullTemporal() { - TEST_DATE_TIME_PARIS.until(null, DAYS); + Assertions.assertThrows(NullPointerException.class, () -> TEST_DATE_TIME_PARIS.until(null, DAYS)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_until_nullUnit() { - TEST_DATE_TIME_PARIS.until(TEST_DATE_TIME_PARIS, null); + Assertions.assertThrows(NullPointerException.class, () -> TEST_DATE_TIME_PARIS.until(TEST_DATE_TIME_PARIS, null)); } //----------------------------------------------------------------------- @@ -2080,12 +2136,12 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_format_formatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s"); String t = ZonedDateTime.of(dateTime(2010, 12, 3, 11, 30), ZONE_PARIS).format(f); - assertEquals(t, "2010 12 3 11 30 0"); + assertEquals("2010 12 3 11 30 0", t); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_format_formatter_null() { - ZonedDateTime.of(dateTime(2010, 12, 3, 11, 30), ZONE_PARIS).format(null); + Assertions.assertThrows(NullPointerException.class, () -> ZonedDateTime.of(dateTime(2010, 12, 3, 11, 30), ZONE_PARIS).format(null)); } //----------------------------------------------------------------------- @@ -2093,13 +2149,12 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void test_toOffsetDateTime() { - assertEquals(TEST_DATE_TIME.toOffsetDateTime(), OffsetDateTime.of(TEST_DATE_TIME.toLocalDateTime(), TEST_DATE_TIME.getOffset())); + assertEquals(OffsetDateTime.of(TEST_DATE_TIME.toLocalDateTime(), TEST_DATE_TIME.getOffset()), TEST_DATE_TIME.toOffsetDateTime()); } //----------------------------------------------------------------------- // toInstant() //----------------------------------------------------------------------- - @DataProvider(name="toInstant") Object[][] data_toInstant() { return new Object[][] { {LocalDateTime.of(1970, 1, 1, 0, 0, 0, 0), 0L, 0}, @@ -2113,28 +2168,31 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="toInstant") + @ParameterizedTest + @MethodSource("data_toInstant") public void test_toInstant_UTC(LocalDateTime ldt, long expectedEpSec, int expectedNos) { ZonedDateTime dt = ldt.atZone(ZoneOffset.UTC); Instant test = dt.toInstant(); - assertEquals(test.getEpochSecond(), expectedEpSec); - assertEquals(test.getNano(), expectedNos); + assertEquals(expectedEpSec, test.getEpochSecond()); + assertEquals(expectedNos, test.getNano()); } - @Test(dataProvider="toInstant") + @ParameterizedTest + @MethodSource("data_toInstant") public void test_toInstant_P0100(LocalDateTime ldt, long expectedEpSec, int expectedNos) { ZonedDateTime dt = ldt.atZone(ZONE_0100); Instant test = dt.toInstant(); - assertEquals(test.getEpochSecond(), expectedEpSec - 3600); - assertEquals(test.getNano(), expectedNos); + assertEquals(expectedEpSec - 3600, test.getEpochSecond()); + assertEquals(expectedNos, test.getNano()); } - @Test(dataProvider="toInstant") + @ParameterizedTest + @MethodSource("data_toInstant") public void test_toInstant_M0100(LocalDateTime ldt, long expectedEpSec, int expectedNos) { ZonedDateTime dt = ldt.atZone(ZONE_M0100); Instant test = dt.toInstant(); - assertEquals(test.getEpochSecond(), expectedEpSec + 3600); - assertEquals(test.getNano(), expectedNos); + assertEquals(expectedEpSec + 3600, test.getEpochSecond()); + assertEquals(expectedNos, test.getNano()); } //----------------------------------------------------------------------- @@ -2145,7 +2203,7 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(1970, 1, 1, 0, 0).plusHours(1); for (int i = 0; i < 100000; i++) { ZonedDateTime a = ZonedDateTime.of(ldt, ZONE_PARIS); - assertEquals(a.toEpochSecond(), i); + assertEquals(i, a.toEpochSecond()); ldt = ldt.plusSeconds(1); } } @@ -2155,27 +2213,30 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { LocalDateTime ldt = LocalDateTime.of(1970, 1, 1, 0, 0).plusHours(1); for (int i = 0; i < 100000; i++) { ZonedDateTime a = ZonedDateTime.of(ldt, ZONE_PARIS); - assertEquals(a.toEpochSecond(), -i); + assertEquals(-i, a.toEpochSecond()); ldt = ldt.minusSeconds(1); } } - @Test(dataProvider="toInstant") + @ParameterizedTest + @MethodSource("data_toInstant") public void test_toEpochSecond_UTC(LocalDateTime ldt, long expectedEpSec, int expectedNos) { ZonedDateTime dt = ldt.atZone(ZoneOffset.UTC); - assertEquals(dt.toEpochSecond(), expectedEpSec); + assertEquals(expectedEpSec, dt.toEpochSecond()); } - @Test(dataProvider="toInstant") + @ParameterizedTest + @MethodSource("data_toInstant") public void test_toEpochSecond_P0100(LocalDateTime ldt, long expectedEpSec, int expectedNos) { ZonedDateTime dt = ldt.atZone(ZONE_0100); - assertEquals(dt.toEpochSecond(), expectedEpSec - 3600); + assertEquals(expectedEpSec - 3600, dt.toEpochSecond()); } - @Test(dataProvider="toInstant") + @ParameterizedTest + @MethodSource("data_toInstant") public void test_toEpochSecond_M0100(LocalDateTime ldt, long expectedEpSec, int expectedNos) { ZonedDateTime dt = ldt.atZone(ZONE_M0100); - assertEquals(dt.toEpochSecond(), expectedEpSec + 3600); + assertEquals(expectedEpSec + 3600, dt.toEpochSecond()); } //----------------------------------------------------------------------- @@ -2185,82 +2246,83 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { public void test_compareTo_time1() { ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 11, 30, 39, 0, ZONE_0100); ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, 11, 30, 41, 0, ZONE_0100); // a is before b due to time - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); } @Test public void test_compareTo_time2() { ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 11, 30, 40, 4, ZONE_0100); ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, 11, 30, 40, 5, ZONE_0100); // a is before b due to time - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); } @Test public void test_compareTo_offset1() { ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 11, 30, 41, 0, ZONE_0200); ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, 11, 30, 39, 0, ZONE_0100); // a is before b due to offset - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); } @Test public void test_compareTo_offset2() { ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 11, 30, 40, 5, ZoneId.of("UTC+01:01")); ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, 11, 30, 40, 4, ZONE_0100); // a is before b due to offset - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); } @Test public void test_compareTo_both() { ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 11, 50, 0, 0, ZONE_0200); ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, 11, 20, 0, 0, ZONE_0100); // a is before b on instant scale - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); } @Test public void test_compareTo_bothNanos() { ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 11, 20, 40, 5, ZONE_0200); ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, 10, 20, 40, 6, ZONE_0100); // a is before b on instant scale - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); } @Test public void test_compareTo_hourDifference() { ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 10, 0, 0, 0, ZONE_0100); ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, 11, 0, 0, 0, ZONE_0200); // a is before b despite being same time-line time - assertEquals(a.compareTo(b) < 0, true); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_compareTo_null() { - ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 23, 30, 59, 0, ZONE_0100); - a.compareTo(null); + Assertions.assertThrows(NullPointerException.class, () -> { + ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 23, 30, 59, 0, ZONE_0100); + a.compareTo(null); + }); } //----------------------------------------------------------------------- // isBefore() //----------------------------------------------------------------------- - @DataProvider(name="IsBefore") Object[][] data_isBefore() { return new Object[][] { {11, 30, ZONE_0100, 11, 31, ZONE_0100, true}, // a is before b due to time @@ -2269,26 +2331,28 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="IsBefore") + @ParameterizedTest + @MethodSource("data_isBefore") public void test_isBefore(int hour1, int minute1, ZoneId zone1, int hour2, int minute2, ZoneId zone2, boolean expected) { ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, hour1, minute1, 0, 0, zone1); ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, hour2, minute2, 0, 0, zone2); - assertEquals(a.isBefore(b), expected); - assertEquals(b.isBefore(a), false); - assertEquals(a.isBefore(a), false); - assertEquals(b.isBefore(b), false); + assertEquals(expected, a.isBefore(b)); + assertEquals(false, b.isBefore(a)); + assertEquals(false, a.isBefore(a)); + assertEquals(false, b.isBefore(b)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isBefore_null() { - ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 23, 30, 59, 0, ZONE_0100); - a.isBefore(null); + Assertions.assertThrows(NullPointerException.class, () -> { + ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 23, 30, 59, 0, ZONE_0100); + a.isBefore(null); + }); } //----------------------------------------------------------------------- // isAfter() //----------------------------------------------------------------------- - @DataProvider(name="IsAfter") Object[][] data_isAfter() { return new Object[][] { {11, 31, ZONE_0100, 11, 30, ZONE_0100, true}, // a is after b due to time @@ -2297,87 +2361,96 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="IsAfter") + @ParameterizedTest + @MethodSource("data_isAfter") public void test_isAfter(int hour1, int minute1, ZoneId zone1, int hour2, int minute2, ZoneId zone2, boolean expected) { ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, hour1, minute1, 0, 0, zone1); ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, hour2, minute2, 0, 0, zone2); - assertEquals(a.isAfter(b), expected); - assertEquals(b.isAfter(a), false); - assertEquals(a.isAfter(a), false); - assertEquals(b.isAfter(b), false); + assertEquals(expected, a.isAfter(b)); + assertEquals(false, b.isAfter(a)); + assertEquals(false, a.isAfter(a)); + assertEquals(false, b.isAfter(b)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_isAfter_null() { - ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 23, 30, 59, 0, ZONE_0100); - a.isAfter(null); + Assertions.assertThrows(NullPointerException.class, () -> { + ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 23, 30, 59, 0, ZONE_0100); + a.isAfter(null); + }); } //----------------------------------------------------------------------- // equals() / hashCode() //----------------------------------------------------------------------- - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_true(int y, int o, int d, int h, int m, int s, int n, ZoneId ignored) { ZonedDateTime a = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0100); ZonedDateTime b = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0100); - assertEquals(a.equals(b), true); - assertEquals(a.hashCode() == b.hashCode(), true); + assertEquals(true, a.equals(b)); + assertEquals(true, a.hashCode() == b.hashCode()); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_year_differs(int y, int o, int d, int h, int m, int s, int n, ZoneId ignored) { ZonedDateTime a = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0100); ZonedDateTime b = ZonedDateTime.of(dateTime(y + 1, o, d, h, m, s, n), ZONE_0100); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_hour_differs(int y, int o, int d, int h, int m, int s, int n, ZoneId ignored) { h = (h == 23 ? 22 : h); ZonedDateTime a = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0100); ZonedDateTime b = ZonedDateTime.of(dateTime(y, o, d, h + 1, m, s, n), ZONE_0100); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_minute_differs(int y, int o, int d, int h, int m, int s, int n, ZoneId ignored) { m = (m == 59 ? 58 : m); ZonedDateTime a = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0100); ZonedDateTime b = ZonedDateTime.of(dateTime(y, o, d, h, m + 1, s, n), ZONE_0100); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_second_differs(int y, int o, int d, int h, int m, int s, int n, ZoneId ignored) { s = (s == 59 ? 58 : s); ZonedDateTime a = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0100); ZonedDateTime b = ZonedDateTime.of(dateTime(y, o, d, h, m, s + 1, n), ZONE_0100); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_nano_differs(int y, int o, int d, int h, int m, int s, int n, ZoneId ignored) { n = (n == 999999999 ? 999999998 : n); ZonedDateTime a = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0100); ZonedDateTime b = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n + 1), ZONE_0100); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_equals_false_offset_differs(int y, int o, int d, int h, int m, int s, int n, ZoneId ignored) { ZonedDateTime a = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0100); ZonedDateTime b = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0200); - assertEquals(a.equals(b), false); + assertEquals(false, a.equals(b)); } @Test public void test_equals_itself_true() { - assertEquals(TEST_DATE_TIME.equals(TEST_DATE_TIME), true); + assertEquals(true, TEST_DATE_TIME.equals(TEST_DATE_TIME)); } @Test public void test_equals_string_false() { - assertEquals(TEST_DATE_TIME.equals("2007-07-15"), false); + assertEquals(false, TEST_DATE_TIME.equals("2007-07-15")); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="sampleToString") Object[][] provider_sampleToString() { return new Object[][] { {2008, 6, 30, 11, 30, 59, 0, "Z", "2008-06-30T11:30:59Z"}, @@ -2394,11 +2467,12 @@ public class TCKZonedDateTime extends AbstractDateTimeTest { }; } - @Test(dataProvider="sampleToString") + @ParameterizedTest + @MethodSource("provider_sampleToString") public void test_toString(int y, int o, int d, int h, int m, int s, int n, String zoneId, String expected) { ZonedDateTime t = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZoneId.of(zoneId)); String str = t.toString(); - assertEquals(str, expected); + assertEquals(expected, str); } //------------------------------------------------------------------------- diff --git a/test/jdk/java/time/tck/java/time/TestIsoChronology.java b/test/jdk/java/time/tck/java/time/TestIsoChronology.java index 5b1a5c67cf3..cac5a67bd09 100644 --- a/test/jdk/java/time/tck/java/time/TestIsoChronology.java +++ b/test/jdk/java/time/tck/java/time/TestIsoChronology.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -64,10 +64,11 @@ import static java.time.chrono.IsoEra.CE; import static java.time.temporal.ChronoField.ERA; import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoField.YEAR_OF_ERA; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.DateTimeException; import java.time.LocalDate; @@ -82,14 +83,16 @@ import java.time.chrono.IsoEra; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAdjusters; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestIsoChronology { //----------------------------------------------------------------------- @@ -99,10 +102,10 @@ public class TestIsoChronology { public void test_chrono_byName() { Chronology c = IsoChronology.INSTANCE; Chronology test = Chronology.of("ISO"); - Assert.assertNotNull(test, "The ISO calendar could not be found byName"); - Assert.assertEquals(test.getId(), "ISO", "ID mismatch"); - Assert.assertEquals(test.getCalendarType(), "iso8601", "Type mismatch"); - Assert.assertEquals(test, c); + assertNotNull(test, "The ISO calendar could not be found byName"); + assertEquals("ISO", test.getId(), "ID mismatch"); + assertEquals("iso8601", test.getCalendarType(), "Type mismatch"); + assertEquals(c, test); } //----------------------------------------------------------------------- @@ -118,14 +121,13 @@ public class TestIsoChronology { //----------------------------------------------------------------------- @Test public void test_eraOf() { - assertEquals(IsoChronology.INSTANCE.eraOf(0), BCE); - assertEquals(IsoChronology.INSTANCE.eraOf(1), CE); + assertEquals(BCE, IsoChronology.INSTANCE.eraOf(0)); + assertEquals(CE, IsoChronology.INSTANCE.eraOf(1)); } //----------------------------------------------------------------------- // creation, toLocalDate() //----------------------------------------------------------------------- - @DataProvider(name="samples") Object[][] data_samples() { return new Object[][] { {IsoChronology.INSTANCE.date(1, 7, 8), LocalDate.of(1, 7, 8)}, @@ -145,17 +147,18 @@ public class TestIsoChronology { }; } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_toLocalDate(LocalDate isoDate, LocalDate iso) { - assertEquals(LocalDate.from(isoDate), iso); + assertEquals(iso, LocalDate.from(isoDate)); } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_fromCalendrical(LocalDate isoDate, LocalDate iso) { - assertEquals(IsoChronology.INSTANCE.date(iso), isoDate); + assertEquals(isoDate, IsoChronology.INSTANCE.date(iso)); } - @DataProvider(name="badDates") Object[][] data_badDates() { return new Object[][] { {2012, 0, 0}, @@ -175,9 +178,10 @@ public class TestIsoChronology { }; } - @Test(dataProvider="badDates", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_badDates") public void test_badDates(int year, int month, int dom) { - IsoChronology.INSTANCE.date(year, month, dom); + Assertions.assertThrows(DateTimeException.class, () -> IsoChronology.INSTANCE.date(year, month, dom)); } @Test @@ -186,20 +190,20 @@ public class TestIsoChronology { int month = 5; int dayOfMonth = 5; LocalDate test = IsoChronology.INSTANCE.date(IsoEra.BCE, year, month, dayOfMonth); - assertEquals(test.getEra(), IsoEra.BCE); - assertEquals(test.get(ChronoField.YEAR_OF_ERA), year); - assertEquals(test.get(ChronoField.MONTH_OF_YEAR), month); - assertEquals(test.get(ChronoField.DAY_OF_MONTH), dayOfMonth); + assertEquals(IsoEra.BCE, test.getEra()); + assertEquals(year, test.get(ChronoField.YEAR_OF_ERA)); + assertEquals(month, test.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(dayOfMonth, test.get(ChronoField.DAY_OF_MONTH)); - assertEquals(test.get(YEAR), 1 + (-1 * year)); - assertEquals(test.get(ERA), 0); - assertEquals(test.get(YEAR_OF_ERA), year); + assertEquals(1 + (-1 * year), test.get(YEAR)); + assertEquals(0, test.get(ERA)); + assertEquals(year, test.get(YEAR_OF_ERA)); } @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test(expectedExceptions=ClassCastException.class) + @Test public void test_date_withEra_withWrongEra() { - IsoChronology.INSTANCE.date((Era) HijrahEra.AH, 1, 1, 1); + Assertions.assertThrows(ClassCastException.class, () -> IsoChronology.INSTANCE.date((Era) HijrahEra.AH, 1, 1, 1)); } //----------------------------------------------------------------------- @@ -209,14 +213,14 @@ public class TestIsoChronology { public void test_adjust1() { LocalDate base = IsoChronology.INSTANCE.date(1728, 10, 28); LocalDate test = base.with(TemporalAdjusters.lastDayOfMonth()); - assertEquals(test, IsoChronology.INSTANCE.date(1728, 10, 31)); + assertEquals(IsoChronology.INSTANCE.date(1728, 10, 31), test); } @Test public void test_adjust2() { LocalDate base = IsoChronology.INSTANCE.date(1728, 12, 2); LocalDate test = base.with(TemporalAdjusters.lastDayOfMonth()); - assertEquals(test, IsoChronology.INSTANCE.date(1728, 12, 31)); + assertEquals(IsoChronology.INSTANCE.date(1728, 12, 31), test); } //----------------------------------------------------------------------- @@ -226,13 +230,13 @@ public class TestIsoChronology { public void test_adjust_toLocalDate() { LocalDate isoDate = IsoChronology.INSTANCE.date(1726, 1, 4); LocalDate test = isoDate.with(LocalDate.of(2012, 7, 6)); - assertEquals(test, IsoChronology.INSTANCE.date(2012, 7, 6)); + assertEquals(IsoChronology.INSTANCE.date(2012, 7, 6), test); } @Test public void test_adjust_toMonth() { LocalDate isoDate = IsoChronology.INSTANCE.date(1726, 1, 4); - assertEquals(IsoChronology.INSTANCE.date(1726, 4, 4), isoDate.with(Month.APRIL)); + assertEquals(isoDate.with(Month.APRIL), IsoChronology.INSTANCE.date(1726, 4, 4)); } //----------------------------------------------------------------------- @@ -242,20 +246,19 @@ public class TestIsoChronology { public void test_LocalDate_adjustToISODate() { LocalDate isoDate = IsoChronology.INSTANCE.date(1728, 10, 29); LocalDate test = LocalDate.MIN.with(isoDate); - assertEquals(test, LocalDate.of(1728, 10, 29)); + assertEquals(LocalDate.of(1728, 10, 29), test); } @Test public void test_LocalDateTime_adjustToISODate() { LocalDate isoDate = IsoChronology.INSTANCE.date(1728, 10, 29); LocalDateTime test = LocalDateTime.MIN.with(isoDate); - assertEquals(test, LocalDateTime.of(1728, 10, 29, 0, 0)); + assertEquals(LocalDateTime.of(1728, 10, 29, 0, 0), test); } //----------------------------------------------------------------------- // isLeapYear() //----------------------------------------------------------------------- - @DataProvider(name="leapYears") Object[][] leapYearInformation() { return new Object[][] { {2000, true}, @@ -267,9 +270,10 @@ public class TestIsoChronology { }; } - @Test(dataProvider="leapYears") + @ParameterizedTest + @MethodSource("leapYearInformation") public void test_isLeapYear(int year, boolean isLeapYear) { - assertEquals(IsoChronology.INSTANCE.isLeapYear(year), isLeapYear); + assertEquals(isLeapYear, IsoChronology.INSTANCE.isLeapYear(year)); } //----------------------------------------------------------------------- @@ -277,13 +281,12 @@ public class TestIsoChronology { //----------------------------------------------------------------------- @Test public void test_now() { - assertEquals(LocalDate.from(IsoChronology.INSTANCE.dateNow()), LocalDate.now()); + assertEquals(LocalDate.now(), LocalDate.from(IsoChronology.INSTANCE.dateNow())); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="toString") Object[][] data_toString() { return new Object[][] { {IsoChronology.INSTANCE.date(1, 1, 1), "0001-01-01"}, @@ -294,9 +297,10 @@ public class TestIsoChronology { }; } - @Test(dataProvider="toString") + @ParameterizedTest + @MethodSource("data_toString") public void test_toString(LocalDate isoDate, String expected) { - assertEquals(isoDate.toString(), expected); + assertEquals(expected, isoDate.toString()); } //----------------------------------------------------------------------- diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKChronoLocalDate.java b/test/jdk/java/time/tck/java/time/chrono/TCKChronoLocalDate.java index eb1ccebc0c2..b4c488d2e11 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKChronoLocalDate.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKChronoLocalDate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,8 +54,8 @@ */ package tck.java.time.chrono; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -85,20 +85,21 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test assertions that must be true for all built-in chronologies. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoLocalDate { //----------------------------------------------------------------------- // regular data factory for names and descriptions of available calendars //----------------------------------------------------------------------- - @DataProvider(name = "calendars") Chronology[][] data_of_calendars() { return new Chronology[][]{ {HijrahChronology.INSTANCE}, @@ -108,7 +109,8 @@ public class TCKChronoLocalDate { {ThaiBuddhistChronology.INSTANCE}}; } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badWithAdjusterChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDate date = chrono.date(refDate); @@ -119,19 +121,20 @@ public class TCKChronoLocalDate { if (chrono != chrono2) { try { date.with(adjuster); - Assert.fail("WithAdjuster should have thrown a ClassCastException"); + Assertions.fail("WithAdjuster should have thrown a ClassCastException"); } catch (ClassCastException cce) { // Expected exception; not an error } } else { // Same chronology, ChronoLocalDate result = date.with(adjuster); - assertEquals(result, date2, "WithAdjuster failed to replace date"); + assertEquals(date2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badPlusAdjusterChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDate date = chrono.date(refDate); @@ -142,19 +145,20 @@ public class TCKChronoLocalDate { if (chrono != chrono2) { try { date.plus(adjuster); - Assert.fail("WithAdjuster should have thrown a ClassCastException"); + Assertions.fail("WithAdjuster should have thrown a ClassCastException"); } catch (ClassCastException cce) { // Expected exception; not an error } } else { // Same chronology, ChronoLocalDate result = date.plus(adjuster); - assertEquals(result, date2, "WithAdjuster failed to replace date"); + assertEquals(date2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badMinusAdjusterChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDate date = chrono.date(refDate); @@ -165,19 +169,20 @@ public class TCKChronoLocalDate { if (chrono != chrono2) { try { date.minus(adjuster); - Assert.fail("WithAdjuster should have thrown a ClassCastException"); + Assertions.fail("WithAdjuster should have thrown a ClassCastException"); } catch (ClassCastException cce) { // Expected exception; not an error } } else { // Same chronology, ChronoLocalDate result = date.minus(adjuster); - assertEquals(result, date2, "WithAdjuster failed to replace date"); + assertEquals(date2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badPlusTemporalUnitChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDate date = chrono.date(refDate); @@ -188,7 +193,7 @@ public class TCKChronoLocalDate { if (chrono != chrono2) { try { date.plus(1, adjuster); - Assert.fail("TemporalUnit.doAdd plus should have thrown a ClassCastException" + date.getClass() + Assertions.fail("TemporalUnit.doAdd plus should have thrown a ClassCastException" + date.getClass() + ", can not be cast to " + date2.getClass()); } catch (ClassCastException cce) { // Expected exception; not an error @@ -196,12 +201,13 @@ public class TCKChronoLocalDate { } else { // Same chronology, ChronoLocalDate result = date.plus(1, adjuster); - assertEquals(result, date2, "WithAdjuster failed to replace date"); + assertEquals(date2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badMinusTemporalUnitChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDate date = chrono.date(refDate); @@ -212,7 +218,7 @@ public class TCKChronoLocalDate { if (chrono != chrono2) { try { date.minus(1, adjuster); - Assert.fail("TemporalUnit.doAdd minus should have thrown a ClassCastException" + date.getClass() + Assertions.fail("TemporalUnit.doAdd minus should have thrown a ClassCastException" + date.getClass() + ", can not be cast to " + date2.getClass()); } catch (ClassCastException cce) { // Expected exception; not an error @@ -220,12 +226,13 @@ public class TCKChronoLocalDate { } else { // Same chronology, ChronoLocalDate result = date.minus(1, adjuster); - assertEquals(result, date2, "WithAdjuster failed to replace date"); + assertEquals(date2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badTemporalFieldChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDate date = chrono.date(refDate); @@ -236,7 +243,7 @@ public class TCKChronoLocalDate { if (chrono != chrono2) { try { date.with(adjuster, 1); - Assert.fail("TemporalField doSet should have thrown a ClassCastException" + date.getClass() + Assertions.fail("TemporalField doSet should have thrown a ClassCastException" + date.getClass() + ", can not be cast to " + date2.getClass()); } catch (ClassCastException cce) { // Expected exception; not an error @@ -244,7 +251,7 @@ public class TCKChronoLocalDate { } else { // Same chronology, ChronoLocalDate result = date.with(adjuster, 1); - assertEquals(result, date2, "TemporalField doSet failed to replace date"); + assertEquals(date2, result, "TemporalField doSet failed to replace date"); } } } @@ -252,7 +259,8 @@ public class TCKChronoLocalDate { //----------------------------------------------------------------------- // isBefore, isAfter, isEqual, DATE_COMPARATOR //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_date_comparisons(Chronology chrono) { List dates = new ArrayList<>(); @@ -285,19 +293,19 @@ public class TCKChronoLocalDate { int cmp = ChronoLocalDate.timeLineOrder().compare(a, b); if (i < j) { assertTrue(cmp < 0, a + " compare " + b); - assertEquals(a.isBefore(b), true, a + " isBefore " + b); - assertEquals(a.isAfter(b), false, a + " isAfter " + b); - assertEquals(a.isEqual(b), false, a + " isEqual " + b); + assertEquals(true, a.isBefore(b), a + " isBefore " + b); + assertEquals(false, a.isAfter(b), a + " isAfter " + b); + assertEquals(false, a.isEqual(b), a + " isEqual " + b); } else if (i > j) { assertTrue(cmp > 0, a + " compare " + b); - assertEquals(a.isBefore(b), false, a + " isBefore " + b); - assertEquals(a.isAfter(b), true, a + " isAfter " + b); - assertEquals(a.isEqual(b), false, a + " isEqual " + b); + assertEquals(false, a.isBefore(b), a + " isBefore " + b); + assertEquals(true, a.isAfter(b), a + " isAfter " + b); + assertEquals(false, a.isEqual(b), a + " isEqual " + b); } else { assertTrue(cmp == 0, a + " compare " + b); - assertEquals(a.isBefore(b), false, a + " isBefore " + b); - assertEquals(a.isAfter(b), false, a + " isAfter " + b); - assertEquals(a.isEqual(b), true, a + " isEqual " + b); + assertEquals(false, a.isBefore(b), a + " isBefore " + b); + assertEquals(false, a.isAfter(b), a + " isAfter " + b); + assertEquals(true, a.isEqual(b), a + " isEqual " + b); } } } @@ -306,26 +314,27 @@ public class TCKChronoLocalDate { //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_from_TemporalAccessor(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDate date = chrono.date(refDate); ChronoLocalDate test1 = ChronoLocalDate.from(date); - assertEquals(test1, date); + assertEquals(date, test1); ChronoLocalDate test2 = ChronoLocalDate.from(date.atTime(LocalTime.of(12, 30))); - assertEquals(test2, date); + assertEquals(date, test2); ChronoLocalDate test3 = ChronoLocalDate.from(date.atTime(LocalTime.of(12, 30)).atZone(ZoneOffset.UTC)); - assertEquals(test3, date); + assertEquals(date, test3); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_from_TemporalAccessor_timeOnly() { - ChronoLocalDate.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> ChronoLocalDate.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_from_TemporalAccessor_null() { - ChronoLocalDate.from(null); + Assertions.assertThrows(NullPointerException.class, () -> ChronoLocalDate.from(null)); } //----------------------------------------------------------------------- diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKChronoLocalDateTime.java b/test/jdk/java/time/tck/java/time/chrono/TCKChronoLocalDateTime.java index 6a3c6a62e08..32cd7e5ab52 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKChronoLocalDateTime.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKChronoLocalDateTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,8 +54,8 @@ */ package tck.java.time.chrono; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -85,20 +85,21 @@ import java.time.temporal.ValueRange; import java.util.ArrayList; import java.util.List; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test assertions that must be true for all built-in chronologies. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoLocalDateTime { //----------------------------------------------------------------------- // regular data factory for names and descriptions of available calendars //----------------------------------------------------------------------- - @DataProvider(name = "calendars") Chronology[][] data_of_calendars() { return new Chronology[][]{ {HijrahChronology.INSTANCE}, @@ -108,7 +109,8 @@ public class TCKChronoLocalDateTime { {ThaiBuddhistChronology.INSTANCE}}; } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badWithAdjusterChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON); @@ -119,7 +121,7 @@ public class TCKChronoLocalDateTime { if (chrono != chrono2) { try { cdt.with(adjuster); - Assert.fail("WithAdjuster should have thrown a ClassCastException, " + Assertions.fail("WithAdjuster should have thrown a ClassCastException, " + "required: " + cdt + ", supplied: " + cdt2); } catch (ClassCastException cce) { // Expected exception; not an error @@ -127,12 +129,13 @@ public class TCKChronoLocalDateTime { } else { // Same chronology, ChronoLocalDateTime result = cdt.with(adjuster); - assertEquals(result, cdt2, "WithAdjuster failed to replace date"); + assertEquals(cdt2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badPlusAdjusterChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON); @@ -143,7 +146,7 @@ public class TCKChronoLocalDateTime { if (chrono != chrono2) { try { cdt.plus(adjuster); - Assert.fail("WithAdjuster should have thrown a ClassCastException, " + Assertions.fail("WithAdjuster should have thrown a ClassCastException, " + "required: " + cdt + ", supplied: " + cdt2); } catch (ClassCastException cce) { // Expected exception; not an error @@ -151,12 +154,13 @@ public class TCKChronoLocalDateTime { } else { // Same chronology, ChronoLocalDateTime result = cdt.plus(adjuster); - assertEquals(result, cdt2, "WithAdjuster failed to replace date time"); + assertEquals(cdt2, result, "WithAdjuster failed to replace date time"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badMinusAdjusterChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON); @@ -167,7 +171,7 @@ public class TCKChronoLocalDateTime { if (chrono != chrono2) { try { cdt.minus(adjuster); - Assert.fail("WithAdjuster should have thrown a ClassCastException, " + Assertions.fail("WithAdjuster should have thrown a ClassCastException, " + "required: " + cdt + ", supplied: " + cdt2); } catch (ClassCastException cce) { // Expected exception; not an error @@ -175,12 +179,13 @@ public class TCKChronoLocalDateTime { } else { // Same chronology, ChronoLocalDateTime result = cdt.minus(adjuster); - assertEquals(result, cdt2, "WithAdjuster failed to replace date"); + assertEquals(cdt2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badPlusTemporalUnitChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON); @@ -191,7 +196,7 @@ public class TCKChronoLocalDateTime { if (chrono != chrono2) { try { cdt.plus(1, adjuster); - Assert.fail("TemporalUnit.doPlus plus should have thrown a ClassCastException" + cdt + Assertions.fail("TemporalUnit.doPlus plus should have thrown a ClassCastException" + cdt + ", can not be cast to " + cdt2); } catch (ClassCastException cce) { // Expected exception; not an error @@ -199,12 +204,13 @@ public class TCKChronoLocalDateTime { } else { // Same chronology, ChronoLocalDateTime result = cdt.plus(1, adjuster); - assertEquals(result, cdt2, "WithAdjuster failed to replace date"); + assertEquals(cdt2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badMinusTemporalUnitChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON); @@ -215,7 +221,7 @@ public class TCKChronoLocalDateTime { if (chrono != chrono2) { try { cdt.minus(1, adjuster); - Assert.fail("TemporalUnit.doPlus minus should have thrown a ClassCastException" + cdt.getClass() + Assertions.fail("TemporalUnit.doPlus minus should have thrown a ClassCastException" + cdt.getClass() + ", can not be cast to " + cdt2.getClass()); } catch (ClassCastException cce) { // Expected exception; not an error @@ -223,12 +229,13 @@ public class TCKChronoLocalDateTime { } else { // Same chronology, ChronoLocalDateTime result = cdt.minus(1, adjuster); - assertEquals(result, cdt2, "WithAdjuster failed to replace date"); + assertEquals(cdt2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badTemporalFieldChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON); @@ -239,7 +246,7 @@ public class TCKChronoLocalDateTime { if (chrono != chrono2) { try { cdt.with(adjuster, 1); - Assert.fail("TemporalField doWith() should have thrown a ClassCastException" + cdt.getClass() + Assertions.fail("TemporalField doWith() should have thrown a ClassCastException" + cdt.getClass() + ", can not be cast to " + cdt2.getClass()); } catch (ClassCastException cce) { // Expected exception; not an error @@ -247,7 +254,7 @@ public class TCKChronoLocalDateTime { } else { // Same chronology, ChronoLocalDateTime result = cdt.with(adjuster, 1); - assertEquals(result, cdt2, "TemporalField doWith() failed to replace date"); + assertEquals(cdt2, result, "TemporalField doWith() failed to replace date"); } } } @@ -255,7 +262,8 @@ public class TCKChronoLocalDateTime { //----------------------------------------------------------------------- // isBefore, isAfter, isEqual //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_datetime_comparisons(Chronology chrono) { List> dates = new ArrayList<>(); @@ -296,19 +304,19 @@ public class TCKChronoLocalDateTime { int cmp = ChronoLocalDateTime.timeLineOrder().compare(a, b); if (i < j) { assertTrue(cmp < 0, a + " compare " + b); - assertEquals(a.isBefore(b), true, a + " isBefore " + b); - assertEquals(a.isAfter(b), false, a + " isAfter " + b); - assertEquals(a.isEqual(b), false, a + " isEqual " + b); + assertEquals(true, a.isBefore(b), a + " isBefore " + b); + assertEquals(false, a.isAfter(b), a + " isAfter " + b); + assertEquals(false, a.isEqual(b), a + " isEqual " + b); } else if (i > j) { assertTrue(cmp > 0, a + " compare " + b); - assertEquals(a.isBefore(b), false, a + " isBefore " + b); - assertEquals(a.isAfter(b), true, a + " isAfter " + b); - assertEquals(a.isEqual(b), false, a + " isEqual " + b); + assertEquals(false, a.isBefore(b), a + " isBefore " + b); + assertEquals(true, a.isAfter(b), a + " isAfter " + b); + assertEquals(false, a.isEqual(b), a + " isEqual " + b); } else { assertTrue(cmp == 0, a + " compare " + b); - assertEquals(a.isBefore(b), false, a + " isBefore " + b); - assertEquals(a.isAfter(b), false, a + " isAfter " + b); - assertEquals(a.isEqual(b), true, a + " isEqual " + b); + assertEquals(false, a.isBefore(b), a + " isBefore " + b); + assertEquals(false, a.isAfter(b), a + " isAfter " + b); + assertEquals(true, a.isEqual(b), a + " isEqual " + b); } } } @@ -316,36 +324,38 @@ public class TCKChronoLocalDateTime { } //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_from_TemporalAccessor(Chronology chrono) { LocalDateTime refDateTime = LocalDateTime.of(2013, 1, 1, 12, 30); ChronoLocalDateTime dateTime = chrono.localDateTime(refDateTime); ChronoLocalDateTime test1 = ChronoLocalDateTime.from(dateTime); - assertEquals(test1, dateTime); + assertEquals(dateTime, test1); ChronoLocalDateTime test2 = ChronoLocalDateTime.from(dateTime.atZone(ZoneOffset.UTC)); - assertEquals(test2, dateTime); + assertEquals(dateTime, test2); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_from_TemporalAccessor_dateOnly() { - ChronoLocalDateTime.from(LocalDate.of(2013, 1, 1)); + Assertions.assertThrows(DateTimeException.class, () -> ChronoLocalDateTime.from(LocalDate.of(2013, 1, 1))); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_from_TemporalAccessor_timeOnly() { - ChronoLocalDateTime.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> ChronoLocalDateTime.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_from_TemporalAccessor_null() { - ChronoLocalDateTime.from(null); + Assertions.assertThrows(NullPointerException.class, () -> ChronoLocalDateTime.from(null)); } //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_getChronology(Chronology chrono) { ChronoLocalDateTime test = chrono.localDateTime(LocalDateTime.of(2010, 6, 30, 11, 30)); - assertEquals(test.getChronology(), chrono); + assertEquals(chrono, test.getChronology()); } //----------------------------------------------------------------------- diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKChronoPeriod.java b/test/jdk/java/time/tck/java/time/chrono/TCKChronoPeriod.java index 3fbc4d02bee..e54d669c8ff 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKChronoPeriod.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKChronoPeriod.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -58,7 +58,8 @@ import static java.time.temporal.ChronoUnit.DAYS; import static java.time.temporal.ChronoUnit.HOURS; import static java.time.temporal.ChronoUnit.MONTHS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -78,16 +79,17 @@ import java.time.chrono.ThaiBuddhistChronology; import java.time.temporal.Temporal; import java.time.temporal.UnsupportedTemporalTypeException; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoPeriod { //----------------------------------------------------------------------- // regular data factory for names and descriptions of available calendars //----------------------------------------------------------------------- - @DataProvider(name = "calendars") Chronology[][] data_of_calendars() { return new Chronology[][]{ {HijrahChronology.INSTANCE}, @@ -100,7 +102,8 @@ public class TCKChronoPeriod { //----------------------------------------------------------------------- // Test Serialization of Calendars //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_serialization(Chronology chrono) throws Exception { ChronoPeriod period = chrono.period(1, 2, 3); ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -111,167 +114,195 @@ public class TCKChronoPeriod { ObjectInputStream in = new ObjectInputStream(bais); ChronoPeriod ser = (ChronoPeriod) in.readObject(); - assertEquals(ser, period, "deserialized ChronoPeriod is wrong"); + assertEquals(period, ser, "deserialized ChronoPeriod is wrong"); } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_get(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); - assertEquals(period.get(YEARS), 1); - assertEquals(period.get(MONTHS), 2); - assertEquals(period.get(DAYS), 3); + assertEquals(1, period.get(YEARS)); + assertEquals(2, period.get(MONTHS)); + assertEquals(3, period.get(DAYS)); } - @Test(dataProvider="calendars", expectedExceptions=UnsupportedTemporalTypeException.class) + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_get_unsupported(Chronology chrono) { - ChronoPeriod period = chrono.period(1, 2, 3); - period.get(HOURS); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> { + ChronoPeriod period = chrono.period(1, 2, 3); + period.get(HOURS); + }); } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_getUnits(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); - assertEquals(period.getUnits().size(), 3); - assertEquals(period.getUnits().get(0), YEARS); - assertEquals(period.getUnits().get(1), MONTHS); - assertEquals(period.getUnits().get(2), DAYS); + assertEquals(3, period.getUnits().size()); + assertEquals(YEARS, period.getUnits().get(0)); + assertEquals(MONTHS, period.getUnits().get(1)); + assertEquals(DAYS, period.getUnits().get(2)); } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_getChronology(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); - assertEquals(period.getChronology(), chrono); + assertEquals(chrono, period.getChronology()); } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_isZero_isNegative(Chronology chrono) { ChronoPeriod periodPositive = chrono.period(1, 2, 3); - assertEquals(periodPositive.isZero(), false); - assertEquals(periodPositive.isNegative(), false); + assertEquals(false, periodPositive.isZero()); + assertEquals(false, periodPositive.isNegative()); ChronoPeriod periodZero = chrono.period(0, 0, 0); - assertEquals(periodZero.isZero(), true); - assertEquals(periodZero.isNegative(), false); + assertEquals(true, periodZero.isZero()); + assertEquals(false, periodZero.isNegative()); ChronoPeriod periodNegative = chrono.period(-1, 0, 0); - assertEquals(periodNegative.isZero(), false); - assertEquals(periodNegative.isNegative(), true); + assertEquals(false, periodNegative.isZero()); + assertEquals(true, periodNegative.isNegative()); } //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_plus(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); ChronoPeriod period2 = chrono.period(2, 3, 4); ChronoPeriod result = period.plus(period2); - assertEquals(result, chrono.period(3, 5, 7)); + assertEquals(chrono.period(3, 5, 7), result); } - @Test(dataProvider="calendars", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_plus_wrongChrono(Chronology chrono) { - ChronoPeriod period = chrono.period(1, 2, 3); - ChronoPeriod isoPeriod = Period.of(2, 3, 4); - ChronoPeriod thaiPeriod = ThaiBuddhistChronology.INSTANCE.period(2, 3, 4); - // one of these two will fail - period.plus(isoPeriod); - period.plus(thaiPeriod); + Assertions.assertThrows(DateTimeException.class, () -> { + ChronoPeriod period = chrono.period(1, 2, 3); + ChronoPeriod isoPeriod = Period.of(2, 3, 4); + ChronoPeriod thaiPeriod = ThaiBuddhistChronology.INSTANCE.period(2, 3, 4); + // one of these two will fail + period.plus(isoPeriod); + period.plus(thaiPeriod); + }); } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_minus(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); ChronoPeriod period2 = chrono.period(2, 3, 4); ChronoPeriod result = period.minus(period2); - assertEquals(result, chrono.period(-1, -1, -1)); + assertEquals(chrono.period(-1, -1, -1), result); } - @Test(dataProvider="calendars", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_minus_wrongChrono(Chronology chrono) { - ChronoPeriod period = chrono.period(1, 2, 3); - ChronoPeriod isoPeriod = Period.of(2, 3, 4); - ChronoPeriod thaiPeriod = ThaiBuddhistChronology.INSTANCE.period(2, 3, 4); - // one of these two will fail - period.minus(isoPeriod); - period.minus(thaiPeriod); + Assertions.assertThrows(DateTimeException.class, () -> { + ChronoPeriod period = chrono.period(1, 2, 3); + ChronoPeriod isoPeriod = Period.of(2, 3, 4); + ChronoPeriod thaiPeriod = ThaiBuddhistChronology.INSTANCE.period(2, 3, 4); + // one of these two will fail + period.minus(isoPeriod); + period.minus(thaiPeriod); + }); } //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_addTo(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); ChronoLocalDate date = chrono.dateNow(); Temporal result = period.addTo(date); - assertEquals(result, date.plus(14, MONTHS).plus(3, DAYS)); + assertEquals(date.plus(14, MONTHS).plus(3, DAYS), result); } - @Test(dataProvider="calendars", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_addTo_wrongChrono(Chronology chrono) { - ChronoPeriod period = chrono.period(1, 2, 3); - ChronoLocalDate isoDate = LocalDate.of(2000, 1, 1); - ChronoLocalDate thaiDate = ThaiBuddhistChronology.INSTANCE.date(2000, 1, 1); - // one of these two will fail - period.addTo(isoDate); - period.addTo(thaiDate); + Assertions.assertThrows(DateTimeException.class, () -> { + ChronoPeriod period = chrono.period(1, 2, 3); + ChronoLocalDate isoDate = LocalDate.of(2000, 1, 1); + ChronoLocalDate thaiDate = ThaiBuddhistChronology.INSTANCE.date(2000, 1, 1); + // one of these two will fail + period.addTo(isoDate); + period.addTo(thaiDate); + }); } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_subtractFrom(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); ChronoLocalDate date = chrono.dateNow(); Temporal result = period.subtractFrom(date); - assertEquals(result, date.minus(14, MONTHS).minus(3, DAYS)); + assertEquals(date.minus(14, MONTHS).minus(3, DAYS), result); } - @Test(dataProvider="calendars", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_subtractFrom_wrongChrono(Chronology chrono) { - ChronoPeriod period = chrono.period(1, 2, 3); - ChronoLocalDate isoDate = LocalDate.of(2000, 1, 1); - ChronoLocalDate thaiDate = ThaiBuddhistChronology.INSTANCE.date(2000, 1, 1); - // one of these two will fail - period.subtractFrom(isoDate); - period.subtractFrom(thaiDate); + Assertions.assertThrows(DateTimeException.class, () -> { + ChronoPeriod period = chrono.period(1, 2, 3); + ChronoLocalDate isoDate = LocalDate.of(2000, 1, 1); + ChronoLocalDate thaiDate = ThaiBuddhistChronology.INSTANCE.date(2000, 1, 1); + // one of these two will fail + period.subtractFrom(isoDate); + period.subtractFrom(thaiDate); + }); } //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_negated(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); - assertEquals(period.negated(), chrono.period(-1, -2, -3)); + assertEquals(chrono.period(-1, -2, -3), period.negated()); } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_multipliedBy(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); - assertEquals(period.multipliedBy(3), chrono.period(3, 6, 9)); + assertEquals(chrono.period(3, 6, 9), period.multipliedBy(3)); } //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_equals_equal(Chronology chrono) { ChronoPeriod a1 = chrono.period(1, 2, 3); ChronoPeriod a2 = chrono.period(1, 2, 3); assertEquals(a1, a1); - assertEquals(a1, a2); assertEquals(a2, a1); + assertEquals(a1, a2); assertEquals(a2, a2); - assertEquals(a1.hashCode(), a2.hashCode()); + assertEquals(a2.hashCode(), a1.hashCode()); } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_equals_notEqual(Chronology chrono) { ChronoPeriod a = chrono.period(1, 2, 3); ChronoPeriod b = chrono.period(2, 2, 3); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(a.equals(""), false); - assertEquals(a.equals(null), false); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(false, a.equals("")); + assertEquals(false, a.equals(null)); } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_toString(Chronology chrono) { ChronoPeriod period = chrono.period(1, 2, 3); if (period instanceof Period == false) { - assertEquals(period.toString(), chrono.getId() + " P1Y2M3D"); + assertEquals(chrono.getId() + " P1Y2M3D", period.toString()); } } diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKChronoZonedDateTime.java b/test/jdk/java/time/tck/java/time/chrono/TCKChronoZonedDateTime.java index be2f9fb1ac9..be1ce445498 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKChronoZonedDateTime.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKChronoZonedDateTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,8 +54,8 @@ */ package tck.java.time.chrono; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -86,20 +86,21 @@ import java.time.temporal.ValueRange; import java.util.ArrayList; import java.util.List; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test assertions that must be true for all built-in chronologies. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoZonedDateTime { //----------------------------------------------------------------------- // regular data factory for names and descriptions of available calendars //----------------------------------------------------------------------- - @DataProvider(name = "calendars") Chronology[][] data_of_calendars() { return new Chronology[][]{ {HijrahChronology.INSTANCE}, @@ -110,7 +111,8 @@ public class TCKChronoZonedDateTime { }; } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badWithAdjusterChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoZonedDateTime czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC); @@ -121,19 +123,20 @@ public class TCKChronoZonedDateTime { if (chrono != chrono2) { try { czdt.with(adjuster); - Assert.fail("WithAdjuster should have thrown a ClassCastException, " + Assertions.fail("WithAdjuster should have thrown a ClassCastException, " + "required: " + czdt + ", supplied: " + czdt2); } catch (ClassCastException cce) { // Expected exception; not an error } } else { ChronoZonedDateTime result = czdt.with(adjuster); - assertEquals(result, czdt2, "WithAdjuster failed to replace date"); + assertEquals(czdt2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badPlusAdjusterChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoZonedDateTime czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC); @@ -144,7 +147,7 @@ public class TCKChronoZonedDateTime { if (chrono != chrono2) { try { czdt.plus(adjuster); - Assert.fail("WithAdjuster should have thrown a ClassCastException, " + Assertions.fail("WithAdjuster should have thrown a ClassCastException, " + "required: " + czdt + ", supplied: " + czdt2); } catch (ClassCastException cce) { // Expected exception; not an error @@ -152,12 +155,13 @@ public class TCKChronoZonedDateTime { } else { // Same chronology, ChronoZonedDateTime result = czdt.plus(adjuster); - assertEquals(result, czdt2, "WithAdjuster failed to replace date time"); + assertEquals(czdt2, result, "WithAdjuster failed to replace date time"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badMinusAdjusterChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoZonedDateTime czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC); @@ -168,7 +172,7 @@ public class TCKChronoZonedDateTime { if (chrono != chrono2) { try { czdt.minus(adjuster); - Assert.fail("WithAdjuster should have thrown a ClassCastException, " + Assertions.fail("WithAdjuster should have thrown a ClassCastException, " + "required: " + czdt + ", supplied: " + czdt2); } catch (ClassCastException cce) { // Expected exception; not an error @@ -176,12 +180,13 @@ public class TCKChronoZonedDateTime { } else { // Same chronology, ChronoZonedDateTime result = czdt.minus(adjuster); - assertEquals(result, czdt2, "WithAdjuster failed to replace date"); + assertEquals(czdt2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badPlusTemporalUnitChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoZonedDateTime czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC); @@ -192,7 +197,7 @@ public class TCKChronoZonedDateTime { if (chrono != chrono2) { try { czdt.plus(1, adjuster); - Assert.fail("TemporalUnit.doPlus plus should have thrown a ClassCastException, " + czdt + Assertions.fail("TemporalUnit.doPlus plus should have thrown a ClassCastException, " + czdt + " can not be cast to " + czdt2); } catch (ClassCastException cce) { // Expected exception; not an error @@ -200,12 +205,13 @@ public class TCKChronoZonedDateTime { } else { // Same chronology, ChronoZonedDateTime result = czdt.plus(1, adjuster); - assertEquals(result, czdt2, "WithAdjuster failed to replace date"); + assertEquals(czdt2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badMinusTemporalUnitChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoZonedDateTime czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC); @@ -216,7 +222,7 @@ public class TCKChronoZonedDateTime { if (chrono != chrono2) { try { czdt.minus(1, adjuster); - Assert.fail("TemporalUnit.doPlus minus should have thrown a ClassCastException, " + czdt.getClass() + Assertions.fail("TemporalUnit.doPlus minus should have thrown a ClassCastException, " + czdt.getClass() + " can not be cast to " + czdt2.getClass()); } catch (ClassCastException cce) { // Expected exception; not an error @@ -224,12 +230,13 @@ public class TCKChronoZonedDateTime { } else { // Same chronology, ChronoZonedDateTime result = czdt.minus(1, adjuster); - assertEquals(result, czdt2, "WithAdjuster failed to replace date"); + assertEquals(czdt2, result, "WithAdjuster failed to replace date"); } } } - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_badTemporalFieldChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoZonedDateTime czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC); @@ -240,7 +247,7 @@ public class TCKChronoZonedDateTime { if (chrono != chrono2) { try { czdt.with(adjuster, 1); - Assert.fail("TemporalField doWith() should have thrown a ClassCastException, " + czdt.getClass() + Assertions.fail("TemporalField doWith() should have thrown a ClassCastException, " + czdt.getClass() + " can not be cast to " + czdt2.getClass()); } catch (ClassCastException cce) { // Expected exception; not an error @@ -248,7 +255,7 @@ public class TCKChronoZonedDateTime { } else { // Same chronology, ChronoZonedDateTime result = czdt.with(adjuster, 1); - assertEquals(result, czdt2, "TemporalField doWith() failed to replace date"); + assertEquals(czdt2, result, "TemporalField doWith() failed to replace date"); } } } @@ -256,7 +263,8 @@ public class TCKChronoZonedDateTime { //----------------------------------------------------------------------- // isBefore, isAfter, isEqual, timeLineOrder() test a Chronology against the other Chronos //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_zonedDateTime_comparisons(Chronology chrono) { List> dates = new ArrayList<>(); @@ -299,19 +307,19 @@ public class TCKChronoZonedDateTime { int cmp = ChronoZonedDateTime.timeLineOrder().compare(a, b); if (i < j) { assertTrue(cmp < 0, a + " compare " + b); - assertEquals(a.isBefore(b), true, a + " isBefore " + b); - assertEquals(a.isAfter(b), false, a + " ifAfter " + b); - assertEquals(a.isEqual(b), false, a + " isEqual " + b); + assertEquals(true, a.isBefore(b), a + " isBefore " + b); + assertEquals(false, a.isAfter(b), a + " ifAfter " + b); + assertEquals(false, a.isEqual(b), a + " isEqual " + b); } else if (i > j) { assertTrue(cmp > 0, a + " compare " + b); - assertEquals(a.isBefore(b), false, a + " isBefore " + b); - assertEquals(a.isAfter(b), true, a + " ifAfter " + b); - assertEquals(a.isEqual(b), false, a + " isEqual " + b); + assertEquals(false, a.isBefore(b), a + " isBefore " + b); + assertEquals(true, a.isAfter(b), a + " ifAfter " + b); + assertEquals(false, a.isEqual(b), a + " isEqual " + b); } else { assertTrue(cmp == 0, a + " compare " + b); - assertEquals(a.isBefore(b), false, a + " isBefore " + b); - assertEquals(a.isAfter(b), false, a + " ifAfter " + b); - assertEquals(a.isEqual(b), true, a + " isEqual " + b); + assertEquals(false, a.isBefore(b), a + " isBefore " + b); + assertEquals(false, a.isAfter(b), a + " ifAfter " + b); + assertEquals(true, a.isEqual(b), a + " isEqual " + b); } } } @@ -319,34 +327,36 @@ public class TCKChronoZonedDateTime { } //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_from_TemporalAccessor(Chronology chrono) { ZonedDateTime refDateTime = ZonedDateTime.of(2013, 1, 1, 12, 30, 0, 0, ZoneId.of("Europe/Paris")); ChronoZonedDateTime dateTime = chrono.zonedDateTime(refDateTime); ChronoZonedDateTime test1 = ChronoZonedDateTime.from(dateTime); - assertEquals(test1, dateTime); + assertEquals(dateTime, test1); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_from_TemporalAccessor_dateOnly() { - ChronoZonedDateTime.from(LocalDate.of(2013, 1, 1)); + Assertions.assertThrows(DateTimeException.class, () -> ChronoZonedDateTime.from(LocalDate.of(2013, 1, 1))); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_from_TemporalAccessor_timeOnly() { - ChronoZonedDateTime.from(LocalTime.of(12, 30)); + Assertions.assertThrows(DateTimeException.class, () -> ChronoZonedDateTime.from(LocalTime.of(12, 30))); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_from_TemporalAccessor_null() { - ChronoZonedDateTime.from(null); + Assertions.assertThrows(NullPointerException.class, () -> ChronoZonedDateTime.from(null)); } //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_getChronology(Chronology chrono) { ChronoZonedDateTime test = chrono.zonedDateTime(ZonedDateTime.of(2010, 6, 30, 11, 30, 0, 0, ZoneOffset.UTC)); - assertEquals(test.getChronology(), chrono); + assertEquals(chrono, test.getChronology()); } //----------------------------------------------------------------------- diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKChronology.java b/test/jdk/java/time/tck/java/time/chrono/TCKChronology.java index b73ff23dbfe..58313001faf 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKChronology.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKChronology.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,10 +59,9 @@ */ package tck.java.time.chrono; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Clock; import java.time.DateTimeException; @@ -89,13 +88,16 @@ import java.time.temporal.ChronoField; import java.util.Locale; import java.util.Set; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test Chronology class. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronology { private static final ZoneOffset OFFSET_P0100 = ZoneOffset.ofHours(1); @@ -109,7 +111,6 @@ public class TCKChronology { //----------------------------------------------------------------------- // regular data factory for ID and calendarType of available calendars //----------------------------------------------------------------------- - @DataProvider(name = "calendarNameAndType") Object[][] data_of_calendars() { return new Object[][] { {"Hijrah-umalqura", "islamic-umalqura"}, @@ -120,15 +121,17 @@ public class TCKChronology { }; } - @Test(dataProvider = "calendarNameAndType") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_getters(String chronoId, String calendarSystemType) { Chronology chrono = Chronology.of(chronoId); assertNotNull(chrono, "Required calendar not found by ID: " + chronoId); - assertEquals(chrono.getId(), chronoId); - assertEquals(chrono.getCalendarType(), calendarSystemType); + assertEquals(chronoId, chrono.getId()); + assertEquals(calendarSystemType, chrono.getCalendarType()); } - @Test(dataProvider = "calendarNameAndType") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_required_calendars(String chronoId, String calendarSystemType) { Chronology chrono = Chronology.of(chronoId); assertNotNull(chrono, "Required calendar not found by ID: " + chronoId); @@ -146,14 +149,13 @@ public class TCKChronology { Chronology lookup = Chronology.of(chrono.getId()); assertNotNull(lookup, "Required calendar not found: " + chrono); } - assertEquals(chronos.size() >= data_of_calendars().length, true, "Chronology.getAvailableChronologies().size = " + chronos.size() + assertEquals(true, chronos.size() >= data_of_calendars().length, "Chronology.getAvailableChronologies().size = " + chronos.size() + ", expected >= " + data_of_calendars().length); } //----------------------------------------------------------------------- // getDisplayName() //----------------------------------------------------------------------- - @DataProvider(name = "calendarDisplayName") Object[][] data_of_calendarDisplayNames() { return new Object[][] { {"Hijrah", "Hijri Calendar (Umm al-Qura)"}, @@ -164,39 +166,41 @@ public class TCKChronology { }; } - @Test(dataProvider = "calendarDisplayName") + @ParameterizedTest + @MethodSource("data_of_calendarDisplayNames") public void test_getDisplayName(String chronoId, String calendarDisplayName) { Chronology chrono = Chronology.of(chronoId); - assertEquals(chrono.getDisplayName(TextStyle.FULL, Locale.ENGLISH), calendarDisplayName); + assertEquals(calendarDisplayName, chrono.getDisplayName(TextStyle.FULL, Locale.ENGLISH)); } /** * Compute the number of days from the Epoch and compute the date from the number of days. */ - @Test(dataProvider = "calendarNameAndType") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_epoch(String name, String alias) { Chronology chrono = Chronology.of(name); // a chronology. In practice this is rarely hardcoded ChronoLocalDate date1 = chrono.dateNow(); long epoch1 = date1.getLong(ChronoField.EPOCH_DAY); ChronoLocalDate date2 = date1.with(ChronoField.EPOCH_DAY, epoch1); - assertEquals(date1, date2, "Date from epoch day is not same date: " + date1 + " != " + date2); + assertEquals(date2, date1, "Date from epoch day is not same date: " + date1 + " != " + date2); long epoch2 = date1.getLong(ChronoField.EPOCH_DAY); - assertEquals(epoch1, epoch2, "Epoch day not the same: " + epoch1 + " != " + epoch2); + assertEquals(epoch2, epoch1, "Epoch day not the same: " + epoch1 + " != " + epoch2); } - @Test(dataProvider = "calendarNameAndType") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_dateEpochDay(String name, String alias) { Chronology chrono = Chronology.of(name); ChronoLocalDate date = chrono.dateNow(); long epochDay = date.getLong(ChronoField.EPOCH_DAY); ChronoLocalDate test = chrono.dateEpochDay(epochDay); - assertEquals(test, date); + assertEquals(date, test); } //----------------------------------------------------------------------- // locale based lookup //----------------------------------------------------------------------- - @DataProvider(name = "calendarsystemtype") Object[][] data_CalendarType() { return new Object[][] { {HijrahChronology.INSTANCE, "islamic-umalqura"}, @@ -207,18 +211,20 @@ public class TCKChronology { }; } - @Test(dataProvider = "calendarsystemtype") + @ParameterizedTest + @MethodSource("data_CalendarType") public void test_getCalendarType(Chronology chrono, String calendarType) { String type = calendarType; - assertEquals(chrono.getCalendarType(), type); + assertEquals(type, chrono.getCalendarType()); } - @Test(dataProvider = "calendarsystemtype") + @ParameterizedTest + @MethodSource("data_CalendarType") public void test_lookupLocale(Chronology chrono, String calendarType) { Locale.Builder builder = new Locale.Builder().setLanguage("en").setRegion("CA"); builder.setUnicodeLocaleKeyword("ca", calendarType); Locale locale = builder.build(); - assertEquals(Chronology.ofLocale(locale), chrono); + assertEquals(chrono, Chronology.ofLocale(locale)); } //----------------------------------------------------------------------- @@ -230,9 +236,9 @@ public class TCKChronology { Clock clock = Clock.system(zoneId_paris); Chronology chrono = Chronology.of("Minguo"); - assertEquals(chrono.dateNow(), MinguoChronology.INSTANCE.dateNow()); - assertEquals(chrono.dateNow(zoneId_paris), MinguoChronology.INSTANCE.dateNow(zoneId_paris)); - assertEquals(chrono.dateNow(clock), MinguoChronology.INSTANCE.dateNow(clock)); + assertEquals(MinguoChronology.INSTANCE.dateNow(), chrono.dateNow()); + assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId_paris), chrono.dateNow(zoneId_paris)); + assertEquals(MinguoChronology.INSTANCE.dateNow(clock), chrono.dateNow(clock)); } @Test @@ -241,9 +247,9 @@ public class TCKChronology { Clock clock = Clock.system(zoneId_paris); Chronology chrono = Chronology.of("ISO"); - assertEquals(chrono.dateNow(), IsoChronology.INSTANCE.dateNow()); - assertEquals(chrono.dateNow(zoneId_paris), IsoChronology.INSTANCE.dateNow(zoneId_paris)); - assertEquals(chrono.dateNow(clock), IsoChronology.INSTANCE.dateNow(clock)); + assertEquals(IsoChronology.INSTANCE.dateNow(), chrono.dateNow()); + assertEquals(IsoChronology.INSTANCE.dateNow(zoneId_paris), chrono.dateNow(zoneId_paris)); + assertEquals(IsoChronology.INSTANCE.dateNow(clock), chrono.dateNow(clock)); } @Test @@ -252,9 +258,9 @@ public class TCKChronology { Clock clock = Clock.system(zoneId_paris); Chronology chrono = Chronology.of("Japanese"); - assertEquals(chrono.dateNow(), JapaneseChronology.INSTANCE.dateNow()); - assertEquals(chrono.dateNow(zoneId_paris), JapaneseChronology.INSTANCE.dateNow(zoneId_paris)); - assertEquals(chrono.dateNow(clock), JapaneseChronology.INSTANCE.dateNow(clock)); + assertEquals(JapaneseChronology.INSTANCE.dateNow(), chrono.dateNow()); + assertEquals(JapaneseChronology.INSTANCE.dateNow(zoneId_paris), chrono.dateNow(zoneId_paris)); + assertEquals(JapaneseChronology.INSTANCE.dateNow(clock), chrono.dateNow(clock)); } @Test @@ -263,9 +269,9 @@ public class TCKChronology { Clock clock = Clock.system(zoneId_paris); Chronology chrono = Chronology.of("ThaiBuddhist"); - assertEquals(chrono.dateNow(), ThaiBuddhistChronology.INSTANCE.dateNow()); - assertEquals(chrono.dateNow(zoneId_paris), ThaiBuddhistChronology.INSTANCE.dateNow(zoneId_paris)); - assertEquals(chrono.dateNow(clock), ThaiBuddhistChronology.INSTANCE.dateNow(clock)); + assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), chrono.dateNow()); + assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(zoneId_paris), chrono.dateNow(zoneId_paris)); + assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(clock), chrono.dateNow(clock)); } //----------------------------------------------------------------------- @@ -276,8 +282,8 @@ public class TCKChronology { Chronology chrono = Chronology.of("Hijrah"); ChronoLocalDate date1 = chrono.dateYearDay(HijrahEra.AH, 1434, 178); ChronoLocalDate date2 = chrono.date(HijrahEra.AH, 1434, 7, 1); - assertEquals(date1, HijrahChronology.INSTANCE.dateYearDay(HijrahEra.AH, 1434, 178)); - assertEquals(date2, HijrahChronology.INSTANCE.dateYearDay(HijrahEra.AH, 1434, 178)); + assertEquals(HijrahChronology.INSTANCE.dateYearDay(HijrahEra.AH, 1434, 178), date1); + assertEquals(HijrahChronology.INSTANCE.dateYearDay(HijrahEra.AH, 1434, 178), date2); } @Test @@ -285,8 +291,8 @@ public class TCKChronology { Chronology chrono = Chronology.of("Minguo"); ChronoLocalDate date1 = chrono.dateYearDay(MinguoEra.ROC, 5, 60); ChronoLocalDate date2 = chrono.date(MinguoEra.ROC, 5, 2, 29); - assertEquals(date1, MinguoChronology.INSTANCE.dateYearDay(MinguoEra.ROC, 5, 60)); - assertEquals(date2, MinguoChronology.INSTANCE.dateYearDay(MinguoEra.ROC, 5, 60)); + assertEquals(MinguoChronology.INSTANCE.dateYearDay(MinguoEra.ROC, 5, 60), date1); + assertEquals(MinguoChronology.INSTANCE.dateYearDay(MinguoEra.ROC, 5, 60), date2); } @Test @@ -294,8 +300,8 @@ public class TCKChronology { Chronology chrono = Chronology.of("ISO"); ChronoLocalDate date1 = chrono.dateYearDay(IsoEra.CE, 5, 60); ChronoLocalDate date2 = chrono.date(IsoEra.CE, 5, 3, 1); - assertEquals(date1, IsoChronology.INSTANCE.dateYearDay(IsoEra.CE, 5, 60)); - assertEquals(date2, IsoChronology.INSTANCE.dateYearDay(IsoEra.CE, 5, 60)); + assertEquals(IsoChronology.INSTANCE.dateYearDay(IsoEra.CE, 5, 60), date1); + assertEquals(IsoChronology.INSTANCE.dateYearDay(IsoEra.CE, 5, 60), date2); } @Test @@ -303,8 +309,8 @@ public class TCKChronology { Chronology chrono = Chronology.of("Japanese"); ChronoLocalDate date1 = chrono.dateYearDay(JapaneseEra.HEISEI, 8, 60); ChronoLocalDate date2 = chrono.date(JapaneseEra.HEISEI, 8, 2, 29); - assertEquals(date1, JapaneseChronology.INSTANCE.dateYearDay(JapaneseEra.HEISEI, 8, 60)); - assertEquals(date2, JapaneseChronology.INSTANCE.dateYearDay(JapaneseEra.HEISEI, 8, 60)); + assertEquals(JapaneseChronology.INSTANCE.dateYearDay(JapaneseEra.HEISEI, 8, 60), date1); + assertEquals(JapaneseChronology.INSTANCE.dateYearDay(JapaneseEra.HEISEI, 8, 60), date2); } @Test @@ -312,8 +318,8 @@ public class TCKChronology { Chronology chrono = Chronology.of("ThaiBuddhist"); ChronoLocalDate date1 = chrono.dateYearDay(ThaiBuddhistEra.BE, 2459, 60); ChronoLocalDate date2 = chrono.date(ThaiBuddhistEra.BE, 2459, 2, 29); - assertEquals(date1, ThaiBuddhistChronology.INSTANCE.dateYearDay(ThaiBuddhistEra.BE, 2459, 60)); - assertEquals(date2, ThaiBuddhistChronology.INSTANCE.dateYearDay(ThaiBuddhistEra.BE, 2459, 60)); + assertEquals(ThaiBuddhistChronology.INSTANCE.dateYearDay(ThaiBuddhistEra.BE, 2459, 60), date1); + assertEquals(ThaiBuddhistChronology.INSTANCE.dateYearDay(ThaiBuddhistEra.BE, 2459, 60), date2); } /** @@ -328,25 +334,28 @@ public class TCKChronology { Locale.Builder builder = new Locale.Builder().setLanguage("en").setRegion("CA"); builder.setUnicodeLocaleKeyword("ca", chrono.getCalendarType()); Locale locale = builder.build(); - assertEquals(Chronology.ofLocale(locale), chrono, "Lookup by type"); + assertEquals(chrono, Chronology.ofLocale(locale), "Lookup by type"); } } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_lookupLocale() { - Locale.Builder builder = new Locale.Builder().setLanguage("en").setRegion("CA"); - builder.setUnicodeLocaleKeyword("ca", "xxx"); + Assertions.assertThrows(DateTimeException.class, () -> { + Locale.Builder builder = new Locale.Builder().setLanguage("en").setRegion("CA"); + builder.setUnicodeLocaleKeyword("ca", "xxx"); - Locale locale = builder.build(); - Chronology.ofLocale(locale); + Locale locale = builder.build(); + Chronology.ofLocale(locale); + }); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_noChrono() { - Chronology chrono = Chronology.of("FooFoo"); + Assertions.assertThrows(DateTimeException.class, () -> { + Chronology chrono = Chronology.of("FooFoo"); + }); } - @DataProvider(name = "epochSecond_dataProvider") Object[][] data_epochSecond() { return new Object[][] { {JapaneseChronology.INSTANCE, 1873, 9, 7, 1, 2, 2, OFFSET_P0100}, @@ -366,15 +375,14 @@ public class TCKChronology { }; } - @Test(dataProvider = "epochSecond_dataProvider") + @ParameterizedTest + @MethodSource("data_epochSecond") public void test_epochSecond(Chronology chrono, int y, int m, int d, int h, int min, int s, ZoneOffset offset) { ChronoLocalDate chronoLd = chrono.date(y, m, d); - assertEquals(chrono.epochSecond(y, m, d, h, min, s, offset), - OffsetDateTime.of(LocalDate.from(chronoLd), LocalTime.of(h, min, s), offset) - .toEpochSecond()); + assertEquals(OffsetDateTime.of(LocalDate.from(chronoLd), LocalTime.of(h, min, s), offset) + .toEpochSecond(), chrono.epochSecond(y, m, d, h, min, s, offset)); } - @DataProvider(name = "era_epochSecond_dataProvider") Object[][] data_era_epochSecond() { return new Object[][] { {JapaneseChronology.INSTANCE, JapaneseEra.MEIJI, 1873 - YDIFF_MEIJI, 9, 7, 1, 2, 2, OFFSET_P0100}, @@ -394,15 +402,14 @@ public class TCKChronology { }; } - @Test(dataProvider = "era_epochSecond_dataProvider") + @ParameterizedTest + @MethodSource("data_era_epochSecond") public void test_epochSecond(Chronology chrono, Era era, int y, int m, int d, int h, int min, int s, ZoneOffset offset) { ChronoLocalDate chronoLd = chrono.date(era, y, m, d); - assertEquals(chrono.epochSecond(era, y, m, d, h, min, s, offset), - OffsetDateTime.of(LocalDate.from(chronoLd), LocalTime.of(h, min, s), offset) - .toEpochSecond()); + assertEquals(OffsetDateTime.of(LocalDate.from(chronoLd), LocalTime.of(h, min, s), offset) + .toEpochSecond(), chrono.epochSecond(era, y, m, d, h, min, s, offset)); } - @DataProvider(name = "bad_epochSecond_dataProvider") Object[][] bad_data_epochSecond() { return new Object[][] { {JapaneseChronology.INSTANCE, 1873, 13, 7, 1, 2, 2, OFFSET_P0100}, @@ -415,12 +422,12 @@ public class TCKChronology { }; } - @Test(dataProvider = "bad_epochSecond_dataProvider", expectedExceptions = DateTimeException.class) + @ParameterizedTest + @MethodSource("bad_data_epochSecond") public void test_bad_epochSecond(Chronology chrono, int y, int m, int d, int h, int min, int s, ZoneOffset offset) { - chrono.epochSecond(y, m, d, h, min, s, offset); + Assertions.assertThrows(DateTimeException.class, () -> chrono.epochSecond(y, m, d, h, min, s, offset)); } - @DataProvider Object[][] data_isIsoBased() { return new Object[][] { {IsoChronology.INSTANCE, true}, @@ -434,8 +441,9 @@ public class TCKChronology { //----------------------------------------------------------------------- // isIsoBased() //----------------------------------------------------------------------- - @Test(dataProvider = "data_isIsoBased") + @ParameterizedTest + @MethodSource("data_isIsoBased") public void test_isIsoBased(Chronology chrono, boolean expected) { - assertEquals(chrono.isIsoBased(), expected); + assertEquals(expected, chrono.isIsoBased()); } } diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKHijrahChronology.java b/test/jdk/java/time/tck/java/time/chrono/TCKHijrahChronology.java index 7301ff67dca..7ada7b38aff 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKHijrahChronology.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKHijrahChronology.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -55,10 +55,11 @@ package tck.java.time.chrono; import java.time.Clock; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.DateTimeException; import java.time.ZoneId; @@ -77,14 +78,16 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKHijrahChronology { //----------------------------------------------------------------------- @@ -94,35 +97,34 @@ public class TCKHijrahChronology { public void test_chrono_byName() { Chronology c = HijrahChronology.INSTANCE; Chronology test = Chronology.of("Hijrah-umalqura"); - Assert.assertNotNull(test, "The Hijrah-umalqura calendar could not be found by name"); - Assert.assertEquals(test.getId(), "Hijrah-umalqura", "ID mismatch"); - Assert.assertEquals(test.getCalendarType(), "islamic-umalqura", "Type mismatch"); - Assert.assertEquals(test, c); + Assertions.assertNotNull(test, "The Hijrah-umalqura calendar could not be found by name"); + assertEquals("Hijrah-umalqura", test.getId(), "ID mismatch"); + assertEquals("islamic-umalqura", test.getCalendarType(), "Type mismatch"); + assertEquals(c, test); } // Tests for dateNow() method @Test public void test_dateNow(){ - assertEquals(HijrahChronology.INSTANCE.dateNow(), HijrahDate.now()) ; - assertEquals(HijrahChronology.INSTANCE.dateNow(), HijrahDate.now(ZoneId.systemDefault())) ; - assertEquals(HijrahChronology.INSTANCE.dateNow(), HijrahDate.now(Clock.systemDefaultZone())) ; - assertEquals(HijrahChronology.INSTANCE.dateNow(), HijrahDate.now(Clock.systemDefaultZone().getZone())) ; + assertEquals(HijrahDate.now(), HijrahChronology.INSTANCE.dateNow()) ; + assertEquals(HijrahDate.now(ZoneId.systemDefault()), HijrahChronology.INSTANCE.dateNow()) ; + assertEquals(HijrahDate.now(Clock.systemDefaultZone()), HijrahChronology.INSTANCE.dateNow()) ; + assertEquals(HijrahDate.now(Clock.systemDefaultZone().getZone()), HijrahChronology.INSTANCE.dateNow()) ; - assertEquals(HijrahChronology.INSTANCE.dateNow(), HijrahChronology.INSTANCE.dateNow(ZoneId.systemDefault())) ; - assertEquals(HijrahChronology.INSTANCE.dateNow(), HijrahChronology.INSTANCE.dateNow(Clock.systemDefaultZone())) ; - assertEquals(HijrahChronology.INSTANCE.dateNow(), HijrahChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone())) ; + assertEquals(HijrahChronology.INSTANCE.dateNow(ZoneId.systemDefault()), HijrahChronology.INSTANCE.dateNow()) ; + assertEquals(HijrahChronology.INSTANCE.dateNow(Clock.systemDefaultZone()), HijrahChronology.INSTANCE.dateNow()) ; + assertEquals(HijrahChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone()), HijrahChronology.INSTANCE.dateNow()) ; ZoneId zoneId = ZoneId.of("Europe/Paris"); - assertEquals(HijrahChronology.INSTANCE.dateNow(zoneId), HijrahChronology.INSTANCE.dateNow(Clock.system(zoneId))) ; - assertEquals(HijrahChronology.INSTANCE.dateNow(zoneId), HijrahChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone())) ; - assertEquals(HijrahChronology.INSTANCE.dateNow(zoneId), HijrahDate.now(Clock.system(zoneId))) ; - assertEquals(HijrahChronology.INSTANCE.dateNow(zoneId), HijrahDate.now(Clock.system(zoneId).getZone())) ; + assertEquals(HijrahChronology.INSTANCE.dateNow(Clock.system(zoneId)), HijrahChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(HijrahChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone()), HijrahChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(HijrahDate.now(Clock.system(zoneId)), HijrahChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(HijrahDate.now(Clock.system(zoneId).getZone()), HijrahChronology.INSTANCE.dateNow(zoneId)) ; - assertEquals(HijrahChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId())), HijrahChronology.INSTANCE.dateNow(Clock.systemUTC())) ; + assertEquals(HijrahChronology.INSTANCE.dateNow(Clock.systemUTC()), HijrahChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId()))) ; } // Sample invalid dates - @DataProvider(name="badDates") Object[][] data_badDates() { return new Object[][] { {1299, 12, 29}, @@ -143,17 +145,20 @@ public class TCKHijrahChronology { } // This is a negative test to verify if the API throws exception if an invalid date is provided - @Test(dataProvider="badDates", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_badDates") public void test_badDates(int year, int month, int dom) { - HijrahChronology.INSTANCE.date(year, month, dom); + Assertions.assertThrows(DateTimeException.class, () -> HijrahChronology.INSTANCE.date(year, month, dom)); } // Negative test or dateYearDay with day too large - @Test(expectedExceptions=java.time.DateTimeException.class) + @Test public void test_ofYearDayTooLarge() { - int year = 1435; - int lengthOfYear = HijrahChronology.INSTANCE.dateYearDay(year, 1).lengthOfYear(); - HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(year, lengthOfYear + 1); + Assertions.assertThrows(DateTimeException.class, () -> { + int year = 1435; + int lengthOfYear = HijrahChronology.INSTANCE.dateYearDay(year, 1).lengthOfYear(); + HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(year, lengthOfYear + 1); + }); } //----------------------------------------------------------------------- @@ -198,7 +203,6 @@ public class TCKHijrahChronology { //----------------------------------------------------------------------- // Tests for HijrahChronology resolve //----------------------------------------------------------------------- - @DataProvider(name = "resolve_styleByEra") Object[][] data_resolve_styleByEra() { Object[][] result = new Object[ResolverStyle.values().length * HijrahEra.values().length][]; int i = 0; @@ -210,42 +214,44 @@ public class TCKHijrahChronology { return result; } - @Test(dataProvider = "resolve_styleByEra") + @ParameterizedTest + @MethodSource("data_resolve_styleByEra") public void test_resolve_yearOfEra_eraOnly_valid(ResolverStyle style, HijrahEra era) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.ERA, (long) era.getValue()); HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(ChronoField.ERA), (Long) (long) era.getValue()); - assertEquals(fieldValues.size(), 1); + assertEquals(null, date); + assertEquals((Long) (long) era.getValue(), fieldValues.get(ChronoField.ERA)); + assertEquals(1, fieldValues.size()); } - @Test(dataProvider = "resolve_styleByEra") + @ParameterizedTest + @MethodSource("data_resolve_styleByEra") public void test_resolve_yearOfEra_eraAndYearOfEraOnly_valid(ResolverStyle style, HijrahEra era) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.ERA, (long) era.getValue()); fieldValues.put(ChronoField.YEAR_OF_ERA, 1343L); HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(ChronoField.ERA), null); - assertEquals(fieldValues.get(ChronoField.YEAR_OF_ERA), null); - assertEquals(fieldValues.get(ChronoField.YEAR), (Long) 1343L); - assertEquals(fieldValues.size(), 1); + assertEquals(null, date); + assertEquals(null, fieldValues.get(ChronoField.ERA)); + assertEquals(null, fieldValues.get(ChronoField.YEAR_OF_ERA)); + assertEquals((Long) 1343L, fieldValues.get(ChronoField.YEAR)); + assertEquals(1, fieldValues.size()); } - @Test(dataProvider = "resolve_styleByEra") + @ParameterizedTest + @MethodSource("data_resolve_styleByEra") public void test_resolve_yearOfEra_eraAndYearOnly_valid(ResolverStyle style, HijrahEra era) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.ERA, (long) era.getValue()); fieldValues.put(ChronoField.YEAR, 1343L); HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(ChronoField.ERA), (Long) (long) era.getValue()); - assertEquals(fieldValues.get(ChronoField.YEAR), (Long) 1343L); - assertEquals(fieldValues.size(), 2); + assertEquals(null, date); + assertEquals((Long) (long) era.getValue(), fieldValues.get(ChronoField.ERA)); + assertEquals((Long) 1343L, fieldValues.get(ChronoField.YEAR)); + assertEquals(2, fieldValues.size()); } - @DataProvider(name = "resolve_styles") Object[][] data_resolve_styles() { Object[][] result = new Object[ResolverStyle.values().length][]; int i = 0; @@ -255,27 +261,29 @@ public class TCKHijrahChronology { return result; } - @Test(dataProvider = "resolve_styles") + @ParameterizedTest + @MethodSource("data_resolve_styles") public void test_resolve_yearOfEra_yearOfEraOnly_valid(ResolverStyle style) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR_OF_ERA, 1343L); HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(ChronoField.YEAR_OF_ERA), (style != ResolverStyle.STRICT) ? null : (Long) 1343L); - assertEquals(fieldValues.get(ChronoField.YEAR), (style == ResolverStyle.STRICT) ? null : (Long) 1343L); - assertEquals(fieldValues.size(), 1); + assertEquals(null, date); + assertEquals((style != ResolverStyle.STRICT) ? null : (Long) 1343L, fieldValues.get(ChronoField.YEAR_OF_ERA)); + assertEquals((style == ResolverStyle.STRICT) ? null : (Long) 1343L, fieldValues.get(ChronoField.YEAR)); + assertEquals(1, fieldValues.size()); } - @Test(dataProvider = "resolve_styles") + @ParameterizedTest + @MethodSource("data_resolve_styles") public void test_resolve_yearOfEra_yearOfEraAndYearOnly_valid(ResolverStyle style) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR_OF_ERA, 1343L); fieldValues.put(ChronoField.YEAR, 1343L); HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(ChronoField.YEAR_OF_ERA), null); - assertEquals(fieldValues.get(ChronoField.YEAR), (Long) 1343L); - assertEquals(fieldValues.size(), 1); + assertEquals(null, date); + assertEquals(null, fieldValues.get(ChronoField.YEAR_OF_ERA)); + assertEquals((Long) 1343L, fieldValues.get(ChronoField.YEAR)); + assertEquals(1, fieldValues.size()); } //----------------------------------------------------------------------- @@ -285,7 +293,6 @@ public class TCKHijrahChronology { // 1434=29 30 29 30 29 30 30 29 30 30 29 29 total = 354 // 1435=30 29 30 29 30 29 30 29 30 30 29 30 total = 355 //----------------------------------------------------------------------- - @DataProvider(name = "resolve_ymd") Object[][] data_resolve_ymd() { // Compute the number of days in various month and years so that test cases // are not dependent on specific calendar data @@ -364,7 +371,8 @@ public class TCKHijrahChronology { }; } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_lenient(int y, int m, int d, HijrahDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -373,8 +381,8 @@ public class TCKHijrahChronology { if (expected != null) { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); @@ -385,7 +393,8 @@ public class TCKHijrahChronology { } } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_smart(int y, int m, int d, HijrahDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -393,11 +402,11 @@ public class TCKHijrahChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (Boolean.TRUE.equals(smart)) { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else if (smart instanceof HijrahDate) { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, smart); + assertEquals(smart, date); } else { try { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -408,7 +417,8 @@ public class TCKHijrahChronology { } } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_strict(int y, int m, int d, HijrahDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -416,8 +426,8 @@ public class TCKHijrahChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (strict) { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected, "Resolved to incorrect date"); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date, "Resolved to incorrect date"); + assertEquals(0, fieldValues.size()); } else { try { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); @@ -429,7 +439,6 @@ public class TCKHijrahChronology { } //----------------------------------------------------------------------- - @DataProvider(name = "resolve_yd") Object[][] data_resolve_yd() { // Compute the number of days in various month and years so that test cases // are not dependent on specific calendar data @@ -478,25 +487,27 @@ public class TCKHijrahChronology { }; } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_lenient(int y, int d, HijrahDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_smart(int y, int d, HijrahDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); if (smart) { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -507,15 +518,16 @@ public class TCKHijrahChronology { } } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_strict(int y, int d, HijrahDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); if (strict) { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { HijrahDate date = HijrahChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKHijrahEra.java b/test/jdk/java/time/tck/java/time/chrono/TCKHijrahEra.java index e5a1cd5e1af..0b7a0333b01 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKHijrahEra.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKHijrahEra.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -55,8 +55,9 @@ package tck.java.time.chrono; import static java.time.temporal.ChronoField.ERA; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.chrono.Era; import java.time.chrono.HijrahChronology; @@ -64,29 +65,31 @@ import java.time.chrono.HijrahEra; import java.time.temporal.ValueRange; import java.util.List; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKHijrahEra { - @DataProvider(name = "HijrahEras") Object[][] data_of_eras() { return new Object[][] { {HijrahEra.AH, "AH", 1}, }; } - @Test(dataProvider="HijrahEras") + @ParameterizedTest + @MethodSource("data_of_eras") public void test_valueOf(HijrahEra era , String eraName, int eraValue) { - assertEquals(era.getValue(), eraValue); + assertEquals(eraValue, era.getValue()); - assertEquals(HijrahChronology.INSTANCE.eraOf(eraValue), era); - assertEquals(HijrahEra.of(eraValue), era); - assertEquals(HijrahEra.valueOf(eraName), era); + assertEquals(era, HijrahChronology.INSTANCE.eraOf(eraValue)); + assertEquals(era, HijrahEra.of(eraValue)); + assertEquals(era, HijrahEra.valueOf(eraName)); } //----------------------------------------------------------------------- @@ -96,7 +99,7 @@ public class TCKHijrahEra { public void test_values() { List eraList = HijrahChronology.INSTANCE.eras(); HijrahEra[] eras = HijrahEra.values(); - assertEquals(eraList.size(), eras.length); + assertEquals(eras.length, eraList.size()); for (HijrahEra era : eras) { assertTrue(eraList.contains(era)); } @@ -108,7 +111,7 @@ public class TCKHijrahEra { @Test public void test_range() { for (HijrahEra era : HijrahEra.values()) { - assertEquals(era.range(ERA), ValueRange.of(1, 1)); + assertEquals(ValueRange.of(1, 1), era.range(ERA)); } } diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKIsoChronology.java b/test/jdk/java/time/tck/java/time/chrono/TCKIsoChronology.java index d47c58d72b7..4c4e428ad31 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKIsoChronology.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKIsoChronology.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,8 +54,8 @@ */ package tck.java.time.chrono; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.time.DateTimeException; import java.time.LocalDate; @@ -81,13 +81,16 @@ import java.time.temporal.TemporalQuery; import java.util.HashMap; import java.util.Map; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKIsoChronology { // Can only work with IsoChronology here // others may be in separate module @@ -96,12 +99,12 @@ public class TCKIsoChronology { @Test public void factory_from_TemporalAccessor_dateWithChronlogy() { - assertEquals(Chronology.from(LocalDate.of(2012, 6, 30)), IsoChronology.INSTANCE); + assertEquals(IsoChronology.INSTANCE, Chronology.from(LocalDate.of(2012, 6, 30))); } @Test public void factory_from_TemporalAccessor_chronology() { - assertEquals(Chronology.from(new TemporalAccessor() { + assertEquals(IsoChronology.INSTANCE, Chronology.from(new TemporalAccessor() { @Override public boolean isSupported(TemporalField field) { throw new UnsupportedOperationException(); @@ -120,12 +123,12 @@ public class TCKIsoChronology { } throw new UnsupportedOperationException(); } - }), IsoChronology.INSTANCE); + })); } @Test public void factory_from_TemporalAccessor_noChronology() { - assertEquals(Chronology.from(new TemporalAccessor() { + assertEquals(IsoChronology.INSTANCE, Chronology.from(new TemporalAccessor() { @Override public boolean isSupported(TemporalField field) { throw new UnsupportedOperationException(); @@ -143,18 +146,18 @@ public class TCKIsoChronology { } throw new UnsupportedOperationException(); } - }), IsoChronology.INSTANCE); + })); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_from_TemporalAccessor_null() { - Chronology.from(null); + Assertions.assertThrows(NullPointerException.class, () -> Chronology.from(null)); } //----------------------------------------------------------------------- @Test public void test_date_TemporalAccessor() { - assertEquals(IsoChronology.INSTANCE.date(new TemporalAccessor() { + assertEquals(LocalDate.of(2012, 6, 30), IsoChronology.INSTANCE.date(new TemporalAccessor() { @Override public boolean isSupported(TemporalField field) { if (field == ChronoField.EPOCH_DAY) { @@ -179,18 +182,18 @@ public class TCKIsoChronology { } throw new UnsupportedOperationException(); } - }), LocalDate.of(2012, 6, 30)); + })); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_date_TemporalAccessor_null() { - IsoChronology.INSTANCE.date(null); + Assertions.assertThrows(NullPointerException.class, () -> IsoChronology.INSTANCE.date(null)); } //----------------------------------------------------------------------- @Test public void test_localDateTime_TemporalAccessor() { - assertEquals(IsoChronology.INSTANCE.localDateTime(new TemporalAccessor() { + assertEquals(LocalDateTime.of(2012, 6, 30, 12, 30, 40), IsoChronology.INSTANCE.localDateTime(new TemporalAccessor() { @Override public boolean isSupported(TemporalField field) { if (field == ChronoField.EPOCH_DAY || field == ChronoField.NANO_OF_DAY) { @@ -221,18 +224,18 @@ public class TCKIsoChronology { } throw new UnsupportedOperationException(); } - }), LocalDateTime.of(2012, 6, 30, 12, 30, 40)); + })); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_localDateTime_TemporalAccessor_null() { - IsoChronology.INSTANCE.localDateTime(null); + Assertions.assertThrows(NullPointerException.class, () -> IsoChronology.INSTANCE.localDateTime(null)); } //----------------------------------------------------------------------- @Test public void test_zonedDateTime_TemporalAccessor() { - assertEquals(IsoChronology.INSTANCE.zonedDateTime(new TemporalAccessor() { + assertEquals(ZonedDateTime.of(2012, 6, 30, 12, 30, 40, 0, ZoneId.of("Europe/London")), IsoChronology.INSTANCE.zonedDateTime(new TemporalAccessor() { @Override public boolean isSupported(TemporalField field) { if (field == ChronoField.EPOCH_DAY || field == ChronoField.NANO_OF_DAY || @@ -273,17 +276,16 @@ public class TCKIsoChronology { } throw new UnsupportedOperationException(); } - }), ZonedDateTime.of(2012, 6, 30, 12, 30, 40, 0, ZoneId.of("Europe/London"))); + })); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_zonedDateTime_TemporalAccessor_null() { - IsoChronology.INSTANCE.zonedDateTime(null); + Assertions.assertThrows(NullPointerException.class, () -> IsoChronology.INSTANCE.zonedDateTime(null)); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_yearOfEra") Object[][] data_resolve_yearOfEra() { return new Object[][] { // era only @@ -348,7 +350,8 @@ public class TCKIsoChronology { }; } - @Test(dataProvider = "resolve_yearOfEra") + @ParameterizedTest + @MethodSource("data_resolve_yearOfEra") public void test_resolve_yearOfEra(ResolverStyle style, Integer e, Integer yoe, Integer y, ChronoField field, Integer expected) { Map fieldValues = new HashMap<>(); if (e != null) { @@ -362,9 +365,9 @@ public class TCKIsoChronology { } if (field != null) { LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(field), (Long) expected.longValue()); - assertEquals(fieldValues.size(), 1); + assertEquals(null, date); + assertEquals((Long) expected.longValue(), fieldValues.get(field)); + assertEquals(1, fieldValues.size()); } else { try { IsoChronology.INSTANCE.resolveDate(fieldValues, style); @@ -377,7 +380,6 @@ public class TCKIsoChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_ymd") Object[][] data_resolve_ymd() { return new Object[][] { {2012, 1, -365, date(2010, 12, 31), false, false}, @@ -436,18 +438,20 @@ public class TCKIsoChronology { }; } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_lenient(int y, int m, int d, LocalDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.MONTH_OF_YEAR, (long) m); fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_smart(int y, int m, int d, LocalDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -455,11 +459,11 @@ public class TCKIsoChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (Boolean.TRUE.equals(smart)) { LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else if (smart instanceof LocalDate) { LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, smart); + assertEquals(smart, date); } else { try { IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -470,7 +474,8 @@ public class TCKIsoChronology { } } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_strict(int y, int m, int d, LocalDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -478,8 +483,8 @@ public class TCKIsoChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (strict) { LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); @@ -492,7 +497,6 @@ public class TCKIsoChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_yd") Object[][] data_resolve_yd() { return new Object[][] { {2012, -365, date(2010, 12, 31), false, false}, @@ -520,25 +524,27 @@ public class TCKIsoChronology { }; } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_lenient(int y, int d, LocalDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_smart(int y, int d, LocalDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); if (smart) { LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -549,15 +555,16 @@ public class TCKIsoChronology { } } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_strict(int y, int d, LocalDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); if (strict) { LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); @@ -570,7 +577,6 @@ public class TCKIsoChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_ymaa") Object[][] data_resolve_ymaa() { return new Object[][] { {2012, 1, 1, -365, date(2010, 12, 31), false, false}, @@ -627,7 +633,8 @@ public class TCKIsoChronology { }; } - @Test(dataProvider = "resolve_ymaa") + @ParameterizedTest + @MethodSource("data_resolve_ymaa") public void test_resolve_ymaa_lenient(int y, int m, int w, int d, LocalDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -635,11 +642,12 @@ public class TCKIsoChronology { fieldValues.put(ChronoField.ALIGNED_WEEK_OF_MONTH, (long) w); fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d); LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_ymaa") + @ParameterizedTest + @MethodSource("data_resolve_ymaa") public void test_resolve_ymaa_smart(int y, int m, int w, int d, LocalDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -648,8 +656,8 @@ public class TCKIsoChronology { fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d); if (smart) { LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -660,7 +668,8 @@ public class TCKIsoChronology { } } - @Test(dataProvider = "resolve_ymaa") + @ParameterizedTest + @MethodSource("data_resolve_ymaa") public void test_resolve_ymaa_strict(int y, int m, int w, int d, LocalDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -669,8 +678,8 @@ public class TCKIsoChronology { fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d); if (strict) { LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); @@ -681,7 +690,6 @@ public class TCKIsoChronology { } } - @DataProvider(name = "epochSecond_dataProvider") Object[][] data_epochSecond() { return new Object[][] { {2008, 3, 3, 1, 2, 2, OFFSET_P0100}, @@ -703,33 +711,28 @@ public class TCKIsoChronology { }; } - @Test(dataProvider = "epochSecond_dataProvider") + @ParameterizedTest + @MethodSource("data_epochSecond") public void test_epochSecond_1(int y, int m, int d, int h , int min, int s, ZoneOffset offset) { - assertEquals(IsoChronology.INSTANCE.epochSecond(y, m, d, h, min, s, offset), - OffsetDateTime.of(y, m, d, h, min, s, 0, offset).toEpochSecond()); + assertEquals(OffsetDateTime.of(y, m, d, h, min, s, 0, offset).toEpochSecond(), IsoChronology.INSTANCE.epochSecond(y, m, d, h, min, s, offset)); } @Test public void test_epochSecond_2() { - assertEquals(IsoChronology.INSTANCE.epochSecond(2008, 3, 3, 1, 2, 2, OFFSET_P0100), - ZonedDateTime.of(2008, 3, 3, 1, 2, 2, 0, ZoneId.of("+01:00")).toEpochSecond()); - assertEquals(IsoChronology.INSTANCE.epochSecond(1969, 3, 3, 1, 2, 2, OFFSET_P0100), - ZonedDateTime.of(1969, 3, 3, 1, 2, 2, 0, ZoneId.of("+01:00")).toEpochSecond()); + assertEquals(ZonedDateTime.of(2008, 3, 3, 1, 2, 2, 0, ZoneId.of("+01:00")).toEpochSecond(), IsoChronology.INSTANCE.epochSecond(2008, 3, 3, 1, 2, 2, OFFSET_P0100)); + assertEquals(ZonedDateTime.of(1969, 3, 3, 1, 2, 2, 0, ZoneId.of("+01:00")).toEpochSecond(), IsoChronology.INSTANCE.epochSecond(1969, 3, 3, 1, 2, 2, OFFSET_P0100)); } @Test public void test_epochSecond_max() { - assertEquals(IsoChronology.INSTANCE.epochSecond(Year.MAX_VALUE, 12, 31, 23, 59, 59, ZoneOffset.MIN), - OffsetDateTime.of(Year.MAX_VALUE, 12, 31, 23, 59, 59, 0, ZoneOffset.MIN).toEpochSecond()); + assertEquals(OffsetDateTime.of(Year.MAX_VALUE, 12, 31, 23, 59, 59, 0, ZoneOffset.MIN).toEpochSecond(), IsoChronology.INSTANCE.epochSecond(Year.MAX_VALUE, 12, 31, 23, 59, 59, ZoneOffset.MIN)); } @Test public void test_epochSecond_min() { - assertEquals(IsoChronology.INSTANCE.epochSecond(Year.MIN_VALUE, 1, 1, 0, 0, 0, ZoneOffset.MAX), - OffsetDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0, 0, 0, ZoneOffset.MAX).toEpochSecond()); + assertEquals(OffsetDateTime.of(Year.MIN_VALUE, 1, 1, 0, 0, 0, 0, ZoneOffset.MAX).toEpochSecond(), IsoChronology.INSTANCE.epochSecond(Year.MIN_VALUE, 1, 1, 0, 0, 0, ZoneOffset.MAX)); } - @DataProvider(name = "bad_epochSecond_dataProvider") Object[][] bad_data_epochSecond() { return new Object[][] { {2009, 13, 1, 1, 1, 1, OFFSET_P0100}, @@ -739,12 +742,12 @@ public class TCKIsoChronology { {2009, 1, 1, 1, 1, -11, OFFSET_P0100}, }; } - @Test(dataProvider = "bad_epochSecond_dataProvider", expectedExceptions = DateTimeException.class) + @ParameterizedTest + @MethodSource("bad_data_epochSecond") public void test_epochSecond_bad(int y, int m, int d, int h , int min, int s, ZoneOffset offset) { - IsoChronology.INSTANCE.epochSecond(y, m, d, h, min, s, offset); + Assertions.assertThrows(DateTimeException.class, () -> IsoChronology.INSTANCE.epochSecond(y, m, d, h, min, s, offset)); } - @DataProvider(name = "era_epochSecond_dataProvider") Object[][] data_era_epochSecond() { return new Object[][] { {IsoEra.CE, 2008, 3, 3, 1, 2, 2, OFFSET_P0100}, @@ -766,24 +769,22 @@ public class TCKIsoChronology { }; } - @Test(dataProvider = "era_epochSecond_dataProvider") + @ParameterizedTest + @MethodSource("data_era_epochSecond") public void test_era_epochSecond_1(Era era, int y, int m, int d, int h , int min, int s, ZoneOffset offset) { - assertEquals(IsoChronology.INSTANCE.epochSecond(era, y, m, d, h, min, s, offset), - OffsetDateTime.of(IsoChronology.INSTANCE.date(era, y, m, d), LocalTime.of(h, min, s), offset) - .toEpochSecond()); + assertEquals(OffsetDateTime.of(IsoChronology.INSTANCE.date(era, y, m, d), LocalTime.of(h, min, s), offset) + .toEpochSecond(), IsoChronology.INSTANCE.epochSecond(era, y, m, d, h, min, s, offset)); } @Test public void test_era_epochSecond_2() { - assertEquals(IsoChronology.INSTANCE.epochSecond(IsoEra.CE, 2008, 3, 3, 1, 2, 2, OFFSET_P0100), - ZonedDateTime.of(2008, 3, 3, 1, 2, 2, 0, ZoneId.of("+01:00")).toEpochSecond()); - assertEquals(IsoChronology.INSTANCE.epochSecond(IsoEra.CE, 1969, 3, 3, 1, 2, 2, OFFSET_P0100), - ZonedDateTime.of(1969, 3, 3, 1, 2, 2, 0, ZoneId.of("+01:00")).toEpochSecond()); + assertEquals(ZonedDateTime.of(2008, 3, 3, 1, 2, 2, 0, ZoneId.of("+01:00")).toEpochSecond(), IsoChronology.INSTANCE.epochSecond(IsoEra.CE, 2008, 3, 3, 1, 2, 2, OFFSET_P0100)); + assertEquals(ZonedDateTime.of(1969, 3, 3, 1, 2, 2, 0, ZoneId.of("+01:00")).toEpochSecond(), IsoChronology.INSTANCE.epochSecond(IsoEra.CE, 1969, 3, 3, 1, 2, 2, OFFSET_P0100)); } - @Test(expectedExceptions = ClassCastException.class) + @Test public void test_era_epochSecond_bad() { - IsoChronology.INSTANCE.epochSecond(HijrahEra.AH, 2009, 2, 29, 1, 2, 2, OFFSET_P0100); + Assertions.assertThrows(ClassCastException.class, () -> IsoChronology.INSTANCE.epochSecond(HijrahEra.AH, 2009, 2, 29, 1, 2, 2, OFFSET_P0100)); } diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKIsoEra.java b/test/jdk/java/time/tck/java/time/chrono/TCKIsoEra.java index 223a5a2b92f..0bb08453303 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKIsoEra.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKIsoEra.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -55,8 +55,9 @@ package tck.java.time.chrono; import static java.time.temporal.ChronoField.ERA; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.chrono.Era; import java.time.chrono.IsoChronology; @@ -64,16 +65,17 @@ import java.time.chrono.IsoEra; import java.time.temporal.ValueRange; import java.util.List; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKIsoEra { - @DataProvider(name = "IsoEras") Object[][] data_of_eras() { return new Object[][] { {IsoEra.BCE, "BCE", 0}, @@ -81,11 +83,12 @@ public class TCKIsoEra { }; } - @Test(dataProvider="IsoEras") + @ParameterizedTest + @MethodSource("data_of_eras") public void test_valueOf(IsoEra era , String eraName, int eraValue) { - assertEquals(era.getValue(), eraValue); - assertEquals(IsoEra.of(eraValue), era); - assertEquals(IsoEra.valueOf(eraName), era); + assertEquals(eraValue, era.getValue()); + assertEquals(era, IsoEra.of(eraValue)); + assertEquals(era, IsoEra.valueOf(eraName)); } //----------------------------------------------------------------------- @@ -95,7 +98,7 @@ public class TCKIsoEra { public void test_values() { List eraList = IsoChronology.INSTANCE.eras(); IsoEra[] eras = IsoEra.values(); - assertEquals(eraList.size(), eras.length); + assertEquals(eras.length, eraList.size()); for (IsoEra era : eras) { assertTrue(eraList.contains(era)); } @@ -107,7 +110,7 @@ public class TCKIsoEra { @Test public void test_range() { for (IsoEra era : IsoEra.values()) { - assertEquals(era.range(ERA), ValueRange.of(0, 1)); + assertEquals(ValueRange.of(0, 1), era.range(ERA)); } } diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKJapaneseChronology.java b/test/jdk/java/time/tck/java/time/chrono/TCKJapaneseChronology.java index 19bb26ed40f..6847d89b1a0 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKJapaneseChronology.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKJapaneseChronology.java @@ -1,5 +1,5 @@ /* - o Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + o Copyright (c) 2012, 2025, 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 @@ -61,18 +61,17 @@ import static java.time.temporal.ChronoField.ERA; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoField.YEAR_OF_ERA; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.Clock; import java.time.DateTimeException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; -import java.time.Period; import java.time.Year; import java.time.ZoneId; import java.time.ZoneOffset; @@ -86,7 +85,6 @@ import java.time.chrono.JapaneseDate; import java.time.chrono.JapaneseEra; import java.time.chrono.MinguoChronology; import java.time.chrono.MinguoDate; -import java.time.chrono.ThaiBuddhistChronology; import java.time.format.ResolverStyle; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; @@ -100,14 +98,16 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKJapaneseChronology { // Year differences from Gregorian years. @@ -124,10 +124,10 @@ public class TCKJapaneseChronology { public void test_chrono_byName() { Chronology c = JapaneseChronology.INSTANCE; Chronology test = Chronology.of("Japanese"); - Assert.assertNotNull(test, "The Japanese calendar could not be found byName"); - Assert.assertEquals(test.getId(), "Japanese", "ID mismatch"); - Assert.assertEquals(test.getCalendarType(), "japanese", "Type mismatch"); - Assert.assertEquals(test, c); + Assertions.assertNotNull(test, "The Japanese calendar could not be found byName"); + assertEquals("Japanese", test.getId(), "ID mismatch"); + assertEquals("japanese", test.getCalendarType(), "Type mismatch"); + assertEquals(c, test); } //----------------------------------------------------------------------- @@ -136,42 +136,41 @@ public class TCKJapaneseChronology { @Test public void test_chrono_byLocale_fullTag_japaneseCalendarFromJapan() { Chronology test = Chronology.ofLocale(Locale.forLanguageTag("ja-JP-u-ca-japanese")); - Assert.assertEquals(test.getId(), "Japanese"); - Assert.assertEquals(test, JapaneseChronology.INSTANCE); + assertEquals("Japanese", test.getId()); + assertEquals(JapaneseChronology.INSTANCE, test); } @Test public void test_chrono_byLocale_fullTag_japaneseCalendarFromElsewhere() { Chronology test = Chronology.ofLocale(Locale.forLanguageTag("en-US-u-ca-japanese")); - Assert.assertEquals(test.getId(), "Japanese"); - Assert.assertEquals(test, JapaneseChronology.INSTANCE); + assertEquals("Japanese", test.getId()); + assertEquals(JapaneseChronology.INSTANCE, test); } @Test public void test_chrono_byLocale_oldJP_noVariant() { Chronology test = Chronology.ofLocale(Locale.JAPAN); - Assert.assertEquals(test.getId(), "ISO"); - Assert.assertEquals(test, IsoChronology.INSTANCE); + assertEquals("ISO", test.getId()); + assertEquals(IsoChronology.INSTANCE, test); } @Test public void test_chrono_byLocale_oldJP_variant() { Chronology test = Chronology.ofLocale(Locale.of("ja", "JP", "JP")); - Assert.assertEquals(test.getId(), "Japanese"); - Assert.assertEquals(test, JapaneseChronology.INSTANCE); + assertEquals("Japanese", test.getId()); + assertEquals(JapaneseChronology.INSTANCE, test); } @Test public void test_chrono_byLocale_iso() { - Assert.assertEquals(Chronology.ofLocale(Locale.JAPAN).getId(), "ISO"); - Assert.assertEquals(Chronology.ofLocale(Locale.forLanguageTag("ja-JP")).getId(), "ISO"); - Assert.assertEquals(Chronology.ofLocale(Locale.forLanguageTag("ja-JP-JP")).getId(), "ISO"); + assertEquals("ISO", Chronology.ofLocale(Locale.JAPAN).getId()); + assertEquals("ISO", Chronology.ofLocale(Locale.forLanguageTag("ja-JP")).getId()); + assertEquals("ISO", Chronology.ofLocale(Locale.forLanguageTag("ja-JP-JP")).getId()); } //----------------------------------------------------------------------- // creation and cross-checks //----------------------------------------------------------------------- - @DataProvider(name="createByEra") Object[][] data_createByEra() { return new Object[][] { {JapaneseEra.REIWA, 2020 - YDIFF_REIWA, 2, 29, 60, LocalDate.of(2020, 2, 29)}, @@ -190,58 +189,64 @@ public class TCKJapaneseChronology { }; } - @Test(dataProvider="createByEra") + @ParameterizedTest + @MethodSource("data_createByEra") public void test_createEymd(JapaneseEra era, int yoe, int moy, int dom, int doy, LocalDate iso) { JapaneseDate dateByChronoFactory = JapaneseChronology.INSTANCE.date(era, yoe, moy, dom); JapaneseDate dateByDateFactory = JapaneseDate.of(era, yoe, moy, dom); - assertEquals(dateByChronoFactory, dateByDateFactory); - assertEquals(dateByChronoFactory.hashCode(), dateByDateFactory.hashCode()); + assertEquals(dateByDateFactory, dateByChronoFactory); + assertEquals(dateByDateFactory.hashCode(), dateByChronoFactory.hashCode()); } - @Test(dataProvider="createByEra") + @ParameterizedTest + @MethodSource("data_createByEra") public void test_createEyd(JapaneseEra era, int yoe, int moy, int dom, int doy, LocalDate iso) { JapaneseDate dateByChronoFactory = JapaneseChronology.INSTANCE.dateYearDay(era, yoe, doy); JapaneseDate dateByDateFactory = JapaneseDate.of(era, yoe, moy, dom); - assertEquals(dateByChronoFactory, dateByDateFactory); - assertEquals(dateByChronoFactory.hashCode(), dateByDateFactory.hashCode()); + assertEquals(dateByDateFactory, dateByChronoFactory); + assertEquals(dateByDateFactory.hashCode(), dateByChronoFactory.hashCode()); } - @Test(dataProvider="createByEra") + @ParameterizedTest + @MethodSource("data_createByEra") public void test_createByEra_isEqual(JapaneseEra era, int yoe, int moy, int dom, int doy, LocalDate iso) { JapaneseDate test = JapaneseDate.of(era, yoe, moy, dom); - assertEquals(test.isEqual(iso), true); - assertEquals(iso.isEqual(test), true); + assertEquals(true, test.isEqual(iso)); + assertEquals(true, iso.isEqual(test)); } - @Test(dataProvider="createByEra") + @ParameterizedTest + @MethodSource("data_createByEra") public void test_createByEra_chronologyTemporalFactory(JapaneseEra era, int yoe, int moy, int dom, int doy, LocalDate iso) { JapaneseDate test = JapaneseDate.of(era, yoe, moy, dom); - assertEquals(IsoChronology.INSTANCE.date(test), iso); - assertEquals(JapaneseChronology.INSTANCE.date(iso), test); + assertEquals(iso, IsoChronology.INSTANCE.date(test)); + assertEquals(test, JapaneseChronology.INSTANCE.date(iso)); } - @Test(dataProvider="createByEra") + @ParameterizedTest + @MethodSource("data_createByEra") public void test_createByEra_dateFrom(JapaneseEra era, int yoe, int moy, int dom, int doy, LocalDate iso) { JapaneseDate test = JapaneseDate.of(era, yoe, moy, dom); - assertEquals(LocalDate.from(test), iso); - assertEquals(JapaneseDate.from(iso), test); + assertEquals(iso, LocalDate.from(test)); + assertEquals(test, JapaneseDate.from(iso)); } - @Test(dataProvider="createByEra") + @ParameterizedTest + @MethodSource("data_createByEra") public void test_createByEra_query(JapaneseEra era, int yoe, int moy, int dom, int doy, LocalDate iso) { JapaneseDate test = JapaneseDate.of(era, yoe, moy, dom); - assertEquals(test.query(TemporalQueries.localDate()), iso); + assertEquals(iso, test.query(TemporalQueries.localDate())); } - @Test(dataProvider="createByEra") + @ParameterizedTest + @MethodSource("data_createByEra") public void test_createByEra_epochDay(JapaneseEra era, int yoe, int moy, int dom, int doy, LocalDate iso) { JapaneseDate test = JapaneseDate.of(era, yoe, moy, dom); - assertEquals(test.getLong(EPOCH_DAY), iso.getLong(EPOCH_DAY)); - assertEquals(test.toEpochDay(), iso.toEpochDay()); + assertEquals(iso.getLong(EPOCH_DAY), test.getLong(EPOCH_DAY)); + assertEquals(iso.toEpochDay(), test.toEpochDay()); } //----------------------------------------------------------------------- - @DataProvider(name="createByProleptic") Object[][] data_createByProleptic() { return new Object[][] { {1928, 2, 28, 59, LocalDate.of(1928, 2, 28)}, @@ -258,79 +263,85 @@ public class TCKJapaneseChronology { }; } - @Test(dataProvider="createByProleptic") + @ParameterizedTest + @MethodSource("data_createByProleptic") public void test_createYmd(int y, int moy, int dom, int doy, LocalDate iso) { JapaneseDate dateByChronoFactory = JapaneseChronology.INSTANCE.date(y, moy, dom); JapaneseDate dateByDateFactory = JapaneseDate.of(y, moy, dom); - assertEquals(dateByChronoFactory, dateByDateFactory); - assertEquals(dateByChronoFactory.hashCode(), dateByDateFactory.hashCode()); + assertEquals(dateByDateFactory, dateByChronoFactory); + assertEquals(dateByDateFactory.hashCode(), dateByChronoFactory.hashCode()); } - @Test(dataProvider="createByProleptic") + @ParameterizedTest + @MethodSource("data_createByProleptic") public void test_createYd(int y, int moy, int dom, int doy, LocalDate iso) { JapaneseDate dateByChronoFactory = JapaneseChronology.INSTANCE.dateYearDay(y, doy); JapaneseDate dateByDateFactory = JapaneseDate.of(y, moy, dom); - assertEquals(dateByChronoFactory, dateByDateFactory); - assertEquals(dateByChronoFactory.hashCode(), dateByDateFactory.hashCode()); + assertEquals(dateByDateFactory, dateByChronoFactory); + assertEquals(dateByDateFactory.hashCode(), dateByChronoFactory.hashCode()); } - @Test(dataProvider="createByProleptic") + @ParameterizedTest + @MethodSource("data_createByProleptic") public void test_createByProleptic_isEqual(int y, int moy, int dom, int doy, LocalDate iso) { JapaneseDate test = JapaneseDate.of(y, moy, dom); - assertEquals(test.isEqual(iso), true); - assertEquals(iso.isEqual(test), true); + assertEquals(true, test.isEqual(iso)); + assertEquals(true, iso.isEqual(test)); } - @Test(dataProvider="createByProleptic") + @ParameterizedTest + @MethodSource("data_createByProleptic") public void test_createByProleptic_chronologyTemporalFactory(int y, int moy, int dom, int doy, LocalDate iso) { JapaneseDate test = JapaneseDate.of(y, moy, dom); - assertEquals(IsoChronology.INSTANCE.date(test), iso); - assertEquals(JapaneseChronology.INSTANCE.date(iso), test); + assertEquals(iso, IsoChronology.INSTANCE.date(test)); + assertEquals(test, JapaneseChronology.INSTANCE.date(iso)); } - @Test(dataProvider="createByProleptic") + @ParameterizedTest + @MethodSource("data_createByProleptic") public void test_createByProleptic_dateFrom(int y, int moy, int dom, int doy, LocalDate iso) { JapaneseDate test = JapaneseDate.of(y, moy, dom); - assertEquals(LocalDate.from(test), iso); - assertEquals(JapaneseDate.from(iso), test); + assertEquals(iso, LocalDate.from(test)); + assertEquals(test, JapaneseDate.from(iso)); } - @Test(dataProvider="createByProleptic") + @ParameterizedTest + @MethodSource("data_createByProleptic") public void test_createByProleptic_query(int y, int moy, int dom, int doy, LocalDate iso) { JapaneseDate test = JapaneseDate.of(y, moy, dom); - assertEquals(test.query(TemporalQueries.localDate()), iso); + assertEquals(iso, test.query(TemporalQueries.localDate())); } - @Test(dataProvider="createByProleptic") + @ParameterizedTest + @MethodSource("data_createByProleptic") public void test_createByProleptic_epochDay(int y, int moy, int dom, int doy, LocalDate iso) { JapaneseDate test = JapaneseDate.of(y, moy, dom); - assertEquals(test.getLong(EPOCH_DAY), iso.getLong(EPOCH_DAY)); - assertEquals(test.toEpochDay(), iso.toEpochDay()); + assertEquals(iso.getLong(EPOCH_DAY), test.getLong(EPOCH_DAY)); + assertEquals(iso.toEpochDay(), test.toEpochDay()); } //----------------------------------------------------------------------- @Test public void test_dateNow(){ - assertEquals(JapaneseChronology.INSTANCE.dateNow(), JapaneseDate.now()) ; - assertEquals(JapaneseChronology.INSTANCE.dateNow(), JapaneseDate.now(ZoneId.systemDefault())) ; - assertEquals(JapaneseChronology.INSTANCE.dateNow(), JapaneseDate.now(Clock.systemDefaultZone())) ; - assertEquals(JapaneseChronology.INSTANCE.dateNow(), JapaneseDate.now(Clock.systemDefaultZone().getZone())) ; + assertEquals(JapaneseDate.now(), JapaneseChronology.INSTANCE.dateNow()) ; + assertEquals(JapaneseDate.now(ZoneId.systemDefault()), JapaneseChronology.INSTANCE.dateNow()) ; + assertEquals(JapaneseDate.now(Clock.systemDefaultZone()), JapaneseChronology.INSTANCE.dateNow()) ; + assertEquals(JapaneseDate.now(Clock.systemDefaultZone().getZone()), JapaneseChronology.INSTANCE.dateNow()) ; - assertEquals(JapaneseChronology.INSTANCE.dateNow(), JapaneseChronology.INSTANCE.dateNow(ZoneId.systemDefault())) ; - assertEquals(JapaneseChronology.INSTANCE.dateNow(), JapaneseChronology.INSTANCE.dateNow(Clock.systemDefaultZone())) ; - assertEquals(JapaneseChronology.INSTANCE.dateNow(), JapaneseChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone())) ; + assertEquals(JapaneseChronology.INSTANCE.dateNow(ZoneId.systemDefault()), JapaneseChronology.INSTANCE.dateNow()) ; + assertEquals(JapaneseChronology.INSTANCE.dateNow(Clock.systemDefaultZone()), JapaneseChronology.INSTANCE.dateNow()) ; + assertEquals(JapaneseChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone()), JapaneseChronology.INSTANCE.dateNow()) ; ZoneId zoneId = ZoneId.of("Europe/Paris"); - assertEquals(JapaneseChronology.INSTANCE.dateNow(zoneId), JapaneseChronology.INSTANCE.dateNow(Clock.system(zoneId))) ; - assertEquals(JapaneseChronology.INSTANCE.dateNow(zoneId), JapaneseChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone())) ; - assertEquals(JapaneseChronology.INSTANCE.dateNow(zoneId), JapaneseDate.now(Clock.system(zoneId))) ; - assertEquals(JapaneseChronology.INSTANCE.dateNow(zoneId), JapaneseDate.now(Clock.system(zoneId).getZone())) ; + assertEquals(JapaneseChronology.INSTANCE.dateNow(Clock.system(zoneId)), JapaneseChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(JapaneseChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone()), JapaneseChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(JapaneseDate.now(Clock.system(zoneId)), JapaneseChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(JapaneseDate.now(Clock.system(zoneId).getZone()), JapaneseChronology.INSTANCE.dateNow(zoneId)) ; - assertEquals(JapaneseChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId())), JapaneseChronology.INSTANCE.dateNow(Clock.systemUTC())) ; + assertEquals(JapaneseChronology.INSTANCE.dateNow(Clock.systemUTC()), JapaneseChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId()))) ; } //----------------------------------------------------------------------- - @DataProvider(name="badDates") Object[][] data_badDates() { return new Object[][] { {1928, 0, 0}, @@ -356,15 +367,15 @@ public class TCKJapaneseChronology { }; } - @Test(dataProvider="badDates", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_badDates") public void test_badDates(int year, int month, int dom) { - JapaneseChronology.INSTANCE.date(year, month, dom); + Assertions.assertThrows(DateTimeException.class, () -> JapaneseChronology.INSTANCE.date(year, month, dom)); } //----------------------------------------------------------------------- // prolepticYear() and is LeapYear() //----------------------------------------------------------------------- - @DataProvider(name="prolepticYear") Object[][] data_prolepticYear() { return new Object[][] { {3, JapaneseEra.REIWA, 1, 1 + YDIFF_REIWA, false}, @@ -384,29 +395,30 @@ public class TCKJapaneseChronology { }; } - @Test(dataProvider="prolepticYear") + @ParameterizedTest + @MethodSource("data_prolepticYear") public void test_prolepticYear(int eraValue, Era era, int yearOfEra, int expectedProlepticYear, boolean isLeapYear) { Era eraObj = JapaneseChronology.INSTANCE.eraOf(eraValue); assertTrue(JapaneseChronology.INSTANCE.eras().contains(eraObj)); - assertEquals(eraObj, era); - assertEquals(JapaneseChronology.INSTANCE.prolepticYear(era, yearOfEra), expectedProlepticYear); + assertEquals(era, eraObj); + assertEquals(expectedProlepticYear, JapaneseChronology.INSTANCE.prolepticYear(era, yearOfEra)); } - @Test(dataProvider="prolepticYear") + @ParameterizedTest + @MethodSource("data_prolepticYear") public void test_isLeapYear(int eraValue, Era era, int yearOfEra, int expectedProlepticYear, boolean isLeapYear) { - assertEquals(JapaneseChronology.INSTANCE.isLeapYear(expectedProlepticYear), isLeapYear); - assertEquals(JapaneseChronology.INSTANCE.isLeapYear(expectedProlepticYear), Year.of(expectedProlepticYear).isLeap()); + assertEquals(isLeapYear, JapaneseChronology.INSTANCE.isLeapYear(expectedProlepticYear)); + assertEquals(Year.of(expectedProlepticYear).isLeap(), JapaneseChronology.INSTANCE.isLeapYear(expectedProlepticYear)); JapaneseDate jdate = JapaneseDate.now(); jdate = jdate.with(ChronoField.YEAR, expectedProlepticYear).with(ChronoField.MONTH_OF_YEAR, 2); if (isLeapYear) { - assertEquals(jdate.lengthOfMonth(), 29); + assertEquals(29, jdate.lengthOfMonth()); } else { - assertEquals(jdate.lengthOfMonth(), 28); + assertEquals(28, jdate.lengthOfMonth()); } } - @DataProvider(name="prolepticYearError") Object[][] data_prolepticYearError() { return new Object[][] { {JapaneseEra.MEIJI, 100}, @@ -423,9 +435,10 @@ public class TCKJapaneseChronology { }; } - @Test(dataProvider="prolepticYearError", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_prolepticYearError") public void test_prolepticYearError(Era era, int yearOfEra) { - JapaneseChronology.INSTANCE.prolepticYear(era, yearOfEra); + Assertions.assertThrows(DateTimeException.class, () -> JapaneseChronology.INSTANCE.prolepticYear(era, yearOfEra)); } //----------------------------------------------------------------------- @@ -464,11 +477,11 @@ public class TCKJapaneseChronology { @Test public void test_getLong() { JapaneseDate base = JapaneseChronology.INSTANCE.date(JapaneseEra.SHOWA, 63, 6, 30); - assertEquals(base.getLong(ERA), JapaneseEra.SHOWA.getValue()); - assertEquals(base.getLong(YEAR), 1988L); - assertEquals(base.getLong(YEAR_OF_ERA), 63L); - assertEquals(base.getLong(MONTH_OF_YEAR), 6L); - assertEquals(base.getLong(DAY_OF_MONTH), 30L); + assertEquals(JapaneseEra.SHOWA.getValue(), base.getLong(ERA)); + assertEquals(1988L, base.getLong(YEAR)); + assertEquals(63L, base.getLong(YEAR_OF_ERA)); + assertEquals(6L, base.getLong(MONTH_OF_YEAR)); + assertEquals(30L, base.getLong(DAY_OF_MONTH)); } //----------------------------------------------------------------------- @@ -478,19 +491,19 @@ public class TCKJapaneseChronology { public void test_with_TemporalField_long() { JapaneseDate base = JapaneseChronology.INSTANCE.date(JapaneseEra.SHOWA, 63, 6, 30); JapaneseDate test = base.with(YEAR, 1987); - assertEquals(test, JapaneseChronology.INSTANCE.date(JapaneseEra.SHOWA, 62, 6, 30)); + assertEquals(JapaneseChronology.INSTANCE.date(JapaneseEra.SHOWA, 62, 6, 30), test); test = test.with(YEAR_OF_ERA, 2); - assertEquals(test, JapaneseChronology.INSTANCE.date(JapaneseEra.SHOWA, 2, 6, 30)); + assertEquals(JapaneseChronology.INSTANCE.date(JapaneseEra.SHOWA, 2, 6, 30), test); test = test.with(ERA, JapaneseEra.HEISEI.getValue()); - assertEquals(test, JapaneseChronology.INSTANCE.date(JapaneseEra.HEISEI, 2, 6, 30)); + assertEquals(JapaneseChronology.INSTANCE.date(JapaneseEra.HEISEI, 2, 6, 30), test); test = test.with(MONTH_OF_YEAR, 3); - assertEquals(test, JapaneseChronology.INSTANCE.date(JapaneseEra.HEISEI, 2, 3, 30)); + assertEquals(JapaneseChronology.INSTANCE.date(JapaneseEra.HEISEI, 2, 3, 30), test); test = test.with(DAY_OF_MONTH, 4); - assertEquals(test, JapaneseChronology.INSTANCE.date(JapaneseEra.HEISEI, 2, 3, 4)); + assertEquals(JapaneseChronology.INSTANCE.date(JapaneseEra.HEISEI, 2, 3, 4), test); } //----------------------------------------------------------------------- @@ -500,14 +513,14 @@ public class TCKJapaneseChronology { public void test_adjust1() { JapaneseDate base = JapaneseChronology.INSTANCE.date(1928, 10, 29); JapaneseDate test = base.with(TemporalAdjusters.lastDayOfMonth()); - assertEquals(test, JapaneseChronology.INSTANCE.date(1928, 10, 31)); + assertEquals(JapaneseChronology.INSTANCE.date(1928, 10, 31), test); } @Test public void test_adjust2() { JapaneseDate base = JapaneseChronology.INSTANCE.date(1928, 12, 2); JapaneseDate test = base.with(TemporalAdjusters.lastDayOfMonth()); - assertEquals(test, JapaneseChronology.INSTANCE.date(1928, 12, 31)); + assertEquals(JapaneseChronology.INSTANCE.date(1928, 12, 31), test); } //----------------------------------------------------------------------- @@ -517,13 +530,15 @@ public class TCKJapaneseChronology { public void test_adjust_toLocalDate() { JapaneseDate jdate = JapaneseChronology.INSTANCE.date(1926, 1, 4); JapaneseDate test = jdate.with(LocalDate.of(2012, 7, 6)); - assertEquals(test, JapaneseChronology.INSTANCE.date(2012, 7, 6)); + assertEquals(JapaneseChronology.INSTANCE.date(2012, 7, 6), test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_adjust_toMonth() { - JapaneseDate jdate = JapaneseChronology.INSTANCE.date(1926, 1, 4); - jdate.with(Month.APRIL); + Assertions.assertThrows(DateTimeException.class, () -> { + JapaneseDate jdate = JapaneseChronology.INSTANCE.date(1926, 1, 4); + jdate.with(Month.APRIL); + }); } //----------------------------------------------------------------------- @@ -533,20 +548,19 @@ public class TCKJapaneseChronology { public void test_LocalDate_adjustToJapaneseDate() { JapaneseDate jdate = JapaneseChronology.INSTANCE.date(1928, 10, 29); LocalDate test = LocalDate.MIN.with(jdate); - assertEquals(test, LocalDate.of(1928, 10, 29)); + assertEquals(LocalDate.of(1928, 10, 29), test); } @Test public void test_LocalDateTime_adjustToJapaneseDate() { JapaneseDate jdate = JapaneseChronology.INSTANCE.date(1928, 10, 29); LocalDateTime test = LocalDateTime.MIN.with(jdate); - assertEquals(test, LocalDateTime.of(1928, 10, 29, 0, 0)); + assertEquals(LocalDateTime.of(1928, 10, 29, 0, 0), test); } //----------------------------------------------------------------------- // Check Japanese Eras //----------------------------------------------------------------------- - @DataProvider(name="japaneseEras") Object[][] data_japanseseEras() { return new Object[][] { { JapaneseEra.MEIJI, -1, "Meiji"}, @@ -557,11 +571,12 @@ public class TCKJapaneseChronology { }; } - @Test(dataProvider="japaneseEras") + @ParameterizedTest + @MethodSource("data_japanseseEras") public void test_Japanese_Eras(Era era, int eraValue, String name) { - assertEquals(era.getValue(), eraValue, "EraValue"); - assertEquals(era.toString(), name, "Era Name"); - assertEquals(era, JapaneseChronology.INSTANCE.eraOf(eraValue), "JapaneseChronology.eraOf()"); + assertEquals(eraValue, era.getValue(), "EraValue"); + assertEquals(name, era.toString(), "Era Name"); + assertEquals(JapaneseChronology.INSTANCE.eraOf(eraValue), era, "JapaneseChronology.eraOf()"); List eras = JapaneseChronology.INSTANCE.eras(); assertTrue(eras.contains(era), "Era is not present in JapaneseChronology.INSTANCE.eras()"); } @@ -579,27 +594,28 @@ public class TCKJapaneseChronology { } } - @Test(dataProvider="japaneseEras") + @ParameterizedTest + @MethodSource("data_japanseseEras") public void test_JapaneseEra_singletons(Era expectedEra, int eraValue, String name) { JapaneseEra actualEra = JapaneseEra.valueOf(name); - assertEquals(actualEra, expectedEra, "JapaneseEra.valueOf(name)"); + assertEquals(expectedEra, actualEra, "JapaneseEra.valueOf(name)"); actualEra = JapaneseEra.of(eraValue); - assertEquals(actualEra, expectedEra, "JapaneseEra.of(value)"); + assertEquals(expectedEra, actualEra, "JapaneseEra.of(value)"); String string = actualEra.toString(); - assertEquals(string, name, "JapaneseEra.toString()"); + assertEquals(name, string, "JapaneseEra.toString()"); } @Test public void test_JapaneseEra_values() { JapaneseEra[] actualEras = JapaneseEra.values(); Object[][] erasInfo = data_japanseseEras(); - assertEquals(actualEras.length, erasInfo.length, "Wrong number of Eras"); + assertEquals(erasInfo.length, actualEras.length, "Wrong number of Eras"); for (int i = 0; i < erasInfo.length; i++) { Object[] eraInfo = erasInfo[i]; - assertEquals(actualEras[i], eraInfo[0], "Singleton mismatch"); + assertEquals(eraInfo[0], actualEras[i], "Singleton mismatch"); } } @@ -607,11 +623,11 @@ public class TCKJapaneseChronology { public void test_JapaneseChronology_eras() { List actualEras = JapaneseChronology.INSTANCE.eras(); Object[][] erasInfo = data_japanseseEras(); - assertEquals(actualEras.size(), erasInfo.length, "Wrong number of Eras"); + assertEquals(erasInfo.length, actualEras.size(), "Wrong number of Eras"); for (int i = 0; i < erasInfo.length; i++) { Object[] eraInfo = erasInfo[i]; - assertEquals(actualEras.get(i), eraInfo[0], "Singleton mismatch"); + assertEquals(eraInfo[0], actualEras.get(i), "Singleton mismatch"); } } @@ -623,7 +639,7 @@ public class TCKJapaneseChronology { JapaneseDate mdate1 = JapaneseDate.of(1970, 1, 1); JapaneseDate mdate2 = JapaneseDate.of(1971, 2, 2); ChronoPeriod period = mdate1.until(mdate2); - assertEquals(period, JapaneseChronology.INSTANCE.period(1, 1, 1)); + assertEquals(JapaneseChronology.INSTANCE.period(1, 1, 1), period); } @Test @@ -631,7 +647,7 @@ public class TCKJapaneseChronology { JapaneseDate mdate1 = JapaneseDate.of(1970, 1, 1); JapaneseDate mdate2 = JapaneseDate.of(1971, 2, 2); long months = mdate1.until(mdate2, ChronoUnit.MONTHS); - assertEquals(months, 13); + assertEquals(13, months); } @Test @@ -640,7 +656,7 @@ public class TCKJapaneseChronology { JapaneseDate mdate2 = JapaneseDate.of(1971, 2, 2); MinguoDate ldate2 = MinguoChronology.INSTANCE.date(mdate2); ChronoPeriod period = mdate1.until(ldate2); - assertEquals(period, JapaneseChronology.INSTANCE.period(1, 1, 1)); + assertEquals(JapaneseChronology.INSTANCE.period(1, 1, 1), period); } //----------------------------------------------------------------------- @@ -653,12 +669,12 @@ public class TCKJapaneseChronology { int firstYear = (era == JapaneseEra.MEIJI) ? 6 : 1; // Until Era supports range(YEAR_OF_ERA) JapaneseDate hd1 = JapaneseChronology.INSTANCE.dateYearDay(era, firstYear, 1); ValueRange range = hd1.range(DAY_OF_YEAR); - assertEquals(range.getMaximum(), hd1.lengthOfYear(), "lengthOfYear should match range.getMaximum()"); + assertEquals(hd1.lengthOfYear(), range.getMaximum(), "lengthOfYear should match range.getMaximum()"); for (int i = 1; i <= hd1.lengthOfYear(); i++) { JapaneseDate hd = JapaneseChronology.INSTANCE.dateYearDay(era, firstYear, i); int doy = hd.get(DAY_OF_YEAR); - assertEquals(doy, i, "get(DAY_OF_YEAR) incorrect for " + i + ", of date: " + hd); + assertEquals(i, doy, "get(DAY_OF_YEAR) incorrect for " + i + ", of date: " + hd); } } } @@ -669,14 +685,13 @@ public class TCKJapaneseChronology { for (int i = 1; i <= hd.lengthOfYear(); i++) { JapaneseDate hd2 = hd.with(DAY_OF_YEAR, i); int doy = hd2.get(DAY_OF_YEAR); - assertEquals(doy, i, "with(DAY_OF_YEAR) incorrect for " + i + " " + hd2); + assertEquals(i, doy, "with(DAY_OF_YEAR) incorrect for " + i + " " + hd2); } } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="toString") Object[][] data_toString() { return new Object[][] { {JapaneseChronology.INSTANCE.date(1873, 12, 5), "Japanese Meiji 6-12-05"}, @@ -693,9 +708,10 @@ public class TCKJapaneseChronology { }; } - @Test(dataProvider="toString") + @ParameterizedTest + @MethodSource("data_toString") public void test_toString(JapaneseDate jdate, String expected) { - assertEquals(jdate.toString(), expected); + assertEquals(expected, jdate.toString()); } //----------------------------------------------------------------------- @@ -713,7 +729,6 @@ public class TCKJapaneseChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_styleByEra") Object[][] data_resolve_styleByEra() { Object[][] result = new Object[ResolverStyle.values().length * JapaneseEra.values().length][]; int i = 0; @@ -725,41 +740,43 @@ public class TCKJapaneseChronology { return result; } - @Test(dataProvider = "resolve_styleByEra") + @ParameterizedTest + @MethodSource("data_resolve_styleByEra") public void test_resolve_yearOfEra_eraOnly_valid(ResolverStyle style, JapaneseEra era) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.ERA, (long) era.getValue()); JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(ChronoField.ERA), (Long) (long) era.getValue()); - assertEquals(fieldValues.size(), 1); + assertEquals(null, date); + assertEquals((Long) (long) era.getValue(), fieldValues.get(ChronoField.ERA)); + assertEquals(1, fieldValues.size()); } - @Test(dataProvider = "resolve_styleByEra") + @ParameterizedTest + @MethodSource("data_resolve_styleByEra") public void test_resolve_yearOfEra_eraAndYearOfEraOnly_valid(ResolverStyle style, JapaneseEra era) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.ERA, (long) era.getValue()); fieldValues.put(ChronoField.YEAR_OF_ERA, 1L); JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(ChronoField.ERA), (Long) (long) era.getValue()); - assertEquals(fieldValues.get(ChronoField.YEAR_OF_ERA), (Long) 1L); - assertEquals(fieldValues.size(), 2); + assertEquals(null, date); + assertEquals((Long) (long) era.getValue(), fieldValues.get(ChronoField.ERA)); + assertEquals((Long) 1L, fieldValues.get(ChronoField.YEAR_OF_ERA)); + assertEquals(2, fieldValues.size()); } - @Test(dataProvider = "resolve_styleByEra") + @ParameterizedTest + @MethodSource("data_resolve_styleByEra") public void test_resolve_yearOfEra_eraAndYearOnly_valid(ResolverStyle style, JapaneseEra era) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.ERA, (long) era.getValue()); fieldValues.put(ChronoField.YEAR, 1L); JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(ChronoField.ERA), (Long) (long) era.getValue()); - assertEquals(fieldValues.get(ChronoField.YEAR), (Long) 1L); - assertEquals(fieldValues.size(), 2); + assertEquals(null, date); + assertEquals((Long) (long) era.getValue(), fieldValues.get(ChronoField.ERA)); + assertEquals((Long) 1L, fieldValues.get(ChronoField.YEAR)); + assertEquals(2, fieldValues.size()); } - @DataProvider(name = "resolve_styles") Object[][] data_resolve_styles() { Object[][] result = new Object[ResolverStyle.values().length][]; int i = 0; @@ -769,28 +786,31 @@ public class TCKJapaneseChronology { return result; } - @Test(dataProvider = "resolve_styles") + @ParameterizedTest + @MethodSource("data_resolve_styles") public void test_resolve_yearOfEra_yearOfEraOnly_valid(ResolverStyle style) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR_OF_ERA, 1L); JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(ChronoField.YEAR_OF_ERA), (Long) 1L); - assertEquals(fieldValues.size(), 1); + assertEquals(null, date); + assertEquals((Long) 1L, fieldValues.get(ChronoField.YEAR_OF_ERA)); + assertEquals(1, fieldValues.size()); } - @Test(dataProvider = "resolve_styles") + @ParameterizedTest + @MethodSource("data_resolve_styles") public void test_resolve_yearOfEra_yearOfEraAndYearOnly_valid(ResolverStyle style) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR_OF_ERA, 1L); fieldValues.put(ChronoField.YEAR, 2012L); JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(ChronoField.YEAR_OF_ERA), (Long) 1L); - assertEquals(fieldValues.get(ChronoField.YEAR), (Long) 2012L); - assertEquals(fieldValues.size(), 2); + assertEquals(null, date); + assertEquals((Long) 1L, fieldValues.get(ChronoField.YEAR_OF_ERA)); + assertEquals((Long) 2012L, fieldValues.get(ChronoField.YEAR)); + assertEquals(2, fieldValues.size()); } + @Test public void test_resolve_yearOfEra_eraOnly_invalidTooSmall() { for (ResolverStyle style : ResolverStyle.values()) { Map fieldValues = new HashMap<>(); @@ -804,6 +824,7 @@ public class TCKJapaneseChronology { } } + @Test public void test_resolve_yearOfEra_eraOnly_invalidTooLarge() { for (ResolverStyle style : ResolverStyle.values()) { Map fieldValues = new HashMap<>(); @@ -819,7 +840,6 @@ public class TCKJapaneseChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_ymd") Object[][] data_resolve_ymd() { return new Object[][] { {2012, 1, -365, date(2010, 12, 31), false, false}, @@ -873,18 +893,20 @@ public class TCKJapaneseChronology { }; } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_lenient(int y, int m, int d, JapaneseDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.MONTH_OF_YEAR, (long) m); fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_smart(int y, int m, int d, JapaneseDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -892,11 +914,11 @@ public class TCKJapaneseChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (Boolean.TRUE.equals(smart)) { JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else if (smart instanceof JapaneseDate) { JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, smart); + assertEquals(smart, date); } else { try { JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -907,7 +929,8 @@ public class TCKJapaneseChronology { } } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_strict(int y, int m, int d, JapaneseDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -915,8 +938,8 @@ public class TCKJapaneseChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (strict) { JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); @@ -929,7 +952,6 @@ public class TCKJapaneseChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_yd") Object[][] data_resolve_yd() { return new Object[][] { {2012, -365, date(2010, 12, 31), false, false}, @@ -957,25 +979,27 @@ public class TCKJapaneseChronology { }; } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_lenient(int y, int d, JapaneseDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_smart(int y, int d, JapaneseDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); if (smart) { JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -986,15 +1010,16 @@ public class TCKJapaneseChronology { } } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_strict(int y, int d, JapaneseDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); if (strict) { JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { JapaneseChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); @@ -1007,7 +1032,6 @@ public class TCKJapaneseChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_eymd") Object[][] data_resolve_eymd() { return new Object[][] { // lenient @@ -1157,7 +1181,8 @@ public class TCKJapaneseChronology { }; } - @Test(dataProvider = "resolve_eymd") + @ParameterizedTest + @MethodSource("data_resolve_eymd") public void test_resolve_eymd(ResolverStyle style, JapaneseEra era, int yoe, int m, int d, JapaneseDate expected) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.ERA, (long) era.getValue()); @@ -1166,8 +1191,8 @@ public class TCKJapaneseChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (expected != null) { JapaneseDate date = JapaneseChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { JapaneseChronology.INSTANCE.resolveDate(fieldValues, style); diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKJapaneseEra.java b/test/jdk/java/time/tck/java/time/chrono/TCKJapaneseEra.java index edd3374b06b..f7f461716d2 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKJapaneseEra.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKJapaneseEra.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,27 +54,30 @@ */ package tck.java.time.chrono; +import java.time.DateTimeException; import static java.time.temporal.ChronoField.ERA; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.chrono.Era; import java.time.chrono.JapaneseChronology; import java.time.chrono.JapaneseEra; import java.util.List; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests for JapaneseEra * @bug 8068278 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKJapaneseEra { - @DataProvider(name = "JapaneseEras") Object[][] data_of_eras() { return new Object[][] { {JapaneseEra.REIWA, "Reiwa", 3}, @@ -85,7 +88,6 @@ public class TCKJapaneseEra { }; } - @DataProvider(name = "InvalidJapaneseEras") Object[][] data_of_invalid_eras() { return new Object[][] { {-2}, @@ -99,11 +101,12 @@ public class TCKJapaneseEra { //----------------------------------------------------------------------- // JapaneseEra value test //----------------------------------------------------------------------- - @Test(dataProvider="JapaneseEras") + @ParameterizedTest + @MethodSource("data_of_eras") public void test_valueOf(JapaneseEra era , String eraName, int eraValue) { - assertEquals(era.getValue(), eraValue); - assertEquals(JapaneseEra.of(eraValue), era); - assertEquals(JapaneseEra.valueOf(eraName), era); + assertEquals(eraValue, era.getValue()); + assertEquals(era, JapaneseEra.of(eraValue)); + assertEquals(era, JapaneseEra.valueOf(eraName)); } //----------------------------------------------------------------------- @@ -113,7 +116,7 @@ public class TCKJapaneseEra { public void test_values() { List eraList = JapaneseChronology.INSTANCE.eras(); JapaneseEra[] eras = JapaneseEra.values(); - assertEquals(eraList.size(), eras.length); + assertEquals(eras.length, eraList.size()); for (JapaneseEra era : eras) { assertTrue(eraList.contains(era)); } @@ -126,18 +129,19 @@ public class TCKJapaneseEra { public void test_range() { // eras may be added after release for (JapaneseEra era : JapaneseEra.values()) { - assertEquals(era.range(ERA).getMinimum(), -1); - assertEquals(era.range(ERA).getLargestMinimum(), -1); - assertEquals(era.range(ERA).getSmallestMaximum(), era.range(ERA).getMaximum()); - assertEquals(era.range(ERA).getMaximum() >= 2, true); + assertEquals(-1, era.range(ERA).getMinimum()); + assertEquals(-1, era.range(ERA).getLargestMinimum()); + assertEquals(era.range(ERA).getMaximum(), era.range(ERA).getSmallestMaximum()); + assertEquals(true, era.range(ERA).getMaximum() >= 2); } } //----------------------------------------------------------------------- // JapaneseChronology.INSTANCE.eraOf invalid era test //----------------------------------------------------------------------- - @Test(dataProvider="InvalidJapaneseEras", expectedExceptions=java.time.DateTimeException.class) + @ParameterizedTest + @MethodSource("data_of_invalid_eras") public void test_outofrange(int era) { - JapaneseChronology.INSTANCE.eraOf(era); + Assertions.assertThrows(DateTimeException.class, () -> JapaneseChronology.INSTANCE.eraOf(era)); } } diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKMinguoChronology.java b/test/jdk/java/time/tck/java/time/chrono/TCKMinguoChronology.java index 523a267104f..85bc8f2b4a0 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKMinguoChronology.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKMinguoChronology.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,11 +54,11 @@ */ package tck.java.time.chrono; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.Clock; import java.time.DateTimeException; @@ -94,14 +94,16 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKMinguoChronology { private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2); @@ -114,16 +116,15 @@ public class TCKMinguoChronology { public void test_chrono_byName() { Chronology c = MinguoChronology.INSTANCE; Chronology test = Chronology.of("Minguo"); - Assert.assertNotNull(test, "The Minguo calendar could not be found byName"); - Assert.assertEquals(test.getId(), "Minguo", "ID mismatch"); - Assert.assertEquals(test.getCalendarType(), "roc", "Type mismatch"); - Assert.assertEquals(test, c); + Assertions.assertNotNull(test, "The Minguo calendar could not be found byName"); + assertEquals("Minguo", test.getId(), "ID mismatch"); + assertEquals("roc", test.getCalendarType(), "Type mismatch"); + assertEquals(c, test); } //----------------------------------------------------------------------- // creation, toLocalDate() //----------------------------------------------------------------------- - @DataProvider(name="samples") Object[][] data_samples() { return new Object[][] { {MinguoChronology.INSTANCE.date(1, 1, 1), LocalDate.of(1 + YDIFF, 1, 1)}, @@ -158,50 +159,55 @@ public class TCKMinguoChronology { }; } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_toLocalDate(MinguoDate minguo, LocalDate iso) { - assertEquals(LocalDate.from(minguo), iso); + assertEquals(iso, LocalDate.from(minguo)); } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_fromCalendrical(MinguoDate minguo, LocalDate iso) { - assertEquals(MinguoChronology.INSTANCE.date(iso), minguo); - assertEquals(MinguoDate.from(iso), minguo); + assertEquals(minguo, MinguoChronology.INSTANCE.date(iso)); + assertEquals(minguo, MinguoDate.from(iso)); } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_isEqual(MinguoDate minguo, LocalDate iso) { assertTrue(minguo.isEqual(iso)); } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_date_equals(MinguoDate minguo, LocalDate iso) { assertFalse(minguo.equals(iso)); - assertNotEquals(minguo.hashCode(), iso.hashCode()); + assertNotEquals(iso.hashCode(), minguo.hashCode()); } @Test public void test_dateNow(){ - assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now()) ; - assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now(ZoneId.systemDefault())) ; - assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now(Clock.systemDefaultZone())) ; - assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now(Clock.systemDefaultZone().getZone())) ; + assertEquals(MinguoDate.now(), MinguoChronology.INSTANCE.dateNow()) ; + assertEquals(MinguoDate.now(ZoneId.systemDefault()), MinguoChronology.INSTANCE.dateNow()) ; + assertEquals(MinguoDate.now(Clock.systemDefaultZone()), MinguoChronology.INSTANCE.dateNow()) ; + assertEquals(MinguoDate.now(Clock.systemDefaultZone().getZone()), MinguoChronology.INSTANCE.dateNow()) ; - assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoChronology.INSTANCE.dateNow(ZoneId.systemDefault())) ; - assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoChronology.INSTANCE.dateNow(Clock.systemDefaultZone())) ; - assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone())) ; + assertEquals(MinguoChronology.INSTANCE.dateNow(ZoneId.systemDefault()), MinguoChronology.INSTANCE.dateNow()) ; + assertEquals(MinguoChronology.INSTANCE.dateNow(Clock.systemDefaultZone()), MinguoChronology.INSTANCE.dateNow()) ; + assertEquals(MinguoChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone()), MinguoChronology.INSTANCE.dateNow()) ; ZoneId zoneId = ZoneId.of("Europe/Paris"); - assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoChronology.INSTANCE.dateNow(Clock.system(zoneId))) ; - assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone())) ; - assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoDate.now(Clock.system(zoneId))) ; - assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoDate.now(Clock.system(zoneId).getZone())) ; + assertEquals(MinguoChronology.INSTANCE.dateNow(Clock.system(zoneId)), MinguoChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(MinguoChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone()), MinguoChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(MinguoDate.now(Clock.system(zoneId)), MinguoChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(MinguoDate.now(Clock.system(zoneId).getZone()), MinguoChronology.INSTANCE.dateNow(zoneId)) ; - assertEquals(MinguoChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId())), MinguoChronology.INSTANCE.dateNow(Clock.systemUTC())) ; + assertEquals(MinguoChronology.INSTANCE.dateNow(Clock.systemUTC()), MinguoChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId()))) ; } @SuppressWarnings("unused") - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_MinguoDate(MinguoDate minguoDate, LocalDate iso) { MinguoDate hd = minguoDate; ChronoLocalDateTime hdt = hd.atTime(LocalTime.NOON); @@ -229,7 +235,6 @@ public class TCKMinguoChronology { ChronoZonedDateTime h4 = h3.atZone(ZoneOffset.UTC); } - @DataProvider(name="badDates") Object[][] data_badDates() { return new Object[][] { {1912, 0, 0}, @@ -256,15 +261,15 @@ public class TCKMinguoChronology { }; } - @Test(dataProvider="badDates", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_badDates") public void test_badDates(int year, int month, int dom) { - MinguoChronology.INSTANCE.date(year, month, dom); + Assertions.assertThrows(DateTimeException.class, () -> MinguoChronology.INSTANCE.date(year, month, dom)); } //----------------------------------------------------------------------- // prolepticYear() and is LeapYear() //----------------------------------------------------------------------- - @DataProvider(name="prolepticYear") Object[][] data_prolepticYear() { return new Object[][] { {1, MinguoEra.ROC, 1912 - YDIFF, 1912 - YDIFF, true}, @@ -290,25 +295,27 @@ public class TCKMinguoChronology { }; } - @Test(dataProvider="prolepticYear") + @ParameterizedTest + @MethodSource("data_prolepticYear") public void test_prolepticYear(int eraValue, Era era, int yearOfEra, int expectedProlepticYear, boolean isLeapYear) { Era eraObj = MinguoChronology.INSTANCE.eraOf(eraValue); assertTrue(MinguoChronology.INSTANCE.eras().contains(eraObj)); - assertEquals(eraObj, era); - assertEquals(MinguoChronology.INSTANCE.prolepticYear(era, yearOfEra), expectedProlepticYear); + assertEquals(era, eraObj); + assertEquals(expectedProlepticYear, MinguoChronology.INSTANCE.prolepticYear(era, yearOfEra)); } - @Test(dataProvider="prolepticYear") + @ParameterizedTest + @MethodSource("data_prolepticYear") public void test_isLeapYear(int eraValue, Era era, int yearOfEra, int expectedProlepticYear, boolean isLeapYear) { - assertEquals(MinguoChronology.INSTANCE.isLeapYear(expectedProlepticYear), isLeapYear); - assertEquals(MinguoChronology.INSTANCE.isLeapYear(expectedProlepticYear), Year.of(expectedProlepticYear + YDIFF).isLeap()); + assertEquals(isLeapYear, MinguoChronology.INSTANCE.isLeapYear(expectedProlepticYear)); + assertEquals(Year.of(expectedProlepticYear + YDIFF).isLeap(), MinguoChronology.INSTANCE.isLeapYear(expectedProlepticYear)); MinguoDate minguo = MinguoDate.now(); minguo = minguo.with(ChronoField.YEAR, expectedProlepticYear).with(ChronoField.MONTH_OF_YEAR, 2); if (isLeapYear) { - assertEquals(minguo.lengthOfMonth(), 29); + assertEquals(29, minguo.lengthOfMonth()); } else { - assertEquals(minguo.lengthOfMonth(), 28); + assertEquals(28, minguo.lengthOfMonth()); } } @@ -359,14 +366,14 @@ public class TCKMinguoChronology { public void test_adjust1() { MinguoDate base = MinguoChronology.INSTANCE.date(2012, 10, 29); MinguoDate test = base.with(TemporalAdjusters.lastDayOfMonth()); - assertEquals(test, MinguoChronology.INSTANCE.date(2012, 10, 31)); + assertEquals(MinguoChronology.INSTANCE.date(2012, 10, 31), test); } @Test public void test_adjust2() { MinguoDate base = MinguoChronology.INSTANCE.date(1728, 12, 2); MinguoDate test = base.with(TemporalAdjusters.lastDayOfMonth()); - assertEquals(test, MinguoChronology.INSTANCE.date(1728, 12, 31)); + assertEquals(MinguoChronology.INSTANCE.date(1728, 12, 31), test); } //----------------------------------------------------------------------- @@ -376,13 +383,15 @@ public class TCKMinguoChronology { public void test_adjust_toLocalDate() { MinguoDate minguo = MinguoChronology.INSTANCE.date(99, 1, 4); MinguoDate test = minguo.with(LocalDate.of(2012, 7, 6)); - assertEquals(test, MinguoChronology.INSTANCE.date(101, 7, 6)); + assertEquals(MinguoChronology.INSTANCE.date(101, 7, 6), test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_adjust_toMonth() { - MinguoDate minguo = MinguoChronology.INSTANCE.date(1726, 1, 4); - minguo.with(Month.APRIL); + Assertions.assertThrows(DateTimeException.class, () -> { + MinguoDate minguo = MinguoChronology.INSTANCE.date(1726, 1, 4); + minguo.with(Month.APRIL); + }); } //----------------------------------------------------------------------- @@ -392,20 +401,19 @@ public class TCKMinguoChronology { public void test_LocalDate_adjustToMinguoDate() { MinguoDate minguo = MinguoChronology.INSTANCE.date(101, 10, 29); LocalDate test = LocalDate.MIN.with(minguo); - assertEquals(test, LocalDate.of(2012, 10, 29)); + assertEquals(LocalDate.of(2012, 10, 29), test); } @Test public void test_LocalDateTime_adjustToMinguoDate() { MinguoDate minguo = MinguoChronology.INSTANCE.date(101, 10, 29); LocalDateTime test = LocalDateTime.MIN.with(minguo); - assertEquals(test, LocalDateTime.of(2012, 10, 29, 0, 0)); + assertEquals(LocalDateTime.of(2012, 10, 29, 0, 0), test); } //----------------------------------------------------------------------- // localDateTime() //----------------------------------------------------------------------- - @DataProvider(name="localDateTime") Object[][] data_localDateTime() { return new Object[][] { {LocalDateTime.of(2012, 2, 29, 2, 7), MinguoChronology.INSTANCE.date(MinguoEra.ROC, 2012 - YDIFF, 2, 29), LocalTime.of(2, 7), null}, @@ -419,13 +427,14 @@ public class TCKMinguoChronology { }; } - @Test(dataProvider="localDateTime") + @ParameterizedTest + @MethodSource("data_localDateTime") public void test_localDateTime(TemporalAccessor accessor, MinguoDate expectedDate, LocalTime expectedTime, Class expectedEx) { if (expectedEx == null) { ChronoLocalDateTime result = MinguoChronology.INSTANCE.localDateTime(accessor); - assertEquals(result.toLocalDate(), expectedDate); - assertEquals(MinguoDate.from(accessor), expectedDate); - assertEquals(result.toLocalTime(), expectedTime); + assertEquals(expectedDate, result.toLocalDate()); + assertEquals(expectedDate, MinguoDate.from(accessor)); + assertEquals(expectedTime, result.toLocalTime()); } else { try { ChronoLocalDateTime result = MinguoChronology.INSTANCE.localDateTime(accessor); @@ -439,7 +448,6 @@ public class TCKMinguoChronology { //----------------------------------------------------------------------- // zonedDateTime(TemporalAccessor) //----------------------------------------------------------------------- - @DataProvider(name="zonedDateTime") Object[][] data_zonedDateTime() { return new Object[][] { {ZonedDateTime.of(2012, 2, 29, 2, 7, 1, 1, ZONE_PARIS), MinguoChronology.INSTANCE.date(MinguoEra.ROC, 2012 - YDIFF, 2, 29), LocalTime.of(2, 7, 1, 1), null}, @@ -453,13 +461,14 @@ public class TCKMinguoChronology { }; } - @Test(dataProvider="zonedDateTime") + @ParameterizedTest + @MethodSource("data_zonedDateTime") public void test_zonedDateTime(TemporalAccessor accessor, MinguoDate expectedDate, LocalTime expectedTime, Class expectedEx) { if (expectedEx == null) { ChronoZonedDateTime result = MinguoChronology.INSTANCE.zonedDateTime(accessor); - assertEquals(result.toLocalDate(), expectedDate); - assertEquals(MinguoDate.from(accessor), expectedDate); - assertEquals(result.toLocalTime(), expectedTime); + assertEquals(expectedDate, result.toLocalDate()); + assertEquals(expectedDate, MinguoDate.from(accessor)); + assertEquals(expectedTime, result.toLocalTime()); } else { try { @@ -480,12 +489,12 @@ public class TCKMinguoChronology { ZonedDateTime zonedDateTime = ZonedDateTime.of(2012, 2, 29, 2, 7, 1, 1, ZONE_PARIS); ChronoZonedDateTime result = MinguoChronology.INSTANCE.zonedDateTime(offsetDateTime.toInstant(), offsetDateTime.getOffset()); - assertEquals(result.toLocalDate(), MinguoChronology.INSTANCE.date(MinguoEra.ROC, 2012 - YDIFF, 2, 29)); - assertEquals(result.toLocalTime(), LocalTime.of(2, 7, 1, 1)); + assertEquals(MinguoChronology.INSTANCE.date(MinguoEra.ROC, 2012 - YDIFF, 2, 29), result.toLocalDate()); + assertEquals(LocalTime.of(2, 7, 1, 1), result.toLocalTime()); result = MinguoChronology.INSTANCE.zonedDateTime(zonedDateTime.toInstant(), zonedDateTime.getOffset()); - assertEquals(result.toLocalDate(), MinguoChronology.INSTANCE.date(MinguoEra.ROC, 2012 - YDIFF, 2, 29)); - assertEquals(result.toLocalTime(), LocalTime.of(2, 7, 1, 1)); + assertEquals(MinguoChronology.INSTANCE.date(MinguoEra.ROC, 2012 - YDIFF, 2, 29), result.toLocalDate()); + assertEquals(LocalTime.of(2, 7, 1, 1), result.toLocalTime()); } //----------------------------------------------------------------------- @@ -496,7 +505,7 @@ public class TCKMinguoChronology { MinguoDate mdate1 = MinguoDate.of(1970, 1, 1); MinguoDate mdate2 = MinguoDate.of(1971, 2, 2); ChronoPeriod period = mdate1.until(mdate2); - assertEquals(period, MinguoChronology.INSTANCE.period(1, 1, 1)); + assertEquals(MinguoChronology.INSTANCE.period(1, 1, 1), period); } @Test @@ -504,7 +513,7 @@ public class TCKMinguoChronology { MinguoDate mdate1 = MinguoDate.of(1970, 1, 1); MinguoDate mdate2 = MinguoDate.of(1971, 2, 2); long months = mdate1.until(mdate2, ChronoUnit.MONTHS); - assertEquals(months, 13); + assertEquals(13, months); } @Test @@ -513,13 +522,12 @@ public class TCKMinguoChronology { MinguoDate mdate2 = MinguoDate.of(1971, 2, 2); ThaiBuddhistDate ldate2 = ThaiBuddhistChronology.INSTANCE.date(mdate2); ChronoPeriod period = mdate1.until(ldate2); - assertEquals(period, MinguoChronology.INSTANCE.period(1, 1, 1)); + assertEquals(MinguoChronology.INSTANCE.period(1, 1, 1), period); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="toString") Object[][] data_toString() { return new Object[][] { {MinguoChronology.INSTANCE.date(1, 1, 1), "Minguo ROC 1-01-01"}, @@ -530,9 +538,10 @@ public class TCKMinguoChronology { }; } - @Test(dataProvider="toString") + @ParameterizedTest + @MethodSource("data_toString") public void test_toString(MinguoDate minguo, String expected) { - assertEquals(minguo.toString(), expected); + assertEquals(expected, minguo.toString()); } //----------------------------------------------------------------------- @@ -550,7 +559,6 @@ public class TCKMinguoChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_yearOfEra") Object[][] data_resolve_yearOfEra() { return new Object[][] { // era only @@ -615,7 +623,8 @@ public class TCKMinguoChronology { }; } - @Test(dataProvider = "resolve_yearOfEra") + @ParameterizedTest + @MethodSource("data_resolve_yearOfEra") public void test_resolve_yearOfEra(ResolverStyle style, Integer e, Integer yoe, Integer y, ChronoField field, Integer expected) { Map fieldValues = new HashMap<>(); if (e != null) { @@ -629,9 +638,9 @@ public class TCKMinguoChronology { } if (field != null) { MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(field), (Long) expected.longValue()); - assertEquals(fieldValues.size(), 1); + assertEquals(null, date); + assertEquals((Long) expected.longValue(), fieldValues.get(field)); + assertEquals(1, fieldValues.size()); } else { try { MinguoChronology.INSTANCE.resolveDate(fieldValues, style); @@ -644,7 +653,6 @@ public class TCKMinguoChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_ymd") Object[][] data_resolve_ymd() { return new Object[][] { {2012 - YDIFF, 1, -365, date(2010 - YDIFF, 12, 31), false, false}, @@ -703,18 +711,20 @@ public class TCKMinguoChronology { }; } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_lenient(int y, int m, int d, MinguoDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.MONTH_OF_YEAR, (long) m); fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_smart(int y, int m, int d, MinguoDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -722,11 +732,11 @@ public class TCKMinguoChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (Boolean.TRUE.equals(smart)) { MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else if (smart instanceof MinguoDate) { MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, smart); + assertEquals(smart, date); } else { try { MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -737,7 +747,8 @@ public class TCKMinguoChronology { } } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_strict(int y, int m, int d, MinguoDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -745,8 +756,8 @@ public class TCKMinguoChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (strict) { MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); @@ -759,7 +770,6 @@ public class TCKMinguoChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_yd") Object[][] data_resolve_yd() { return new Object[][] { {2012 - YDIFF, -365, date(2010 - YDIFF, 12, 31), false, false}, @@ -787,25 +797,27 @@ public class TCKMinguoChronology { }; } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_lenient(int y, int d, MinguoDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_smart(int y, int d, MinguoDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); if (smart) { MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -816,15 +828,16 @@ public class TCKMinguoChronology { } } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_strict(int y, int d, MinguoDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); if (strict) { MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); @@ -837,7 +850,6 @@ public class TCKMinguoChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_ymaa") Object[][] data_resolve_ymaa() { return new Object[][] { {2012 - YDIFF, 1, 1, -365, date(2010 - YDIFF, 12, 31), false, false}, @@ -894,7 +906,8 @@ public class TCKMinguoChronology { }; } - @Test(dataProvider = "resolve_ymaa") + @ParameterizedTest + @MethodSource("data_resolve_ymaa") public void test_resolve_ymaa_lenient(int y, int m, int w, int d, MinguoDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -902,11 +915,12 @@ public class TCKMinguoChronology { fieldValues.put(ChronoField.ALIGNED_WEEK_OF_MONTH, (long) w); fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d); MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_ymaa") + @ParameterizedTest + @MethodSource("data_resolve_ymaa") public void test_resolve_ymaa_smart(int y, int m, int w, int d, MinguoDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -915,8 +929,8 @@ public class TCKMinguoChronology { fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d); if (smart) { MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -927,7 +941,8 @@ public class TCKMinguoChronology { } } - @Test(dataProvider = "resolve_ymaa") + @ParameterizedTest + @MethodSource("data_resolve_ymaa") public void test_resolve_ymaa_strict(int y, int m, int w, int d, MinguoDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -936,8 +951,8 @@ public class TCKMinguoChronology { fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d); if (strict) { MinguoDate date = MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { MinguoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKMinguoEra.java b/test/jdk/java/time/tck/java/time/chrono/TCKMinguoEra.java index 9b7d5bcb535..3a48002c141 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKMinguoEra.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKMinguoEra.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -56,8 +56,9 @@ package tck.java.time.chrono; import static java.time.temporal.ChronoField.ERA; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.chrono.Era; import java.time.chrono.MinguoChronology; @@ -65,16 +66,17 @@ import java.time.chrono.MinguoEra; import java.time.temporal.ValueRange; import java.util.List; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKMinguoEra { - @DataProvider(name = "MinguoEras") Object[][] data_of_eras() { return new Object[][] { {MinguoEra.BEFORE_ROC, "BEFORE_ROC", 0}, @@ -85,11 +87,12 @@ public class TCKMinguoEra { //----------------------------------------------------------------------- // valueOf() //----------------------------------------------------------------------- - @Test(dataProvider="MinguoEras") + @ParameterizedTest + @MethodSource("data_of_eras") public void test_valueOf(MinguoEra era , String eraName, int eraValue) { - assertEquals(era.getValue(), eraValue); - assertEquals(MinguoEra.of(eraValue), era); - assertEquals(MinguoEra.valueOf(eraName), era); + assertEquals(eraValue, era.getValue()); + assertEquals(era, MinguoEra.of(eraValue)); + assertEquals(era, MinguoEra.valueOf(eraName)); } @@ -100,7 +103,7 @@ public class TCKMinguoEra { public void test_values() { List eraList = MinguoChronology.INSTANCE.eras(); MinguoEra[] eras = MinguoEra.values() ; - assertEquals(eraList.size(), eras.length); + assertEquals(eras.length, eraList.size()); for (MinguoEra era : eras) { assertTrue(eraList.contains(era)); } @@ -112,7 +115,7 @@ public class TCKMinguoEra { @Test public void test_range() { for (MinguoEra era : MinguoEra.values()) { - assertEquals(era.range(ERA), ValueRange.of(0, 1)); + assertEquals(ValueRange.of(0, 1), era.range(ERA)); } } diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKTestServiceLoader.java b/test/jdk/java/time/tck/java/time/chrono/TCKTestServiceLoader.java index aa3aeef31a5..824b8dae70f 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKTestServiceLoader.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKTestServiceLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,19 +59,18 @@ */ package tck.java.time.chrono; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDate; import java.time.chrono.ChronoLocalDate; import java.time.chrono.Chronology; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Tests that a custom Chronology is available via the ServiceLoader. * The CopticChronology is configured via META-INF/services/java.time.chrono.Chronology. */ -@Test public class TCKTestServiceLoader { @Test @@ -79,8 +78,8 @@ public class TCKTestServiceLoader { Chronology chrono = Chronology.of("Coptic"); ChronoLocalDate copticDate = chrono.date(1729, 4, 27); LocalDate ld = LocalDate.from(copticDate); - assertEquals(ld, LocalDate.of(2013, 1, 5), "CopticDate does not match LocalDate"); - assertEquals(chrono.isIsoBased(), false); + assertEquals(LocalDate.of(2013, 1, 5), ld, "CopticDate does not match LocalDate"); + assertEquals(false, chrono.isIsoBased()); } } diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKThaiBuddhistChronology.java b/test/jdk/java/time/tck/java/time/chrono/TCKThaiBuddhistChronology.java index e54ecf9dc23..739515aa278 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKThaiBuddhistChronology.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKThaiBuddhistChronology.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,11 +59,12 @@ import static java.time.temporal.ChronoField.DAY_OF_YEAR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoField.YEAR_OF_ERA; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.Clock; import java.time.DateTimeException; @@ -94,14 +95,16 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKThaiBuddhistChronology { private static final int YDIFF = 543; @@ -113,10 +116,10 @@ public class TCKThaiBuddhistChronology { public void test_chrono_byName() { Chronology c = ThaiBuddhistChronology.INSTANCE; Chronology test = Chronology.of("ThaiBuddhist"); - Assert.assertNotNull(test, "The ThaiBuddhist calendar could not be found byName"); - Assert.assertEquals(test.getId(), "ThaiBuddhist", "ID mismatch"); - Assert.assertEquals(test.getCalendarType(), "buddhist", "Type mismatch"); - Assert.assertEquals(test, c); + Assertions.assertNotNull(test, "The ThaiBuddhist calendar could not be found byName"); + assertEquals("ThaiBuddhist", test.getId(), "ID mismatch"); + assertEquals("buddhist", test.getCalendarType(), "Type mismatch"); + assertEquals(c, test); } //----------------------------------------------------------------------- @@ -125,42 +128,41 @@ public class TCKThaiBuddhistChronology { @Test public void test_chrono_byLocale_fullTag_thaiCalendarFromThai() { Chronology test = Chronology.ofLocale(Locale.forLanguageTag("th-TH-u-ca-buddhist")); - Assert.assertEquals(test.getId(), "ThaiBuddhist"); - Assert.assertEquals(test, ThaiBuddhistChronology.INSTANCE); + assertEquals("ThaiBuddhist", test.getId()); + assertEquals(ThaiBuddhistChronology.INSTANCE, test); } @Test public void test_chrono_byLocale_fullTag_thaiCalendarFromElsewhere() { Chronology test = Chronology.ofLocale(Locale.forLanguageTag("en-US-u-ca-buddhist")); - Assert.assertEquals(test.getId(), "ThaiBuddhist"); - Assert.assertEquals(test, ThaiBuddhistChronology.INSTANCE); + assertEquals("ThaiBuddhist", test.getId()); + assertEquals(ThaiBuddhistChronology.INSTANCE, test); } @Test public void test_chrono_byLocale_oldTH_noVariant() { // deliberately different to Calendar Chronology test = Chronology.ofLocale(Locale.of("th", "TH")); - Assert.assertEquals(test.getId(), "ISO"); - Assert.assertEquals(test, IsoChronology.INSTANCE); + assertEquals("ISO", test.getId()); + assertEquals(IsoChronology.INSTANCE, test); } @Test public void test_chrono_byLocale_oldTH_variant() { Chronology test = Chronology.ofLocale(Locale.of("th", "TH", "TH")); - Assert.assertEquals(test.getId(), "ISO"); - Assert.assertEquals(test, IsoChronology.INSTANCE); + assertEquals("ISO", test.getId()); + assertEquals(IsoChronology.INSTANCE, test); } @Test public void test_chrono_byLocale_iso() { - Assert.assertEquals(Chronology.ofLocale(Locale.of("th", "TH")).getId(), "ISO"); - Assert.assertEquals(Chronology.ofLocale(Locale.forLanguageTag("th-TH")).getId(), "ISO"); - Assert.assertEquals(Chronology.ofLocale(Locale.forLanguageTag("th-TH-TH")).getId(), "ISO"); + assertEquals("ISO", Chronology.ofLocale(Locale.of("th", "TH")).getId()); + assertEquals("ISO", Chronology.ofLocale(Locale.forLanguageTag("th-TH")).getId()); + assertEquals("ISO", Chronology.ofLocale(Locale.forLanguageTag("th-TH-TH")).getId()); } //----------------------------------------------------------------------- // creation, toLocalDate() //----------------------------------------------------------------------- - @DataProvider(name="samples") Object[][] data_samples() { return new Object[][] { {ThaiBuddhistChronology.INSTANCE.date(1 + YDIFF, 1, 1), LocalDate.of(1, 1, 1)}, @@ -195,49 +197,52 @@ public class TCKThaiBuddhistChronology { }; } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_toLocalDate(ThaiBuddhistDate jdate, LocalDate iso) { - assertEquals(LocalDate.from(jdate), iso); + assertEquals(iso, LocalDate.from(jdate)); } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_fromCalendrical(ThaiBuddhistDate jdate, LocalDate iso) { - assertEquals(ThaiBuddhistChronology.INSTANCE.date(iso), jdate); - assertEquals(ThaiBuddhistDate.from(iso), jdate); + assertEquals(jdate, ThaiBuddhistChronology.INSTANCE.date(iso)); + assertEquals(jdate, ThaiBuddhistDate.from(iso)); } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_isEqual(ThaiBuddhistDate jdate, LocalDate iso) { assertTrue(jdate.isEqual(iso)); } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_date_equals(ThaiBuddhistDate jdate, LocalDate iso) { assertFalse(jdate.equals(iso)); - assertNotEquals(jdate.hashCode(), iso.hashCode()); + assertNotEquals(iso.hashCode(), jdate.hashCode()); } @Test public void test_dateNow(){ - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistDate.now()) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistDate.now(ZoneId.systemDefault())) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistDate.now(Clock.systemDefaultZone())) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistDate.now(Clock.systemDefaultZone().getZone())) ; + assertEquals(ThaiBuddhistDate.now(), ThaiBuddhistChronology.INSTANCE.dateNow()) ; + assertEquals(ThaiBuddhistDate.now(ZoneId.systemDefault()), ThaiBuddhistChronology.INSTANCE.dateNow()) ; + assertEquals(ThaiBuddhistDate.now(Clock.systemDefaultZone()), ThaiBuddhistChronology.INSTANCE.dateNow()) ; + assertEquals(ThaiBuddhistDate.now(Clock.systemDefaultZone().getZone()), ThaiBuddhistChronology.INSTANCE.dateNow()) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistChronology.INSTANCE.dateNow(ZoneId.systemDefault())) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistChronology.INSTANCE.dateNow(Clock.systemDefaultZone())) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone())) ; + assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(ZoneId.systemDefault()), ThaiBuddhistChronology.INSTANCE.dateNow()) ; + assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(Clock.systemDefaultZone()), ThaiBuddhistChronology.INSTANCE.dateNow()) ; + assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone()), ThaiBuddhistChronology.INSTANCE.dateNow()) ; ZoneId zoneId = ZoneId.of("Europe/Paris"); - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(zoneId), ThaiBuddhistChronology.INSTANCE.dateNow(Clock.system(zoneId))) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(zoneId), ThaiBuddhistChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone())) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(zoneId), ThaiBuddhistDate.now(Clock.system(zoneId))) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(zoneId), ThaiBuddhistDate.now(Clock.system(zoneId).getZone())) ; + assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(Clock.system(zoneId)), ThaiBuddhistChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone()), ThaiBuddhistChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(ThaiBuddhistDate.now(Clock.system(zoneId)), ThaiBuddhistChronology.INSTANCE.dateNow(zoneId)) ; + assertEquals(ThaiBuddhistDate.now(Clock.system(zoneId).getZone()), ThaiBuddhistChronology.INSTANCE.dateNow(zoneId)) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId())), ThaiBuddhistChronology.INSTANCE.dateNow(Clock.systemUTC())) ; + assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(Clock.systemUTC()), ThaiBuddhistChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId()))) ; } - @DataProvider(name="badDates") Object[][] data_badDates() { return new Object[][] { {1728, 0, 0}, @@ -261,15 +266,15 @@ public class TCKThaiBuddhistChronology { }; } - @Test(dataProvider="badDates", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("data_badDates") public void test_badDates(int year, int month, int dom) { - ThaiBuddhistChronology.INSTANCE.date(year, month, dom); + Assertions.assertThrows(DateTimeException.class, () -> ThaiBuddhistChronology.INSTANCE.date(year, month, dom)); } //----------------------------------------------------------------------- // prolepticYear() and is LeapYear() //----------------------------------------------------------------------- - @DataProvider(name="prolepticYear") Object[][] data_prolepticYear() { return new Object[][] { {1, ThaiBuddhistEra.BE, 4 + YDIFF, 4 + YDIFF, true}, @@ -297,25 +302,27 @@ public class TCKThaiBuddhistChronology { }; } - @Test(dataProvider="prolepticYear") + @ParameterizedTest + @MethodSource("data_prolepticYear") public void test_prolepticYear(int eraValue, Era era, int yearOfEra, int expectedProlepticYear, boolean isLeapYear) { Era eraObj = ThaiBuddhistChronology.INSTANCE.eraOf(eraValue); assertTrue(ThaiBuddhistChronology.INSTANCE.eras().contains(eraObj)); - assertEquals(eraObj, era); - assertEquals(ThaiBuddhistChronology.INSTANCE.prolepticYear(era, yearOfEra), expectedProlepticYear); + assertEquals(era, eraObj); + assertEquals(expectedProlepticYear, ThaiBuddhistChronology.INSTANCE.prolepticYear(era, yearOfEra)); } - @Test(dataProvider="prolepticYear") + @ParameterizedTest + @MethodSource("data_prolepticYear") public void test_isLeapYear(int eraValue, Era era, int yearOfEra, int expectedProlepticYear, boolean isLeapYear) { - assertEquals(ThaiBuddhistChronology.INSTANCE.isLeapYear(expectedProlepticYear), isLeapYear) ; - assertEquals(ThaiBuddhistChronology.INSTANCE.isLeapYear(expectedProlepticYear), Year.of(expectedProlepticYear - YDIFF).isLeap()); + assertEquals(isLeapYear, ThaiBuddhistChronology.INSTANCE.isLeapYear(expectedProlepticYear)) ; + assertEquals(Year.of(expectedProlepticYear - YDIFF).isLeap(), ThaiBuddhistChronology.INSTANCE.isLeapYear(expectedProlepticYear)); ThaiBuddhistDate jdate = ThaiBuddhistDate.now(); jdate = jdate.with(ChronoField.YEAR, expectedProlepticYear).with(ChronoField.MONTH_OF_YEAR, 2); if (isLeapYear) { - assertEquals(jdate.lengthOfMonth(), 29); + assertEquals(29, jdate.lengthOfMonth()); } else { - assertEquals(jdate.lengthOfMonth(), 28); + assertEquals(28, jdate.lengthOfMonth()); } } @@ -365,14 +372,14 @@ public class TCKThaiBuddhistChronology { public void test_adjust1() { ThaiBuddhistDate base = ThaiBuddhistChronology.INSTANCE.date(1728, 10, 29); ThaiBuddhistDate test = base.with(TemporalAdjusters.lastDayOfMonth()); - assertEquals(test, ThaiBuddhistChronology.INSTANCE.date(1728, 10, 31)); + assertEquals(ThaiBuddhistChronology.INSTANCE.date(1728, 10, 31), test); } @Test public void test_adjust2() { ThaiBuddhistDate base = ThaiBuddhistChronology.INSTANCE.date(1728, 12, 2); ThaiBuddhistDate test = base.with(TemporalAdjusters.lastDayOfMonth()); - assertEquals(test, ThaiBuddhistChronology.INSTANCE.date(1728, 12, 31)); + assertEquals(ThaiBuddhistChronology.INSTANCE.date(1728, 12, 31), test); } //----------------------------------------------------------------------- @@ -382,14 +389,14 @@ public class TCKThaiBuddhistChronology { public void test_withYear_BE() { ThaiBuddhistDate base = ThaiBuddhistChronology.INSTANCE.date(2555, 8, 29); ThaiBuddhistDate test = base.with(YEAR, 2554); - assertEquals(test, ThaiBuddhistChronology.INSTANCE.date(2554, 8, 29)); + assertEquals(ThaiBuddhistChronology.INSTANCE.date(2554, 8, 29), test); } @Test public void test_withYear_BBE() { ThaiBuddhistDate base = ThaiBuddhistChronology.INSTANCE.date(-2554, 8, 29); ThaiBuddhistDate test = base.with(YEAR_OF_ERA, 2554); - assertEquals(test, ThaiBuddhistChronology.INSTANCE.date(-2553, 8, 29)); + assertEquals(ThaiBuddhistChronology.INSTANCE.date(-2553, 8, 29), test); } //----------------------------------------------------------------------- @@ -399,21 +406,21 @@ public class TCKThaiBuddhistChronology { public void test_withEra_BE() { ThaiBuddhistDate base = ThaiBuddhistChronology.INSTANCE.date(2555, 8, 29); ThaiBuddhistDate test = base.with(ChronoField.ERA, ThaiBuddhistEra.BE.getValue()); - assertEquals(test, ThaiBuddhistChronology.INSTANCE.date(2555, 8, 29)); + assertEquals(ThaiBuddhistChronology.INSTANCE.date(2555, 8, 29), test); } @Test public void test_withEra_BBE() { ThaiBuddhistDate base = ThaiBuddhistChronology.INSTANCE.date(-2554, 8, 29); ThaiBuddhistDate test = base.with(ChronoField.ERA, ThaiBuddhistEra.BEFORE_BE.getValue()); - assertEquals(test, ThaiBuddhistChronology.INSTANCE.date(-2554, 8, 29)); + assertEquals(ThaiBuddhistChronology.INSTANCE.date(-2554, 8, 29), test); } @Test public void test_withEra_swap() { ThaiBuddhistDate base = ThaiBuddhistChronology.INSTANCE.date(-2554, 8, 29); ThaiBuddhistDate test = base.with(ChronoField.ERA, ThaiBuddhistEra.BE.getValue()); - assertEquals(test, ThaiBuddhistChronology.INSTANCE.date(2555, 8, 29)); + assertEquals(ThaiBuddhistChronology.INSTANCE.date(2555, 8, 29), test); } //----------------------------------------------------------------------- @@ -423,13 +430,15 @@ public class TCKThaiBuddhistChronology { public void test_adjust_toLocalDate() { ThaiBuddhistDate jdate = ThaiBuddhistChronology.INSTANCE.date(1726, 1, 4); ThaiBuddhistDate test = jdate.with(LocalDate.of(2012, 7, 6)); - assertEquals(test, ThaiBuddhistChronology.INSTANCE.date(2555, 7, 6)); + assertEquals(ThaiBuddhistChronology.INSTANCE.date(2555, 7, 6), test); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_adjust_toMonth() { - ThaiBuddhistDate jdate = ThaiBuddhistChronology.INSTANCE.date(1726, 1, 4); - jdate.with(Month.APRIL); + Assertions.assertThrows(DateTimeException.class, () -> { + ThaiBuddhistDate jdate = ThaiBuddhistChronology.INSTANCE.date(1726, 1, 4); + jdate.with(Month.APRIL); + }); } //----------------------------------------------------------------------- @@ -439,14 +448,14 @@ public class TCKThaiBuddhistChronology { public void test_LocalDate_adjustToBuddhistDate() { ThaiBuddhistDate jdate = ThaiBuddhistChronology.INSTANCE.date(2555, 10, 29); LocalDate test = LocalDate.MIN.with(jdate); - assertEquals(test, LocalDate.of(2012, 10, 29)); + assertEquals(LocalDate.of(2012, 10, 29), test); } @Test public void test_LocalDateTime_adjustToBuddhistDate() { ThaiBuddhistDate jdate = ThaiBuddhistChronology.INSTANCE.date(2555, 10, 29); LocalDateTime test = LocalDateTime.MIN.with(jdate); - assertEquals(test, LocalDateTime.of(2012, 10, 29, 0, 0)); + assertEquals(LocalDateTime.of(2012, 10, 29, 0, 0), test); } //----------------------------------------------------------------------- @@ -457,7 +466,7 @@ public class TCKThaiBuddhistChronology { ThaiBuddhistDate mdate1 = ThaiBuddhistDate.of(1, 1, 1); ThaiBuddhistDate mdate2 = ThaiBuddhistDate.of(2, 2, 2); ChronoPeriod period = mdate1.until(mdate2); - assertEquals(period, ThaiBuddhistChronology.INSTANCE.period(1, 1, 1)); + assertEquals(ThaiBuddhistChronology.INSTANCE.period(1, 1, 1), period); } @Test @@ -465,7 +474,7 @@ public class TCKThaiBuddhistChronology { ThaiBuddhistDate mdate1 = ThaiBuddhistDate.of(1, 1, 1); ThaiBuddhistDate mdate2 = ThaiBuddhistDate.of(2, 2, 2); long months = mdate1.until(mdate2, ChronoUnit.MONTHS); - assertEquals(months, 13); + assertEquals(13, months); } @Test @@ -474,13 +483,12 @@ public class TCKThaiBuddhistChronology { ThaiBuddhistDate mdate2 = ThaiBuddhistDate.of(2, 2, 2); MinguoDate ldate2 = MinguoChronology.INSTANCE.date(mdate2); ChronoPeriod period = mdate1.until(ldate2); - assertEquals(period, ThaiBuddhistChronology.INSTANCE.period(1, 1, 1)); + assertEquals(ThaiBuddhistChronology.INSTANCE.period(1, 1, 1), period); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- - @DataProvider(name="toString") Object[][] data_toString() { return new Object[][] { {ThaiBuddhistChronology.INSTANCE.date(544, 1, 1), "ThaiBuddhist BE 544-01-01"}, @@ -491,9 +499,10 @@ public class TCKThaiBuddhistChronology { }; } - @Test(dataProvider="toString") + @ParameterizedTest + @MethodSource("data_toString") public void test_toString(ThaiBuddhistDate jdate, String expected) { - assertEquals(jdate.toString(), expected); + assertEquals(expected, jdate.toString()); } //----------------------------------------------------------------------- @@ -503,12 +512,12 @@ public class TCKThaiBuddhistChronology { public void test_Chrono_range() { long minYear = LocalDate.MIN.getYear() + YDIFF; long maxYear = LocalDate.MAX.getYear() + YDIFF; - assertEquals(ThaiBuddhistChronology.INSTANCE.range(YEAR), ValueRange.of(minYear, maxYear)); - assertEquals(ThaiBuddhistChronology.INSTANCE.range(YEAR_OF_ERA), ValueRange.of(1, -minYear + 1, maxYear)); + assertEquals(ValueRange.of(minYear, maxYear), ThaiBuddhistChronology.INSTANCE.range(YEAR)); + assertEquals(ValueRange.of(1, -minYear + 1, maxYear), ThaiBuddhistChronology.INSTANCE.range(YEAR_OF_ERA)); - assertEquals(ThaiBuddhistChronology.INSTANCE.range(DAY_OF_MONTH), DAY_OF_MONTH.range()); - assertEquals(ThaiBuddhistChronology.INSTANCE.range(DAY_OF_YEAR), DAY_OF_YEAR.range()); - assertEquals(ThaiBuddhistChronology.INSTANCE.range(MONTH_OF_YEAR), MONTH_OF_YEAR.range()); + assertEquals(DAY_OF_MONTH.range(), ThaiBuddhistChronology.INSTANCE.range(DAY_OF_MONTH)); + assertEquals(DAY_OF_YEAR.range(), ThaiBuddhistChronology.INSTANCE.range(DAY_OF_YEAR)); + assertEquals(MONTH_OF_YEAR.range(), ThaiBuddhistChronology.INSTANCE.range(MONTH_OF_YEAR)); } //----------------------------------------------------------------------- @@ -526,7 +535,6 @@ public class TCKThaiBuddhistChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_yearOfEra") Object[][] data_resolve_yearOfEra() { return new Object[][] { // era only @@ -591,7 +599,8 @@ public class TCKThaiBuddhistChronology { }; } - @Test(dataProvider = "resolve_yearOfEra") + @ParameterizedTest + @MethodSource("data_resolve_yearOfEra") public void test_resolve_yearOfEra(ResolverStyle style, Integer e, Integer yoe, Integer y, ChronoField field, Integer expected) { Map fieldValues = new HashMap<>(); if (e != null) { @@ -605,9 +614,9 @@ public class TCKThaiBuddhistChronology { } if (field != null) { ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, style); - assertEquals(date, null); - assertEquals(fieldValues.get(field), (Long) expected.longValue()); - assertEquals(fieldValues.size(), 1); + assertEquals(null, date); + assertEquals((Long) expected.longValue(), fieldValues.get(field)); + assertEquals(1, fieldValues.size()); } else { try { ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, style); @@ -620,7 +629,6 @@ public class TCKThaiBuddhistChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_ymd") Object[][] data_resolve_ymd() { return new Object[][] { {YDIFF + 2012, 1, -365, date(YDIFF + 2010, 12, 31), false, false}, @@ -679,18 +687,20 @@ public class TCKThaiBuddhistChronology { }; } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_lenient(int y, int m, int d, ThaiBuddhistDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.MONTH_OF_YEAR, (long) m); fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_smart(int y, int m, int d, ThaiBuddhistDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -698,11 +708,11 @@ public class TCKThaiBuddhistChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (Boolean.TRUE.equals(smart)) { ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else if (smart instanceof ThaiBuddhistDate) { ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, smart); + assertEquals(smart, date); } else { try { ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -713,7 +723,8 @@ public class TCKThaiBuddhistChronology { } } - @Test(dataProvider = "resolve_ymd") + @ParameterizedTest + @MethodSource("data_resolve_ymd") public void test_resolve_ymd_strict(int y, int m, int d, ThaiBuddhistDate expected, Object smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -721,8 +732,8 @@ public class TCKThaiBuddhistChronology { fieldValues.put(ChronoField.DAY_OF_MONTH, (long) d); if (strict) { ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); @@ -735,7 +746,6 @@ public class TCKThaiBuddhistChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_yd") Object[][] data_resolve_yd() { return new Object[][] { {YDIFF + 2012, -365, date(YDIFF + 2010, 12, 31), false, false}, @@ -763,25 +773,27 @@ public class TCKThaiBuddhistChronology { }; } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_lenient(int y, int d, ThaiBuddhistDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_smart(int y, int d, ThaiBuddhistDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); if (smart) { ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -792,15 +804,16 @@ public class TCKThaiBuddhistChronology { } } - @Test(dataProvider = "resolve_yd") + @ParameterizedTest + @MethodSource("data_resolve_yd") public void test_resolve_yd_strict(int y, int d, ThaiBuddhistDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); fieldValues.put(ChronoField.DAY_OF_YEAR, (long) d); if (strict) { ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); @@ -813,7 +826,6 @@ public class TCKThaiBuddhistChronology { //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "resolve_ymaa") Object[][] data_resolve_ymaa() { return new Object[][] { {YDIFF + 2012, 1, 1, -365, date(YDIFF + 2010, 12, 31), false, false}, @@ -870,7 +882,8 @@ public class TCKThaiBuddhistChronology { }; } - @Test(dataProvider = "resolve_ymaa") + @ParameterizedTest + @MethodSource("data_resolve_ymaa") public void test_resolve_ymaa_lenient(int y, int m, int w, int d, ThaiBuddhistDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -878,11 +891,12 @@ public class TCKThaiBuddhistChronology { fieldValues.put(ChronoField.ALIGNED_WEEK_OF_MONTH, (long) w); fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d); ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.LENIENT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } - @Test(dataProvider = "resolve_ymaa") + @ParameterizedTest + @MethodSource("data_resolve_ymaa") public void test_resolve_ymaa_smart(int y, int m, int w, int d, ThaiBuddhistDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -891,8 +905,8 @@ public class TCKThaiBuddhistChronology { fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d); if (smart) { ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.SMART); @@ -903,7 +917,8 @@ public class TCKThaiBuddhistChronology { } } - @Test(dataProvider = "resolve_ymaa") + @ParameterizedTest + @MethodSource("data_resolve_ymaa") public void test_resolve_ymaa_strict(int y, int m, int w, int d, ThaiBuddhistDate expected, boolean smart, boolean strict) { Map fieldValues = new HashMap<>(); fieldValues.put(ChronoField.YEAR, (long) y); @@ -912,8 +927,8 @@ public class TCKThaiBuddhistChronology { fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d); if (strict) { ThaiBuddhistDate date = ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); - assertEquals(date, expected); - assertEquals(fieldValues.size(), 0); + assertEquals(expected, date); + assertEquals(0, fieldValues.size()); } else { try { ThaiBuddhistChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT); diff --git a/test/jdk/java/time/tck/java/time/chrono/TCKThaiBuddhistEra.java b/test/jdk/java/time/tck/java/time/chrono/TCKThaiBuddhistEra.java index c4db30ccd72..d6585de716e 100644 --- a/test/jdk/java/time/tck/java/time/chrono/TCKThaiBuddhistEra.java +++ b/test/jdk/java/time/tck/java/time/chrono/TCKThaiBuddhistEra.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -55,8 +55,9 @@ package tck.java.time.chrono; import static java.time.temporal.ChronoField.ERA; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.chrono.Era; import java.time.chrono.ThaiBuddhistChronology; @@ -64,16 +65,17 @@ import java.time.chrono.ThaiBuddhistEra; import java.time.temporal.ValueRange; import java.util.List; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKThaiBuddhistEra { - @DataProvider(name = "ThaiBuddhistEras") Object[][] data_of_eras() { return new Object[][] { {ThaiBuddhistEra.BEFORE_BE, "BEFORE_BE", 0}, @@ -85,11 +87,12 @@ public class TCKThaiBuddhistEra { //----------------------------------------------------------------------- // valueOf() //----------------------------------------------------------------------- - @Test(dataProvider="ThaiBuddhistEras") + @ParameterizedTest + @MethodSource("data_of_eras") public void test_valueOf(ThaiBuddhistEra era , String eraName, int eraValue) { - assertEquals(era.getValue(), eraValue); - assertEquals(ThaiBuddhistEra.of(eraValue), era); - assertEquals(ThaiBuddhistEra.valueOf(eraName), era); + assertEquals(eraValue, era.getValue()); + assertEquals(era, ThaiBuddhistEra.of(eraValue)); + assertEquals(era, ThaiBuddhistEra.valueOf(eraName)); } //----------------------------------------------------------------------- @@ -99,7 +102,7 @@ public class TCKThaiBuddhistEra { public void test_values() { List eraList = ThaiBuddhistChronology.INSTANCE.eras(); ThaiBuddhistEra[] eras = ThaiBuddhistEra.values(); - assertEquals(eraList.size(), eras.length); + assertEquals(eras.length, eraList.size()); for (ThaiBuddhistEra era : eras) { assertTrue(eraList.contains(era)); } @@ -111,7 +114,7 @@ public class TCKThaiBuddhistEra { @Test public void test_range() { for (ThaiBuddhistEra era : ThaiBuddhistEra.values()) { - assertEquals(era.range(ERA), ValueRange.of(0, 1)); + assertEquals(ValueRange.of(0, 1), era.range(ERA)); } } diff --git a/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoLocalDateSerialization.java b/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoLocalDateSerialization.java index 8364d0137d8..42234f23f92 100644 --- a/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoLocalDateSerialization.java +++ b/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoLocalDateSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -69,17 +69,17 @@ import java.time.chrono.JapaneseEra; import java.time.chrono.MinguoDate; import java.time.chrono.ThaiBuddhistDate; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - - +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import tck.java.time.AbstractTCKTest; /** * Test serialization of built-in chronologies. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoLocalDateSerialization extends AbstractTCKTest { static final int CHRONO_TYPE = 1; // java.time.chrono.Ser.CHRONO_TYPE @@ -91,7 +91,6 @@ public class TCKChronoLocalDateSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Regular data factory for names and descriptions of available calendars //----------------------------------------------------------------------- - @DataProvider(name = "calendars") Object[][] data_of_calendars() { return new Object[][]{ {JapaneseDate.of(JapaneseEra.HEISEI, 25, 01, 05), JAPANESE_DATE_TYPE}, @@ -104,7 +103,8 @@ public class TCKChronoLocalDateSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Test Serialization of Calendars //----------------------------------------------------------------------- - @Test( dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_ChronoSerialization(ChronoLocalDate date, int dateType) throws Exception { assertSerializable(date); } @@ -112,8 +112,9 @@ public class TCKChronoLocalDateSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Test that serialization produces exact sequence of bytes //----------------------------------------------------------------------- - @Test(dataProvider="calendars") - private void test_serialization_format(ChronoLocalDate date, int dateType) throws Exception { + @ParameterizedTest + @MethodSource("data_of_calendars") + void test_serialization_format(ChronoLocalDate date, int dateType) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(baos) ) { dos.writeByte(dateType); @@ -164,7 +165,6 @@ public class TCKChronoLocalDateSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Regular data factory for names and descriptions of available calendars //----------------------------------------------------------------------- - @DataProvider(name = "invalidSerialformClasses") Object[][] invalid_serial_classes() { return new Object[][]{ {JapaneseEra.class}, @@ -175,7 +175,8 @@ public class TCKChronoLocalDateSerialization extends AbstractTCKTest { }; } - @Test(dataProvider="invalidSerialformClasses") + @ParameterizedTest + @MethodSource("invalid_serial_classes") public void test_invalid_serialform(Class clazz) throws Exception { assertNotSerializable(clazz); } diff --git a/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoLocalDateTimeSerialization.java b/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoLocalDateTimeSerialization.java index eb4e2cb6554..b3b987699c0 100644 --- a/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoLocalDateTimeSerialization.java +++ b/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoLocalDateTimeSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,8 +54,6 @@ */ package tck.java.time.chrono.serial; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.time.LocalDate; import java.time.LocalDateTime; @@ -67,18 +65,21 @@ import java.time.chrono.JapaneseChronology; import java.time.chrono.MinguoChronology; import java.time.chrono.ThaiBuddhistChronology; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import tck.java.time.AbstractTCKTest; /** * Test serialization of ChronoLocalDateTime for all built-in chronologies. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoLocalDateTimeSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // regular data factory for available calendars //----------------------------------------------------------------------- - @DataProvider(name = "calendars") Chronology[][] data_of_calendars() { return new Chronology[][]{ {HijrahChronology.INSTANCE}, @@ -91,7 +92,8 @@ public class TCKChronoLocalDateTimeSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Test Serialization of ChronoLocalDateTime //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_ChronoLocalDateTimeSerialization(Chronology chrono) throws Exception { LocalDateTime ref = LocalDate.of(2013, 1, 5).atTime(12, 1, 2, 3); ChronoLocalDateTime original = chrono.date(ref).atTime(ref.toLocalTime()); diff --git a/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoZonedDateTimeSerialization.java b/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoZonedDateTimeSerialization.java index bb76aa8e381..0c41e893f15 100644 --- a/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoZonedDateTimeSerialization.java +++ b/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronoZonedDateTimeSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -64,20 +64,22 @@ import java.time.chrono.IsoChronology; import java.time.chrono.JapaneseChronology; import java.time.chrono.MinguoChronology; import java.time.chrono.ThaiBuddhistChronology; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; + +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import tck.java.time.AbstractTCKTest; /** * Test assertions that must be true for all built-in chronologies. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoZonedDateTimeSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // regular data factory for names and descriptions of available calendars //----------------------------------------------------------------------- - @DataProvider(name = "calendars") Chronology[][] data_of_calendars() { return new Chronology[][]{ {HijrahChronology.INSTANCE}, @@ -91,7 +93,8 @@ public class TCKChronoZonedDateTimeSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Test Serialization of ISO via chrono API //----------------------------------------------------------------------- - @Test( dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_ChronoZonedDateTimeSerialization(Chronology chrono) throws Exception { ZonedDateTime ref = LocalDate.of(2013, 1, 5).atTime(12, 1, 2, 3).atZone(ZoneId.of("GMT+01:23")); ChronoZonedDateTime original = chrono.date(ref).atTime(ref.toLocalTime()).atZone(ref.getZone()); diff --git a/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronologySerialization.java b/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronologySerialization.java index 950c371c620..b615bcf3423 100644 --- a/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronologySerialization.java +++ b/test/jdk/java/time/tck/java/time/chrono/serial/TCKChronologySerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -64,12 +64,13 @@ import java.time.chrono.JapaneseChronology; import java.time.chrono.MinguoChronology; import java.time.chrono.ThaiBuddhistChronology; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import tck.java.time.AbstractTCKTest; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronologySerialization extends AbstractTCKTest { static final int CHRONO_TYPE = 1; // java.time.chrono.Ser.CHRONO_TYPE @@ -77,7 +78,6 @@ public class TCKChronologySerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Regular data factory for available calendars //----------------------------------------------------------------------- - @DataProvider(name = "calendars") Chronology[][] data_of_calendars() { return new Chronology[][]{ {HijrahChronology.INSTANCE}, @@ -90,7 +90,8 @@ public class TCKChronologySerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Test Serialization of Calendars //----------------------------------------------------------------------- - @Test(dataProvider="calendars") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_chronoSerialization(Chronology chrono) throws Exception { assertSerializable(chrono); } @@ -98,8 +99,9 @@ public class TCKChronologySerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Test that serialization produces exact sequence of bytes //----------------------------------------------------------------------- - @Test(dataProvider="calendars") - private void test_serializationBytes(Chronology chrono) throws Exception { + @ParameterizedTest + @MethodSource("data_of_calendars") + void test_serializationBytes(Chronology chrono) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(baos) ) { dos.writeByte(CHRONO_TYPE); @@ -113,7 +115,6 @@ public class TCKChronologySerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Regular data factory for names and descriptions of available calendars //----------------------------------------------------------------------- - @DataProvider(name = "invalidSerialformClasses") Object[][] invalid_serial_classes() { return new Object[][]{ {IsoChronology.class}, @@ -124,7 +125,8 @@ public class TCKChronologySerialization extends AbstractTCKTest { }; } - @Test(dataProvider="invalidSerialformClasses") + @ParameterizedTest + @MethodSource("invalid_serial_classes") public void test_invalid_serialform(Class clazz) throws Exception { assertNotSerializable(clazz); } diff --git a/test/jdk/java/time/tck/java/time/chrono/serial/TCKCopticSerialization.java b/test/jdk/java/time/tck/java/time/chrono/serial/TCKCopticSerialization.java index 0fc489ee27c..10fc8e970ad 100644 --- a/test/jdk/java/time/tck/java/time/chrono/serial/TCKCopticSerialization.java +++ b/test/jdk/java/time/tck/java/time/chrono/serial/TCKCopticSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -63,13 +63,13 @@ import java.io.IOException; import java.time.chrono.ChronoLocalDate; import java.time.chrono.Chronology; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; + import tck.java.time.AbstractTCKTest; /** * Tests the serialization of ChronoLocalDate using a CopticDate. */ -@Test public class TCKCopticSerialization extends AbstractTCKTest { @Test diff --git a/test/jdk/java/time/tck/java/time/chrono/serial/TCKEraSerialization.java b/test/jdk/java/time/tck/java/time/chrono/serial/TCKEraSerialization.java index 8df56baa8ef..55aa1d69667 100644 --- a/test/jdk/java/time/tck/java/time/chrono/serial/TCKEraSerialization.java +++ b/test/jdk/java/time/tck/java/time/chrono/serial/TCKEraSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -75,8 +75,10 @@ import java.time.chrono.JapaneseEra; import java.time.chrono.MinguoEra; import java.time.chrono.ThaiBuddhistEra; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import tck.java.time.AbstractTCKTest; @@ -87,7 +89,7 @@ import tck.java.time.AbstractTCKTest; * The serialized form of these types are not tested, only that they are * serializable. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKEraSerialization extends AbstractTCKTest { static final int JAPANESE_ERA_TYPE = 5; // java.time.chrono.Ser.JAPANESE_ERA @@ -96,7 +98,6 @@ public class TCKEraSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Regular data factory for the available Eras //----------------------------------------------------------------------- - @DataProvider(name = "Eras") Era[][] data_of_calendars() { return new Era[][] { {HijrahEra.AH}, @@ -109,7 +110,8 @@ public class TCKEraSerialization extends AbstractTCKTest { }; } - @Test(dataProvider="Eras") + @ParameterizedTest + @MethodSource("data_of_calendars") public void test_eraSerialization(Era era) throws IOException, ClassNotFoundException { assertSerializableSame(era); } @@ -118,7 +120,7 @@ public class TCKEraSerialization extends AbstractTCKTest { // Test JapaneseEra serialization produces exact sequence of bytes //----------------------------------------------------------------------- @Test - private void test_JapaneseErasSerialization() throws Exception { + void test_JapaneseErasSerialization() throws Exception { for (JapaneseEra era : JapaneseEra.values()) { assertSerializableSame(era); diff --git a/test/jdk/java/time/tck/java/time/format/TCKChronoPrinterParser.java b/test/jdk/java/time/tck/java/time/format/TCKChronoPrinterParser.java index 882bf9ccd44..427055fb8a1 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKChronoPrinterParser.java +++ b/test/jdk/java/time/tck/java/time/format/TCKChronoPrinterParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,7 +59,7 @@ */ package tck.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.ParsePosition; import java.time.chrono.Chronology; @@ -72,39 +72,41 @@ import java.time.temporal.TemporalQueries; import java.time.temporal.TemporalQuery; import java.util.Locale; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test formatter chrono. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoPrinterParser { // this test assumes ISO, ThaiBuddhist and Japanese are available private DateTimeFormatterBuilder builder; private ParsePosition pos; - @BeforeMethod + @BeforeEach public void setUp() { builder = new DateTimeFormatterBuilder(); pos = new ParsePosition(0); } //----------------------------------------------------------------------- - @Test(expectedExceptions=IndexOutOfBoundsException.class) + @Test public void test_parse_negativePosition() { - builder.appendChronologyId().toFormatter().parseUnresolved("ISO", new ParsePosition(-1)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> builder.appendChronologyId().toFormatter().parseUnresolved("ISO", new ParsePosition(-1))); } - @Test(expectedExceptions=IndexOutOfBoundsException.class) + @Test public void test_parse_offEndPosition() { - builder.appendChronologyId().toFormatter().parseUnresolved("ISO", new ParsePosition(4)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> builder.appendChronologyId().toFormatter().parseUnresolved("ISO", new ParsePosition(4))); } //----------------------------------------------------------------------- - @DataProvider(name="parseValid") Object[][] data_parseValid() { return new Object[][] { {"ISO", IsoChronology.INSTANCE}, @@ -117,35 +119,37 @@ public class TCKChronoPrinterParser { }; } - @Test(dataProvider="parseValid") + @ParameterizedTest + @MethodSource("data_parseValid") public void test_parseValid_caseSensitive(String text, Chronology expected) { builder.appendChronologyId(); TemporalAccessor parsed = builder.toFormatter().parseUnresolved(text, pos); - assertEquals(pos.getIndex(), expected.getId().length()); - assertEquals(pos.getErrorIndex(), -1); - assertEquals(parsed.query(TemporalQueries.chronology()), expected); + assertEquals(expected.getId().length(), pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); + assertEquals(expected, parsed.query(TemporalQueries.chronology())); } - @Test(dataProvider="parseValid") + @ParameterizedTest + @MethodSource("data_parseValid") public void test_parseValid_caseSensitive_lowercaseRejected(String text, Chronology expected) { builder.appendChronologyId(); TemporalAccessor parsed = builder.toFormatter().parseUnresolved(text.toLowerCase(Locale.ENGLISH), pos); - assertEquals(pos.getIndex(), 0); - assertEquals(pos.getErrorIndex(), 0); - assertEquals(parsed, null); + assertEquals(0, pos.getIndex()); + assertEquals(0, pos.getErrorIndex()); + assertEquals(null, parsed); } - @Test(dataProvider="parseValid") + @ParameterizedTest + @MethodSource("data_parseValid") public void test_parseValid_caseInsensitive(String text, Chronology expected) { builder.parseCaseInsensitive().appendChronologyId(); TemporalAccessor parsed = builder.toFormatter().parseUnresolved(text.toLowerCase(Locale.ENGLISH), pos); - assertEquals(pos.getIndex(), expected.getId().length()); - assertEquals(pos.getErrorIndex(), -1); - assertEquals(parsed.query(TemporalQueries.chronology()), expected); + assertEquals(expected.getId().length(), pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); + assertEquals(expected, parsed.query(TemporalQueries.chronology())); } //----------------------------------------------------------------------- - @DataProvider(name="parseInvalid") Object[][] data_parseInvalid() { return new Object[][] { {"Rubbish"}, @@ -155,13 +159,14 @@ public class TCKChronoPrinterParser { }; } - @Test(dataProvider="parseInvalid") + @ParameterizedTest + @MethodSource("data_parseInvalid") public void test_parseInvalid(String text) { builder.appendChronologyId(); TemporalAccessor parsed = builder.toFormatter().parseUnresolved(text, pos); - assertEquals(pos.getIndex(), 0); - assertEquals(pos.getErrorIndex(), 0); - assertEquals(parsed, null); + assertEquals(0, pos.getIndex()); + assertEquals(0, pos.getErrorIndex()); + assertEquals(null, parsed); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKDTFParsedInstant.java b/test/jdk/java/time/tck/java/time/format/TCKDTFParsedInstant.java index ec60f0f586d..d4d6a813a1e 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKDTFParsedInstant.java +++ b/test/jdk/java/time/tck/java/time/format/TCKDTFParsedInstant.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -22,7 +22,6 @@ */ package tck.java.time.format; -import static org.testng.AssertJUnit.assertEquals; import java.time.LocalDateTime; import java.time.OffsetDateTime; @@ -32,9 +31,11 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Testing DateTimeFormatter Parsing with 4 different test conditions: @@ -44,7 +45,7 @@ import org.testng.annotations.Test; * 4. When Zone is not provided and Offset is provided */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKDTFParsedInstant { private static final ZoneId EUROPE_BERLIN = ZoneId.of("Europe/Berlin"); @@ -55,12 +56,11 @@ public class TCKDTFParsedInstant { private LocalDateTime ldt1; private OffsetDateTime odt1; - @BeforeMethod + @BeforeEach public void setUp() throws Exception { dtFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; } - @DataProvider(name="parseWithoutZoneWithoutOffset") Object[][] data_parse_WithoutOffset_WithoutZone() { return new Object[][] { {"1966-12-31T00:01:10", LocalDateTime.of(1966, 12, 31, 0, 1, 10)}, @@ -70,14 +70,14 @@ public class TCKDTFParsedInstant { }; } - @Test(dataProvider="parseWithoutZoneWithoutOffset") + @ParameterizedTest + @MethodSource("data_parse_WithoutOffset_WithoutZone") public void testWithoutZoneWithoutOffset(String ldtString, LocalDateTime expectedLDT) { dtFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; ldt1 = LocalDateTime.parse(ldtString, dtFormatter); - assertEquals(expectedLDT, ldt1); + Assertions.assertEquals(expectedLDT, ldt1); } - @DataProvider(name="parseWithZoneWithOffset") Object[][] data_parse_WithZone_WithOffset() { return new Object[][] { {"2012-10-28T01:45:00-02:30[Europe/Berlin]", @@ -168,15 +168,15 @@ public class TCKDTFParsedInstant { }; } - @Test(dataProvider="parseWithZoneWithOffset") + @ParameterizedTest + @MethodSource("data_parse_WithZone_WithOffset") public void testWithZoneWithOffset(String zdtString, LocalDateTime ldt, ZoneOffset offset, ZoneId zone) { dtFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; zdt1 = ZonedDateTime.ofInstant(ldt, offset, zone); zdt2 = ZonedDateTime.parse(zdtString, dtFormatter); - assertEquals(zdt1, zdt2); + Assertions.assertEquals(zdt1, zdt2); } - @DataProvider(name="parseWithZoneWithoutOffset") Object[][] data_parse_WithZone_WithoutOffset() { return new Object[][] { {"28 Oct 00:45:00 2012 Europe/Berlin", ZonedDateTime.of(2012, 10, 28, 0, 45, 0, 0, EUROPE_BERLIN)}, @@ -193,14 +193,14 @@ public class TCKDTFParsedInstant { }; } - @Test(dataProvider="parseWithZoneWithoutOffset") + @ParameterizedTest + @MethodSource("data_parse_WithZone_WithoutOffset") public void testWithZoneWithoutOffset(String withZoneWithoutOffset, ZonedDateTime expectedZDT) { dtFormatter = DateTimeFormatter.ofPattern("d MMM HH:mm:ss uuuu VV").withLocale(Locale.ENGLISH); zdt1 = ZonedDateTime.parse(withZoneWithoutOffset, dtFormatter); - assertEquals(expectedZDT, zdt1); + Assertions.assertEquals(expectedZDT, zdt1); } - @DataProvider(name="parseWithOffsetWithoutZone") Object[][] data_parse_WithOffset_WithoutZone() { return new Object[][] { {"2015-12-14T00:45:00-11:30", OffsetDateTime.of(2015, 12, 14, 0, 45, 0, 0, ZoneOffset.of("-11:30"))}, @@ -212,10 +212,11 @@ public class TCKDTFParsedInstant { }; } - @Test(dataProvider="parseWithOffsetWithoutZone") + @ParameterizedTest + @MethodSource("data_parse_WithOffset_WithoutZone") public void testWithOffsetWithoutZone(String odtString, OffsetDateTime expectedOTD) { dtFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; odt1 = OffsetDateTime.parse(odtString, dtFormatter); - assertEquals(expectedOTD, odt1); + Assertions.assertEquals(expectedOTD, odt1); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatter.java b/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatter.java index 9c0a783ec53..c8a04c21154 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatter.java +++ b/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, 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 @@ -65,10 +65,11 @@ import static java.time.temporal.ChronoField.DAY_OF_YEAR; import static java.time.temporal.ChronoField.HOUR_OF_DAY; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.text.Format; import java.text.ParseException; @@ -105,14 +106,17 @@ import java.util.HashSet; import java.util.Locale; import java.util.Set; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatter. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKDateTimeFormatter { private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); @@ -124,7 +128,7 @@ public class TCKDateTimeFormatter { private DateTimeFormatter fmt; - @BeforeMethod + @BeforeEach public void setUp() { fmt = new DateTimeFormatterBuilder().appendLiteral("ONE") .appendValue(DAY_OF_MONTH, 1, 2, SignStyle.NOT_NEGATIVE) @@ -136,37 +140,39 @@ public class TCKDateTimeFormatter { public void test_withLocale() { DateTimeFormatter base = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); DateTimeFormatter test = base.withLocale(Locale.GERMAN); - assertEquals(test.getLocale(), Locale.GERMAN); + assertEquals(Locale.GERMAN, test.getLocale()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_withLocale_null() { - DateTimeFormatter base = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - base.withLocale((Locale) null); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter base = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + base.withLocale((Locale) null); + }); } //----------------------------------------------------------------------- @Test public void test_withChronology() { DateTimeFormatter test = fmt; - assertEquals(test.getChronology(), null); + assertEquals(null, test.getChronology()); test = test.withChronology(IsoChronology.INSTANCE); - assertEquals(test.getChronology(), IsoChronology.INSTANCE); + assertEquals(IsoChronology.INSTANCE, test.getChronology()); test = test.withChronology(null); - assertEquals(test.getChronology(), null); + assertEquals(null, test.getChronology()); } //----------------------------------------------------------------------- @Test public void test_withZone() { DateTimeFormatter test = fmt; - assertEquals(test.getZone(), null); + assertEquals(null, test.getZone()); test = test.withZone(ZoneId.of("Europe/Paris")); - assertEquals(test.getZone(), ZoneId.of("Europe/Paris")); + assertEquals(ZoneId.of("Europe/Paris"), test.getZone()); test = test.withZone(ZoneOffset.UTC); - assertEquals(test.getZone(), ZoneOffset.UTC); + assertEquals(ZoneOffset.UTC, test.getZone()); test = test.withZone(null); - assertEquals(test.getZone(), null); + assertEquals(null, test.getZone()); } //----------------------------------------------------------------------- @@ -183,7 +189,7 @@ public class TCKDateTimeFormatter { // expected, fails as it produces two different dates } LocalDate parsed = f.parse("2012-6-30-321", LocalDate::from); // ignored day-of-year - assertEquals(parsed, LocalDate.of(2012, 6, 30)); + assertEquals(LocalDate.of(2012, 6, 30), parsed); } @Test @@ -193,8 +199,7 @@ public class TCKDateTimeFormatter { .appendValue(DAY_OF_MONTH).appendLiteral('-').appendValue(DAY_OF_YEAR).toFormatter(); DateTimeFormatter f = base.withResolverFields(YEAR, DAY_OF_YEAR); Set expected = new HashSet<>(Arrays.asList(YEAR, DAY_OF_YEAR)); - // Use set.equals(); testNG comparison of Collections is ordered - assertTrue(f.getResolverFields().equals(expected), "ResolveFields: " + f.getResolverFields()); + assertEquals(expected, f.getResolverFields(), "ResolveFields: " + f.getResolverFields()); try { base.parse("2012-6-30-321", LocalDate::from); // wrong month/day-of-month fail(); @@ -202,7 +207,7 @@ public class TCKDateTimeFormatter { // expected, fails as it produces two different dates } LocalDate parsed = f.parse("2012-6-30-321", LocalDate::from); // ignored month/day-of-month - assertEquals(parsed, LocalDate.of(2012, 11, 16)); + assertEquals(LocalDate.of(2012, 11, 16), parsed); } @Test @@ -218,7 +223,7 @@ public class TCKDateTimeFormatter { // expected, should fail in cross-check of day-of-week } LocalDate parsed = f.parse("2012-321-1", LocalDate::from); // ignored wrong day-of-week - assertEquals(parsed, LocalDate.of(2012, 11, 16)); + assertEquals(LocalDate.of(2012, 11, 16), parsed); } @Test @@ -226,7 +231,7 @@ public class TCKDateTimeFormatter { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).toFormatter().withResolverFields(); TemporalAccessor parsed = f.parse("2012"); - assertEquals(parsed.isSupported(YEAR), false); // not in the list of resolverFields + assertEquals(false, parsed.isSupported(YEAR)); // not in the list of resolverFields } @Test @@ -234,7 +239,7 @@ public class TCKDateTimeFormatter { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).toFormatter().withResolverFields(YEAR); TemporalAccessor parsed = f.parse("2012"); - assertEquals(parsed.isSupported(YEAR), true); + assertEquals(true, parsed.isSupported(YEAR)); } @Test @@ -242,8 +247,8 @@ public class TCKDateTimeFormatter { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).toFormatter().withResolverFields(MONTH_OF_YEAR); TemporalAccessor parsed = f.parse("2012"); - assertEquals(parsed.isSupported(YEAR), false); // not in the list of resolverFields - assertEquals(parsed.isSupported(MONTH_OF_YEAR), false); + assertEquals(false, parsed.isSupported(YEAR)); // not in the list of resolverFields + assertEquals(false, parsed.isSupported(MONTH_OF_YEAR)); } @Test @@ -251,29 +256,28 @@ public class TCKDateTimeFormatter { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).toFormatter().withResolverFields((TemporalField) null); TemporalAccessor parsed = f.parse("2012"); - assertEquals(parsed.isSupported(YEAR), false); // not in the list of resolverFields + assertEquals(false, parsed.isSupported(YEAR)); // not in the list of resolverFields } @Test public void test_resolverFields_Array_null() throws Exception { DateTimeFormatter f = DateTimeFormatter.ISO_DATE.withResolverFields(MONTH_OF_YEAR); - assertEquals(f.getResolverFields().size(), 1); + assertEquals(1, f.getResolverFields().size()); f = f.withResolverFields((TemporalField[]) null); - assertEquals(f.getResolverFields(), null); + assertEquals(null, f.getResolverFields()); } @Test public void test_resolverFields_Set_null() throws Exception { DateTimeFormatter f = DateTimeFormatter.ISO_DATE.withResolverFields(MONTH_OF_YEAR); - assertEquals(f.getResolverFields().size(), 1); + assertEquals(1, f.getResolverFields().size()); f = f.withResolverFields((Set) null); - assertEquals(f.getResolverFields(), null); + assertEquals(null, f.getResolverFields()); } //----------------------------------------------------------------------- // format //----------------------------------------------------------------------- - @DataProvider(name="formatWithZoneWithChronology") Object[][] data_format_withZone_withChronology() { YearMonth ym = YearMonth.of(2008, 6); LocalDate ld = LocalDate.of(2008, 6, 30); @@ -351,7 +355,8 @@ public class TCKDateTimeFormatter { }; } - @Test(dataProvider="formatWithZoneWithChronology") + @ParameterizedTest + @MethodSource("data_format_withZone_withChronology") public void test_format_withZone_withChronology(Chronology overrideChrono, ZoneId overrideZone, TemporalAccessor temporal, String expected) { DateTimeFormatter test = new DateTimeFormatterBuilder() .optionalStart().appendValue(YEAR, 4).optionalEnd() @@ -363,7 +368,7 @@ public class TCKDateTimeFormatter { .withChronology(overrideChrono).withZone(overrideZone); if (expected != null) { String result = test.format(temporal); - assertEquals(result, expected); + assertEquals(expected, result); } else { try { test.format(temporal); @@ -394,7 +399,7 @@ public class TCKDateTimeFormatter { .toFormatter(Locale.ENGLISH) .withChronology(IsoChronology.INSTANCE); String result = test.format(temporal); - assertEquals(result, "2345"); + assertEquals("2345", result); } //----------------------------------------------------------------------- @@ -402,19 +407,23 @@ public class TCKDateTimeFormatter { public void test_format_TemporalAccessor_simple() { DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); String result = test.format(LocalDate.of(2008, 6, 30)); - assertEquals(result, "ONE30"); + assertEquals("ONE30", result); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_format_TemporalAccessor_noSuchField() { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.format(LocalTime.of(11, 30)); + Assertions.assertThrows(DateTimeException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.format(LocalTime.of(11, 30)); + }); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_format_TemporalAccessor_null() { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.format((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.format((TemporalAccessor) null); + }); } //----------------------------------------------------------------------- @@ -423,27 +432,33 @@ public class TCKDateTimeFormatter { DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); StringBuilder buf = new StringBuilder(); test.formatTo(LocalDate.of(2008, 6, 30), buf); - assertEquals(buf.toString(), "ONE30"); + assertEquals("ONE30", buf.toString()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_TemporalAppendable_noSuchField() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - StringBuilder buf = new StringBuilder(); - test.formatTo(LocalTime.of(11, 30), buf); + Assertions.assertThrows(DateTimeException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + StringBuilder buf = new StringBuilder(); + test.formatTo(LocalTime.of(11, 30), buf); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_print_TemporalAppendable_nullTemporal() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - StringBuilder buf = new StringBuilder(); - test.formatTo((TemporalAccessor) null, buf); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + StringBuilder buf = new StringBuilder(); + test.formatTo((TemporalAccessor) null, buf); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_print_TemporalAppendable_nullAppendable() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.formatTo(LocalDate.of(2008, 6, 30), (Appendable) null); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.formatTo(LocalDate.of(2008, 6, 30), (Appendable) null); + }); } //----------------------------------------------------------------------- @@ -453,29 +468,31 @@ public class TCKDateTimeFormatter { public void test_parse_CharSequence() { DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); TemporalAccessor result = test.parse("ONE30"); - assertEquals(result.isSupported(DAY_OF_MONTH), true); - assertEquals(result.getLong(DAY_OF_MONTH), 30L); - assertEquals(result.isSupported(HOUR_OF_DAY), false); + assertEquals(true, result.isSupported(DAY_OF_MONTH)); + assertEquals(30L, result.getLong(DAY_OF_MONTH)); + assertEquals(false, result.isSupported(HOUR_OF_DAY)); } @Test public void test_parse_CharSequence_resolved() { DateTimeFormatter test = DateTimeFormatter.ISO_DATE; TemporalAccessor result = test.parse("2012-06-30"); - assertEquals(result.isSupported(YEAR), true); - assertEquals(result.isSupported(MONTH_OF_YEAR), true); - assertEquals(result.isSupported(DAY_OF_MONTH), true); - assertEquals(result.isSupported(HOUR_OF_DAY), false); - assertEquals(result.getLong(YEAR), 2012L); - assertEquals(result.getLong(MONTH_OF_YEAR), 6L); - assertEquals(result.getLong(DAY_OF_MONTH), 30L); - assertEquals(result.query(LocalDate::from), LocalDate.of(2012, 6, 30)); + assertEquals(true, result.isSupported(YEAR)); + assertEquals(true, result.isSupported(MONTH_OF_YEAR)); + assertEquals(true, result.isSupported(DAY_OF_MONTH)); + assertEquals(false, result.isSupported(HOUR_OF_DAY)); + assertEquals(2012L, result.getLong(YEAR)); + assertEquals(6L, result.getLong(MONTH_OF_YEAR)); + assertEquals(30L, result.getLong(DAY_OF_MONTH)); + assertEquals(LocalDate.of(2012, 6, 30), result.query(LocalDate::from)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_parse_CharSequence_null() { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.parse((String) null); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.parse((String) null); + }); } //----------------------------------------------------------------------- @@ -486,11 +503,11 @@ public class TCKDateTimeFormatter { DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); ParsePosition pos = new ParsePosition(3); TemporalAccessor result = test.parse("XXXONE30XXX", pos); - assertEquals(pos.getIndex(), 8); - assertEquals(pos.getErrorIndex(), -1); - assertEquals(result.isSupported(DAY_OF_MONTH), true); - assertEquals(result.getLong(DAY_OF_MONTH), 30L); - assertEquals(result.isSupported(HOUR_OF_DAY), false); + assertEquals(8, pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); + assertEquals(true, result.isSupported(DAY_OF_MONTH)); + assertEquals(30L, result.getLong(DAY_OF_MONTH)); + assertEquals(false, result.isSupported(HOUR_OF_DAY)); } @Test @@ -498,47 +515,55 @@ public class TCKDateTimeFormatter { DateTimeFormatter test = DateTimeFormatter.ISO_DATE; ParsePosition pos = new ParsePosition(3); TemporalAccessor result = test.parse("XXX2012-06-30XXX", pos); - assertEquals(pos.getIndex(), 13); - assertEquals(pos.getErrorIndex(), -1); - assertEquals(result.isSupported(YEAR), true); - assertEquals(result.isSupported(MONTH_OF_YEAR), true); - assertEquals(result.isSupported(DAY_OF_MONTH), true); - assertEquals(result.isSupported(HOUR_OF_DAY), false); - assertEquals(result.getLong(YEAR), 2012L); - assertEquals(result.getLong(MONTH_OF_YEAR), 6L); - assertEquals(result.getLong(DAY_OF_MONTH), 30L); - assertEquals(result.query(LocalDate::from), LocalDate.of(2012, 6, 30)); + assertEquals(13, pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); + assertEquals(true, result.isSupported(YEAR)); + assertEquals(true, result.isSupported(MONTH_OF_YEAR)); + assertEquals(true, result.isSupported(DAY_OF_MONTH)); + assertEquals(false, result.isSupported(HOUR_OF_DAY)); + assertEquals(2012L, result.getLong(YEAR)); + assertEquals(6L, result.getLong(MONTH_OF_YEAR)); + assertEquals(30L, result.getLong(DAY_OF_MONTH)); + assertEquals(LocalDate.of(2012, 6, 30), result.query(LocalDate::from)); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_parse_CharSequence_ParsePosition_parseError() { - DateTimeFormatter test = DateTimeFormatter.ISO_DATE; - ParsePosition pos = new ParsePosition(3); - try { - test.parse("XXX2012XXX", pos); - fail(); - } catch (DateTimeParseException ex) { - assertEquals(ex.getErrorIndex(), 7); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + DateTimeFormatter test = DateTimeFormatter.ISO_DATE; + ParsePosition pos = new ParsePosition(3); + try { + test.parse("XXX2012XXX", pos); + fail(); + } catch (DateTimeParseException ex) { + assertEquals(7, ex.getErrorIndex()); + throw ex; + } + }); } - @Test(expectedExceptions=IndexOutOfBoundsException.class) + @Test public void test_parse_CharSequence_ParsePosition_indexTooBig() { - DateTimeFormatter test = DateTimeFormatter.ISO_DATE; - test.parse("Text", new ParsePosition(5)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { + DateTimeFormatter test = DateTimeFormatter.ISO_DATE; + test.parse("Text", new ParsePosition(5)); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_parse_CharSequence_ParsePosition_nullText() { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.parse((CharSequence) null, new ParsePosition(0)); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.parse((CharSequence) null, new ParsePosition(0)); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_parse_CharSequence_ParsePosition_nullParsePosition() { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.parse("Text", (ParsePosition) null); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.parse("Text", (ParsePosition) null); + }); } //----------------------------------------------------------------------- @@ -547,63 +572,71 @@ public class TCKDateTimeFormatter { @Test public void test_parse_Query_String() throws Exception { LocalDate result = DATE_FORMATTER.parse("ONE2012 07 27", LocalDate::from); - assertEquals(result, LocalDate.of(2012, 7, 27)); + assertEquals(LocalDate.of(2012, 7, 27), result); } @Test public void test_parse_Query_CharSequence() throws Exception { LocalDate result = DATE_FORMATTER.parse(new StringBuilder("ONE2012 07 27"), LocalDate::from); - assertEquals(result, LocalDate.of(2012, 7, 27)); + assertEquals(LocalDate.of(2012, 7, 27), result); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_parse_Query_String_parseError() throws Exception { - try { - DATE_FORMATTER.parse("ONE2012 07 XX", LocalDate::from); - } catch (DateTimeParseException ex) { - assertEquals(ex.getMessage().contains("could not be parsed"), true); - assertEquals(ex.getMessage().contains("ONE2012 07 XX"), true); - assertEquals(ex.getParsedString(), "ONE2012 07 XX"); - assertEquals(ex.getErrorIndex(), 11); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + try { + DATE_FORMATTER.parse("ONE2012 07 XX", LocalDate::from); + } catch (DateTimeParseException ex) { + assertEquals(true, ex.getMessage().contains("could not be parsed")); + assertEquals(true, ex.getMessage().contains("ONE2012 07 XX")); + assertEquals("ONE2012 07 XX", ex.getParsedString()); + assertEquals(11, ex.getErrorIndex()); + throw ex; + } + }); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_parse_Query_String_parseErrorLongText() throws Exception { - try { - DATE_FORMATTER.parse("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789", LocalDate::from); - } catch (DateTimeParseException ex) { - assertEquals(ex.getMessage().contains("could not be parsed"), true); - assertEquals(ex.getMessage().contains("ONEXXX6789012345678901234567890123456789012345678901234567890123..."), true); - assertEquals(ex.getParsedString(), "ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789"); - assertEquals(ex.getErrorIndex(), 3); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + try { + DATE_FORMATTER.parse("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789", LocalDate::from); + } catch (DateTimeParseException ex) { + assertEquals(true, ex.getMessage().contains("could not be parsed")); + assertEquals(true, ex.getMessage().contains("ONEXXX6789012345678901234567890123456789012345678901234567890123...")); + assertEquals("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789", ex.getParsedString()); + assertEquals(3, ex.getErrorIndex()); + throw ex; + } + }); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_parse_Query_String_parseIncomplete() throws Exception { - try { - DATE_FORMATTER.parse("ONE2012 07 27SomethingElse", LocalDate::from); - } catch (DateTimeParseException ex) { - assertEquals(ex.getMessage().contains("could not be parsed"), true); - assertEquals(ex.getMessage().contains("ONE2012 07 27SomethingElse"), true); - assertEquals(ex.getParsedString(), "ONE2012 07 27SomethingElse"); - assertEquals(ex.getErrorIndex(), 13); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + try { + DATE_FORMATTER.parse("ONE2012 07 27SomethingElse", LocalDate::from); + } catch (DateTimeParseException ex) { + assertEquals(true, ex.getMessage().contains("could not be parsed")); + assertEquals(true, ex.getMessage().contains("ONE2012 07 27SomethingElse")); + assertEquals("ONE2012 07 27SomethingElse", ex.getParsedString()); + assertEquals(13, ex.getErrorIndex()); + throw ex; + } + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_parse_Query_String_nullText() throws Exception { - DATE_FORMATTER.parse((String) null, LocalDate::from); + Assertions.assertThrows(NullPointerException.class, () -> DATE_FORMATTER.parse((String) null, LocalDate::from)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_parse_Query_String_nullRule() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.parse("30", (TemporalQuery) null); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.parse("30", (TemporalQuery) null); + }); } //----------------------------------------------------------------------- @@ -612,80 +645,94 @@ public class TCKDateTimeFormatter { DateTimeFormatter test = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm[XXX]"); TemporalAccessor result = test.parseBest("2011-06-30 12:30+03:00", ZonedDateTime::from, LocalDateTime::from); LocalDateTime ldt = LocalDateTime.of(2011, 6, 30, 12, 30); - assertEquals(result, ZonedDateTime.of(ldt, ZoneOffset.ofHours(3))); + assertEquals(ZonedDateTime.of(ldt, ZoneOffset.ofHours(3)), result); } @Test public void test_parseBest_secondOption() throws Exception { DateTimeFormatter test = DateTimeFormatter.ofPattern("yyyy-MM-dd[ HH:mm[XXX]]"); TemporalAccessor result = test.parseBest("2011-06-30", ZonedDateTime::from, LocalDate::from); - assertEquals(result, LocalDate.of(2011, 6, 30)); + assertEquals(LocalDate.of(2011, 6, 30), result); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_parseBest_String_parseError() throws Exception { - DateTimeFormatter test = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm[XXX]"); - try { - test.parseBest("2011-06-XX", ZonedDateTime::from, LocalDateTime::from); - } catch (DateTimeParseException ex) { - assertEquals(ex.getMessage().contains("could not be parsed"), true); - assertEquals(ex.getMessage().contains("XX"), true); - assertEquals(ex.getParsedString(), "2011-06-XX"); - assertEquals(ex.getErrorIndex(), 8); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + DateTimeFormatter test = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm[XXX]"); + try { + test.parseBest("2011-06-XX", ZonedDateTime::from, LocalDateTime::from); + } catch (DateTimeParseException ex) { + assertEquals(true, ex.getMessage().contains("could not be parsed")); + assertEquals(true, ex.getMessage().contains("XX")); + assertEquals("2011-06-XX", ex.getParsedString()); + assertEquals(8, ex.getErrorIndex()); + throw ex; + } + }); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_parseBest_String_parseErrorLongText() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - try { - test.parseBest("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789", ZonedDateTime::from, LocalDate::from); - } catch (DateTimeParseException ex) { - assertEquals(ex.getMessage().contains("could not be parsed"), true); - assertEquals(ex.getMessage().contains("ONEXXX6789012345678901234567890123456789012345678901234567890123..."), true); - assertEquals(ex.getParsedString(), "ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789"); - assertEquals(ex.getErrorIndex(), 3); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + try { + test.parseBest("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789", ZonedDateTime::from, LocalDate::from); + } catch (DateTimeParseException ex) { + assertEquals(true, ex.getMessage().contains("could not be parsed")); + assertEquals(true, ex.getMessage().contains("ONEXXX6789012345678901234567890123456789012345678901234567890123...")); + assertEquals("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789", ex.getParsedString()); + assertEquals(3, ex.getErrorIndex()); + throw ex; + } + }); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_parseBest_String_parseIncomplete() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - try { - test.parseBest("ONE30SomethingElse", ZonedDateTime::from, LocalDate::from); - } catch (DateTimeParseException ex) { - assertEquals(ex.getMessage().contains("could not be parsed"), true); - assertEquals(ex.getMessage().contains("ONE30SomethingElse"), true); - assertEquals(ex.getParsedString(), "ONE30SomethingElse"); - assertEquals(ex.getErrorIndex(), 5); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + try { + test.parseBest("ONE30SomethingElse", ZonedDateTime::from, LocalDate::from); + } catch (DateTimeParseException ex) { + assertEquals(true, ex.getMessage().contains("could not be parsed")); + assertEquals(true, ex.getMessage().contains("ONE30SomethingElse")); + assertEquals("ONE30SomethingElse", ex.getParsedString()); + assertEquals(5, ex.getErrorIndex()); + throw ex; + } + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_parseBest_String_nullText() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.parseBest((String) null, ZonedDateTime::from, LocalDate::from); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.parseBest((String) null, ZonedDateTime::from, LocalDate::from); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_parseBest_String_nullRules() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.parseBest("30", (TemporalQuery[]) null); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.parseBest("30", (TemporalQuery[]) null); + }); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_parseBest_String_zeroRules() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.parseBest("30", new TemporalQuery[0]); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.parseBest("30", new TemporalQuery[0]); + }); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_parseBest_String_oneRule() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.parseBest("30", LocalDate::from); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.parseBest("30", LocalDate::from); + }); } //----------------------------------------------------------------------- @@ -694,9 +741,9 @@ public class TCKDateTimeFormatter { DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); ParsePosition pos = new ParsePosition(0); TemporalAccessor result = test.parseUnresolved("ONE30XXX", pos); - assertEquals(pos.getIndex(), 5); - assertEquals(pos.getErrorIndex(), -1); - assertEquals(result.getLong(DAY_OF_MONTH), 30L); + assertEquals(5, pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); + assertEquals(30L, result.getLong(DAY_OF_MONTH)); } @Test @@ -704,9 +751,9 @@ public class TCKDateTimeFormatter { DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); ParsePosition pos = new ParsePosition(0); TemporalAccessor result = test.parseUnresolved("ONEXXX", pos); - assertEquals(pos.getIndex(), 0); - assertEquals(pos.getErrorIndex(), 3); - assertEquals(result, null); + assertEquals(0, pos.getIndex()); + assertEquals(3, pos.getErrorIndex()); + assertEquals(null, result); } @Test @@ -715,9 +762,9 @@ public class TCKDateTimeFormatter { .appendValue(MONTH_OF_YEAR).appendLiteral('-').appendValue(MONTH_OF_YEAR).toFormatter(); ParsePosition pos = new ParsePosition(3); TemporalAccessor result = test.parseUnresolved("XXX6-6", pos); - assertEquals(pos.getIndex(), 6); - assertEquals(pos.getErrorIndex(), -1); - assertEquals(result.getLong(MONTH_OF_YEAR), 6); + assertEquals(6, pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); + assertEquals(6, result.getLong(MONTH_OF_YEAR)); } @Test @@ -726,29 +773,35 @@ public class TCKDateTimeFormatter { .appendValue(MONTH_OF_YEAR).appendLiteral('-').appendValue(MONTH_OF_YEAR).toFormatter(); ParsePosition pos = new ParsePosition(3); TemporalAccessor result = test.parseUnresolved("XXX6-7", pos); - assertEquals(pos.getIndex(), 3); - assertEquals(pos.getErrorIndex(), 5); - assertEquals(result, null); + assertEquals(3, pos.getIndex()); + assertEquals(5, pos.getErrorIndex()); + assertEquals(null, result); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_parseUnresolved_StringParsePosition_nullString() { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - ParsePosition pos = new ParsePosition(0); - test.parseUnresolved((String) null, pos); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + ParsePosition pos = new ParsePosition(0); + test.parseUnresolved((String) null, pos); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_parseUnresolved_StringParsePosition_nullParsePosition() { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - test.parseUnresolved("ONE30", (ParsePosition) null); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + test.parseUnresolved("ONE30", (ParsePosition) null); + }); } - @Test(expectedExceptions=IndexOutOfBoundsException.class) + @Test public void test_parseUnresolved_StringParsePosition_invalidPosition() { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - ParsePosition pos = new ParsePosition(6); - test.parseUnresolved("ONE30", pos); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + ParsePosition pos = new ParsePosition(6); + test.parseUnresolved("ONE30", pos); + }); } //----------------------------------------------------------------------- @@ -758,21 +811,25 @@ public class TCKDateTimeFormatter { DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); Format format = test.toFormat(); String result = format.format(LocalDate.of(2008, 6, 30)); - assertEquals(result, "ONE30"); + assertEquals("ONE30", result); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_toFormat_format_null() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - Format format = test.toFormat(); - format.format(null); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + Format format = test.toFormat(); + format.format(null); + }); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_toFormat_format_notTemporal() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - Format format = test.toFormat(); - format.format("Not a Temporal"); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + Format format = test.toFormat(); + format.format("Not a Temporal"); + }); } //----------------------------------------------------------------------- @@ -781,42 +838,48 @@ public class TCKDateTimeFormatter { DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); Format format = test.toFormat(); TemporalAccessor result = (TemporalAccessor) format.parseObject("ONE30"); - assertEquals(result.isSupported(DAY_OF_MONTH), true); - assertEquals(result.getLong(DAY_OF_MONTH), 30L); + assertEquals(true, result.isSupported(DAY_OF_MONTH)); + assertEquals(30L, result.getLong(DAY_OF_MONTH)); } - @Test(expectedExceptions=ParseException.class) + @Test public void test_toFormat_parseObject_String_parseError() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - Format format = test.toFormat(); - try { - format.parseObject("ONEXXX"); - } catch (ParseException ex) { - assertEquals(ex.getMessage().contains("ONEXXX"), true); - assertEquals(ex.getErrorOffset(), 3); - throw ex; - } + Assertions.assertThrows(ParseException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + Format format = test.toFormat(); + try { + format.parseObject("ONEXXX"); + } catch (ParseException ex) { + assertEquals(true, ex.getMessage().contains("ONEXXX")); + assertEquals(3, ex.getErrorOffset()); + throw ex; + } + }); } - @Test(expectedExceptions=ParseException.class) + @Test public void test_toFormat_parseObject_String_parseErrorLongText() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - Format format = test.toFormat(); - try { - format.parseObject("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789"); - } catch (DateTimeParseException ex) { - assertEquals(ex.getMessage().contains("ONEXXX6789012345678901234567890123456789012345678901234567890123..."), true); - assertEquals(ex.getParsedString(), "ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789"); - assertEquals(ex.getErrorIndex(), 3); - throw ex; - } + Assertions.assertThrows(ParseException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + Format format = test.toFormat(); + try { + format.parseObject("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789"); + } catch (DateTimeParseException ex) { + assertEquals(true, ex.getMessage().contains("ONEXXX6789012345678901234567890123456789012345678901234567890123...")); + assertEquals("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789", ex.getParsedString()); + assertEquals(3, ex.getErrorIndex()); + throw ex; + } + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_toFormat_parseObject_String_null() throws Exception { - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - Format format = test.toFormat(); - format.parseObject((String) null); + Assertions.assertThrows(NullPointerException.class, () -> { + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + Format format = test.toFormat(); + format.parseObject((String) null); + }); } //----------------------------------------------------------------------- @@ -826,10 +889,10 @@ public class TCKDateTimeFormatter { Format format = test.toFormat(); ParsePosition pos = new ParsePosition(0); TemporalAccessor result = (TemporalAccessor) format.parseObject("ONE30XXX", pos); - assertEquals(pos.getIndex(), 5); - assertEquals(pos.getErrorIndex(), -1); - assertEquals(result.isSupported(DAY_OF_MONTH), true); - assertEquals(result.getLong(DAY_OF_MONTH), 30L); + assertEquals(5, pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); + assertEquals(true, result.isSupported(DAY_OF_MONTH)); + assertEquals(30L, result.getLong(DAY_OF_MONTH)); } @Test @@ -838,26 +901,30 @@ public class TCKDateTimeFormatter { Format format = test.toFormat(); ParsePosition pos = new ParsePosition(0); TemporalAccessor result = (TemporalAccessor) format.parseObject("ONEXXX", pos); - assertEquals(pos.getIndex(), 0); // TODO: is this right? - assertEquals(pos.getErrorIndex(), 3); - assertEquals(result, null); + assertEquals(0, pos.getIndex()); // TODO: is this right? + assertEquals(3, pos.getErrorIndex()); + assertEquals(null, result); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_toFormat_parseObject_StringParsePosition_nullString() throws Exception { - // SimpleDateFormat has this behavior - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - Format format = test.toFormat(); - ParsePosition pos = new ParsePosition(0); - format.parseObject((String) null, pos); + Assertions.assertThrows(NullPointerException.class, () -> { + // SimpleDateFormat has this behavior + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + Format format = test.toFormat(); + ParsePosition pos = new ParsePosition(0); + format.parseObject((String) null, pos); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_toFormat_parseObject_StringParsePosition_nullParsePosition() throws Exception { - // SimpleDateFormat has this behavior - DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); - Format format = test.toFormat(); - format.parseObject("ONE30", (ParsePosition) null); + Assertions.assertThrows(NullPointerException.class, () -> { + // SimpleDateFormat has this behavior + DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD); + Format format = test.toFormat(); + format.parseObject("ONE30", (ParsePosition) null); + }); } @Test @@ -885,25 +952,27 @@ public class TCKDateTimeFormatter { public void test_toFormat_Query_format() throws Exception { Format format = BASIC_FORMATTER.toFormat(); String result = format.format(LocalDate.of(2008, 6, 30)); - assertEquals(result, "ONE30"); + assertEquals("ONE30", result); } @Test public void test_toFormat_Query_parseObject_String() throws Exception { Format format = DATE_FORMATTER.toFormat(LocalDate::from); LocalDate result = (LocalDate) format.parseObject("ONE2012 07 27"); - assertEquals(result, LocalDate.of(2012, 7, 27)); + assertEquals(LocalDate.of(2012, 7, 27), result); } - @Test(expectedExceptions=ParseException.class) + @Test public void test_toFormat_parseObject_StringParsePosition_dateTimeError() throws Exception { - Format format = DATE_FORMATTER.toFormat(LocalDate::from); - format.parseObject("ONE2012 07 32"); + Assertions.assertThrows(ParseException.class, () -> { + Format format = DATE_FORMATTER.toFormat(LocalDate::from); + format.parseObject("ONE2012 07 32"); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_toFormat_Query() throws Exception { - BASIC_FORMATTER.toFormat(null); + Assertions.assertThrows(NullPointerException.class, () -> BASIC_FORMATTER.toFormat(null)); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java b/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java index b02cc8c0134..2c18d1fb5c2 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java +++ b/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -67,7 +67,8 @@ import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.NANO_OF_SECOND; import static java.time.temporal.ChronoField.OFFSET_SECONDS; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.ParsePosition; import java.time.LocalDate; @@ -89,19 +90,22 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatterBuilder. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKDateTimeFormatterBuilder { private DateTimeFormatterBuilder builder; - @BeforeMethod + @BeforeEach public void setUp() { builder = new DateTimeFormatterBuilder(); } @@ -110,7 +114,7 @@ public class TCKDateTimeFormatterBuilder { @Test public void test_toFormatter_empty() throws Exception { DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.format(LocalDate.of(2012, 6, 30)), ""); + assertEquals("", f.format(LocalDate.of(2012, 6, 30))); } //----------------------------------------------------------------------- @@ -120,7 +124,7 @@ public class TCKDateTimeFormatterBuilder { .parseDefaulting(YEAR, 2012).parseDefaulting(MONTH_OF_YEAR, 6) .parseDefaulting(DAY_OF_MONTH, 30).toFormatter(); LocalDate parsed = f.parse("", LocalDate::from); // blank string can be parsed - assertEquals(parsed, LocalDate.of(2012, 6, 30)); + assertEquals(LocalDate.of(2012, 6, 30), parsed); } @Test @@ -132,213 +136,212 @@ public class TCKDateTimeFormatterBuilder { .optionalEnd().optionalEnd() .parseDefaulting(MONTH_OF_YEAR, 1) .parseDefaulting(DAY_OF_MONTH, 1).toFormatter(); - assertEquals(f.parse("2012", LocalDate::from), LocalDate.of(2012, 1, 1)); - assertEquals(f.parse("2012-6", LocalDate::from), LocalDate.of(2012, 6, 1)); - assertEquals(f.parse("2012-6-30", LocalDate::from), LocalDate.of(2012, 6, 30)); + assertEquals(LocalDate.of(2012, 1, 1), f.parse("2012", LocalDate::from)); + assertEquals(LocalDate.of(2012, 6, 1), f.parse("2012-6", LocalDate::from)); + assertEquals(LocalDate.of(2012, 6, 30), f.parse("2012-6-30", LocalDate::from)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void test_parseDefaulting_null() { - builder.parseDefaulting(null, 1); + Assertions.assertThrows(NullPointerException.class, () -> builder.parseDefaulting(null, 1)); } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValue_1arg_null() throws Exception { - builder.appendValue(null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValue(null)); } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValue_2arg_null() throws Exception { - builder.appendValue(null, 3); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValue(null, 3)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_2arg_widthTooSmall() throws Exception { - builder.appendValue(DAY_OF_MONTH, 0); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 0)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_2arg_widthTooBig() throws Exception { - builder.appendValue(DAY_OF_MONTH, 20); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 20)); } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValue_3arg_nullField() throws Exception { - builder.appendValue(null, 2, 3, SignStyle.NORMAL); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValue(null, 2, 3, SignStyle.NORMAL)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_3arg_minWidthTooSmall() throws Exception { - builder.appendValue(DAY_OF_MONTH, 0, 2, SignStyle.NORMAL); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 0, 2, SignStyle.NORMAL)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_3arg_minWidthTooBig() throws Exception { - builder.appendValue(DAY_OF_MONTH, 20, 2, SignStyle.NORMAL); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 20, 2, SignStyle.NORMAL)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_3arg_maxWidthTooSmall() throws Exception { - builder.appendValue(DAY_OF_MONTH, 2, 0, SignStyle.NORMAL); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 2, 0, SignStyle.NORMAL)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_3arg_maxWidthTooBig() throws Exception { - builder.appendValue(DAY_OF_MONTH, 2, 20, SignStyle.NORMAL); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 2, 20, SignStyle.NORMAL)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_3arg_maxWidthMinWidth() throws Exception { - builder.appendValue(DAY_OF_MONTH, 4, 2, SignStyle.NORMAL); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 4, 2, SignStyle.NORMAL)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValue_3arg_nullSignStyle() throws Exception { - builder.appendValue(DAY_OF_MONTH, 2, 3, null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValue(DAY_OF_MONTH, 2, 3, null)); } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValueReduced_int_nullField() throws Exception { - builder.appendValueReduced(null, 2, 2, 2000); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValueReduced(null, 2, 2, 2000)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValueReduced_int_minWidthTooSmall() throws Exception { - builder.appendValueReduced(YEAR, 0, 2, 2000); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValueReduced(YEAR, 0, 2, 2000)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValueReduced_int_minWidthTooBig() throws Exception { - builder.appendValueReduced(YEAR, 11, 2, 2000); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValueReduced(YEAR, 11, 2, 2000)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValueReduced_int_maxWidthTooSmall() throws Exception { - builder.appendValueReduced(YEAR, 2, 0, 2000); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValueReduced(YEAR, 2, 0, 2000)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValueReduced_int_maxWidthTooBig() throws Exception { - builder.appendValueReduced(YEAR, 2, 11, 2000); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValueReduced(YEAR, 2, 11, 2000)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValueReduced_int_maxWidthLessThanMin() throws Exception { - builder.appendValueReduced(YEAR, 2, 1, 2000); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValueReduced(YEAR, 2, 1, 2000)); } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValueReduced_date_nullField() throws Exception { - builder.appendValueReduced(null, 2, 2, LocalDate.of(2000, 1, 1)); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValueReduced(null, 2, 2, LocalDate.of(2000, 1, 1))); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValueReduced_date_nullDate() throws Exception { - builder.appendValueReduced(YEAR, 2, 2, null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValueReduced(YEAR, 2, 2, null)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValueReduced_date_minWidthTooSmall() throws Exception { - builder.appendValueReduced(YEAR, 0, 2, LocalDate.of(2000, 1, 1)); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValueReduced(YEAR, 0, 2, LocalDate.of(2000, 1, 1))); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValueReduced_date_minWidthTooBig() throws Exception { - builder.appendValueReduced(YEAR, 11, 2, LocalDate.of(2000, 1, 1)); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValueReduced(YEAR, 11, 2, LocalDate.of(2000, 1, 1))); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValueReduced_date_maxWidthTooSmall() throws Exception { - builder.appendValueReduced(YEAR, 2, 0, LocalDate.of(2000, 1, 1)); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValueReduced(YEAR, 2, 0, LocalDate.of(2000, 1, 1))); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValueReduced_date_maxWidthTooBig() throws Exception { - builder.appendValueReduced(YEAR, 2, 11, LocalDate.of(2000, 1, 1)); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValueReduced(YEAR, 2, 11, LocalDate.of(2000, 1, 1))); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValueReduced_date_maxWidthLessThanMin() throws Exception { - builder.appendValueReduced(YEAR, 2, 1, LocalDate.of(2000, 1, 1)); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValueReduced(YEAR, 2, 1, LocalDate.of(2000, 1, 1))); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendFraction_4arg_nullRule() throws Exception { - builder.appendFraction(null, 1, 9, false); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendFraction(null, 1, 9, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_invalidRuleNotFixedSet() throws Exception { - builder.appendFraction(DAY_OF_MONTH, 1, 9, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(DAY_OF_MONTH, 1, 9, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_minTooSmall() throws Exception { - builder.appendFraction(MINUTE_OF_HOUR, -1, 9, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(MINUTE_OF_HOUR, -1, 9, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_minTooBig() throws Exception { - builder.appendFraction(MINUTE_OF_HOUR, 10, 9, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(MINUTE_OF_HOUR, 10, 9, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_maxTooSmall() throws Exception { - builder.appendFraction(MINUTE_OF_HOUR, 0, -1, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(MINUTE_OF_HOUR, 0, -1, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_maxTooBig() throws Exception { - builder.appendFraction(MINUTE_OF_HOUR, 1, 10, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(MINUTE_OF_HOUR, 1, 10, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_maxWidthMinWidth() throws Exception { - builder.appendFraction(MINUTE_OF_HOUR, 9, 3, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(MINUTE_OF_HOUR, 9, 3, false)); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendText_1arg_null() throws Exception { - builder.appendText(null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendText(null)); } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendText_2arg_nullRule() throws Exception { - builder.appendText(null, TextStyle.SHORT); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendText(null, TextStyle.SHORT)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendText_2arg_nullStyle() throws Exception { - builder.appendText(MONTH_OF_YEAR, (TextStyle) null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendText(MONTH_OF_YEAR, (TextStyle) null)); } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendTextMap_nullRule() throws Exception { - builder.appendText(null, new HashMap<>()); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendText(null, new HashMap<>())); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendTextMap_nullStyle() throws Exception { - builder.appendText(MONTH_OF_YEAR, (Map) null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendText(MONTH_OF_YEAR, (Map) null)); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="offsetPatterns") Object[][] data_offsetPatterns() { return new Object[][] { {"+HH", 2, 0, 0, "+02"}, @@ -532,23 +535,24 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="offsetPatterns") + @ParameterizedTest + @MethodSource("data_offsetPatterns") public void test_appendOffset_format(String pattern, int h, int m, int s, String expected) throws Exception { builder.appendOffset(pattern, "Z"); DateTimeFormatter f = builder.toFormatter(); ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(h, m, s); - assertEquals(f.format(offset), expected); + assertEquals(expected, f.format(offset)); } - @Test(dataProvider="offsetPatterns") + @ParameterizedTest + @MethodSource("data_offsetPatterns") public void test_appendOffset_parse(String pattern, int h, int m, int s, String expected) throws Exception { builder.appendOffset(pattern, "Z"); DateTimeFormatter f = builder.toFormatter(); ZoneOffset parsed = f.parse(expected, ZoneOffset::from); - assertEquals(f.format(parsed), expected); + assertEquals(expected, f.format(parsed)); } - @DataProvider(name="badOffsetPatterns") Object[][] data_badOffsetPatterns() { return new Object[][] { {"HH"}, @@ -563,25 +567,25 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="badOffsetPatterns", expectedExceptions=IllegalArgumentException.class) + @ParameterizedTest + @MethodSource("data_badOffsetPatterns") public void test_appendOffset_badPattern(String pattern) throws Exception { - builder.appendOffset(pattern, "Z"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendOffset(pattern, "Z")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendOffset_3arg_nullText() throws Exception { - builder.appendOffset("+HH:MM", null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendOffset("+HH:MM", null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendOffset_3arg_nullPattern() throws Exception { - builder.appendOffset(null, "Z"); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendOffset(null, "Z")); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name = "formatGenericTimeZonePatterns") Object[][] data_formatGenericNonLocationPatterns() { return new Object[][] { {"v", "America/Los_Angeles", "PT"}, @@ -591,14 +595,14 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider = "formatGenericTimeZonePatterns") + @ParameterizedTest + @MethodSource("data_formatGenericNonLocationPatterns") public void test_appendZoneText_formatGenericTimeZonePatterns(String pattern, String input, String expected) { ZonedDateTime zdt = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of(input)); DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern, Locale.US); - assertEquals(zdt.format(df), expected); + assertEquals(expected, zdt.format(df)); } - @DataProvider(name = "parseGenericTimeZonePatterns") Object[][] data_parseGenericTimeZonePatterns() { return new Object[][] { {"yyyy DDD HH mm v", LocalDateTime.of(2015, Month.MARCH, 10, 12, 13), ZoneId.of("America/Los_Angeles"), @@ -612,15 +616,15 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider = "parseGenericTimeZonePatterns") + @ParameterizedTest + @MethodSource("data_parseGenericTimeZonePatterns") public void test_appendZoneText_parseGenericTimeZonePatterns(String pattern, LocalDateTime ldt, ZoneId zId, String input) { DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(Locale.US); ZonedDateTime expected = ZonedDateTime.parse(input, df); ZonedDateTime actual = ZonedDateTime.of(ldt, zId); - assertEquals(actual, expected); + assertEquals(expected, actual); } - @DataProvider(name = "formatNonGenericTimeZonePatterns_1") Object[][] data_formatNonGenericTimeZonePatterns_1() { return new Object[][] { {"yyyy-MM-dd HH:mm:ss z", LocalDateTime.of(2015, Month.NOVEMBER, 1, 0, 30), @@ -638,16 +642,16 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider = "formatNonGenericTimeZonePatterns_1") + @ParameterizedTest + @MethodSource("data_formatNonGenericTimeZonePatterns_1") public void test_appendZoneText_parseNonGenricTimeZonePatterns_1(String pattern, LocalDateTime ldt, String expected) { ZoneId zId = ZoneId.of("America/Los_Angeles"); DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(Locale.US); ZonedDateTime zdt = ZonedDateTime.of(ldt, zId); String actual = df.format(zdt); - assertEquals(actual, expected); + assertEquals(expected, actual); } - @DataProvider(name = "formatNonGenericTimeZonePatterns_2") Object[][] data_formatNonGenericTimeZonePatterns_2() { return new Object[][] { {"yyyy-MM-dd HH:mm:ss z", LocalDateTime.of(2015, Month.NOVEMBER, 1, 0, 30), @@ -665,17 +669,18 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider = "formatNonGenericTimeZonePatterns_2") + @ParameterizedTest + @MethodSource("data_formatNonGenericTimeZonePatterns_2") public void test_appendZoneText_parseNonGenricTimeZonePatterns_2(String pattern, LocalDateTime ldt, String expected) { ZoneId zId = ZoneId.of("America/Los_Angeles"); DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern, Locale.US).withZone(zId); String actual = df.format(ldt); - assertEquals(actual, expected); + assertEquals(expected, actual); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendZoneText_1arg_nullText() throws Exception { - builder.appendZoneText(null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendZoneText(null)); } //----------------------------------------------------------------------- @@ -684,24 +689,24 @@ public class TCKDateTimeFormatterBuilder { @Test public void test_padNext_1arg() { builder.appendValue(MONTH_OF_YEAR).appendLiteral(':').padNext(2).appendValue(DAY_OF_MONTH); - assertEquals(builder.toFormatter().format(LocalDate.of(2013, 2, 1)), "2: 1"); + assertEquals("2: 1", builder.toFormatter().format(LocalDate.of(2013, 2, 1))); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_padNext_1arg_invalidWidth() throws Exception { - builder.padNext(0); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.padNext(0)); } //----------------------------------------------------------------------- @Test public void test_padNext_2arg_dash() throws Exception { builder.appendValue(MONTH_OF_YEAR).appendLiteral(':').padNext(2, '-').appendValue(DAY_OF_MONTH); - assertEquals(builder.toFormatter().format(LocalDate.of(2013, 2, 1)), "2:-1"); + assertEquals("2:-1", builder.toFormatter().format(LocalDate.of(2013, 2, 1))); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_padNext_2arg_invalidWidth() throws Exception { - builder.padNext(0, '-'); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.padNext(0, '-')); } //----------------------------------------------------------------------- @@ -710,22 +715,21 @@ public class TCKDateTimeFormatterBuilder { builder.appendValue(MONTH_OF_YEAR).appendLiteral(':') .padNext(5).optionalStart().appendValue(DAY_OF_MONTH).optionalEnd() .appendLiteral(':').appendValue(YEAR); - assertEquals(builder.toFormatter().format(LocalDate.of(2013, 2, 1)), "2: 1:2013"); - assertEquals(builder.toFormatter().format(YearMonth.of(2013, 2)), "2: :2013"); + assertEquals("2: 1:2013", builder.toFormatter().format(LocalDate.of(2013, 2, 1))); + assertEquals("2: :2013", builder.toFormatter().format(YearMonth.of(2013, 2))); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @Test(expectedExceptions=IllegalStateException.class) + @Test public void test_optionalEnd_noStart() throws Exception { - builder.optionalEnd(); + Assertions.assertThrows(IllegalStateException.class, () -> builder.optionalEnd()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="validPatterns") Object[][] dataValid() { return new Object[][] { {"'a'"}, @@ -882,13 +886,13 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="validPatterns") + @ParameterizedTest + @MethodSource("dataValid") public void test_appendPattern_valid(String input) throws Exception { builder.appendPattern(input); // test is for no error here } //----------------------------------------------------------------------- - @DataProvider(name="invalidPatterns") Object[][] dataInvalid() { return new Object[][] { {"'"}, @@ -954,13 +958,15 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="invalidPatterns", expectedExceptions=IllegalArgumentException.class) + @ParameterizedTest + @MethodSource("dataInvalid") public void test_appendPattern_invalid(String input) throws Exception { - builder.appendPattern(input); // test is for error here + Assertions.assertThrows(IllegalArgumentException.class, () -> { + builder.appendPattern(input); // test is for error here + }); } //----------------------------------------------------------------------- - @DataProvider(name="patternPrint") Object[][] data_patternPrint() { return new Object[][] { {"Q", date(2012, 2, 10), "1"}, @@ -971,11 +977,12 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="patternPrint") + @ParameterizedTest + @MethodSource("data_patternPrint") public void test_appendPattern_patternPrint(String input, Temporal temporal, String expected) throws Exception { DateTimeFormatter f = builder.appendPattern(input).toFormatter(Locale.UK); String test = f.format(temporal); - assertEquals(test, expected); + assertEquals(expected, test); } private static Temporal date(int y, int m, int d) { @@ -983,7 +990,6 @@ public class TCKDateTimeFormatterBuilder { } //----------------------------------------------------------------------- - @DataProvider(name="modJulianFieldPattern") Object[][] data_modJuilanFieldPattern() { return new Object[][] { {"g", "1"}, @@ -992,12 +998,12 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="modJulianFieldPattern") + @ParameterizedTest + @MethodSource("data_modJuilanFieldPattern") public void test_modJulianFieldPattern(String pattern, String input) throws Exception { DateTimeFormatter.ofPattern(pattern).parse(input); } - @DataProvider(name="modJulianFieldValues") Object[][] data_modJuilanFieldValues() { return new Object[][] { {1970, 1, 1, "40587"}, @@ -1006,13 +1012,13 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="modJulianFieldValues") + @ParameterizedTest + @MethodSource("data_modJuilanFieldValues") public void test_modJulianFieldValues(int y, int m, int d, String expected) throws Exception { DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern("g").toFormatter(); - assertEquals(LocalDate.of(y, m, d).format(df), expected); + assertEquals(expected, LocalDate.of(y, m, d).format(df)); } //---------------------------------------------------------------------- - @DataProvider(name="dayOfYearFieldValues") Object[][] data_dayOfYearFieldValues() { return new Object[][] { {2016, 1, 1, "D", "1"}, @@ -1026,13 +1032,13 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="dayOfYearFieldValues") + @ParameterizedTest + @MethodSource("data_dayOfYearFieldValues") public void test_dayOfYearFieldValues(int y, int m, int d, String pattern, String expected) throws Exception { DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(); - assertEquals(LocalDate.of(y, m, d).format(df), expected); + assertEquals(expected, LocalDate.of(y, m, d).format(df)); } - @DataProvider(name="dayOfYearFieldAdjacentParsingValues") Object[][] data_dayOfYearFieldAdjacentParsingValues() { return new Object[][] { {"20160281015", LocalDateTime.of(2016, 1, 28, 10, 15)}, @@ -1040,26 +1046,28 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="dayOfYearFieldAdjacentParsingValues") + @ParameterizedTest + @MethodSource("data_dayOfYearFieldAdjacentParsingValues") public void test_dayOfYearFieldAdjacentValueParsing(String input, LocalDateTime expected) { DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern("yyyyDDDHHmm").toFormatter(); LocalDateTime actual = LocalDateTime.parse(input, df); - assertEquals(actual, expected); + assertEquals(expected, actual); } - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_dayOfYearFieldInvalidValue() { - DateTimeFormatter.ofPattern("DDD").parse("1234"); + Assertions.assertThrows(DateTimeParseException.class, () -> DateTimeFormatter.ofPattern("DDD").parse("1234")); } - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_dayOfYearFieldInvalidAdacentValueParsingPattern() { - // patterns D and DD will not take part in adjacent value parsing - DateTimeFormatter.ofPattern("yyyyDDHHmmss").parse("201610123456"); + Assertions.assertThrows(DateTimeParseException.class, () -> { + // patterns D and DD will not take part in adjacent value parsing + DateTimeFormatter.ofPattern("yyyyDDHHmmss").parse("201610123456"); + }); } //----------------------------------------------------------------------- - @DataProvider(name="secondsPattern") Object[][] data_secondsPattern() { return new Object[][] { {"A", "1", LocalTime.ofNanoOfDay(1_000_000)}, @@ -1080,13 +1088,13 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="secondsPattern") + @ParameterizedTest + @MethodSource("data_secondsPattern") public void test_secondsPattern(String pattern, String input, LocalTime expected) throws Exception { DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(); - assertEquals(LocalTime.parse(input, df), expected); + assertEquals(expected, LocalTime.parse(input, df)); } - @DataProvider(name="secondsValues") Object[][] data_secondsValues() { return new Object[][] { {"A", 1, "1000"}, @@ -1095,16 +1103,19 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="secondsValues") + @ParameterizedTest + @MethodSource("data_secondsValues") public void test_secondsValues(String pattern, int seconds , String expected) throws Exception { DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(); - assertEquals(LocalTime.ofSecondOfDay(seconds).format(df), expected); + assertEquals(expected, LocalTime.ofSecondOfDay(seconds).format(df)); } - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_secondsPatternInvalidAdacentValueParsingPattern() { - // patterns A*, N*, n* will not take part in adjacent value parsing - DateTimeFormatter.ofPattern("yyyyAA").parse("201610"); + Assertions.assertThrows(DateTimeParseException.class, () -> { + // patterns A*, N*, n* will not take part in adjacent value parsing + DateTimeFormatter.ofPattern("yyyyAA").parse("201610"); + }); } //----------------------------------------------------------------------- @@ -1114,10 +1125,10 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY, 2).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('9').toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("12309", pp); - assertEquals(pp.getErrorIndex(), -1); - assertEquals(pp.getIndex(), 5); - assertEquals(parsed.getLong(HOUR_OF_DAY), 12L); - assertEquals(parsed.getLong(MINUTE_OF_HOUR), 30L); + assertEquals(-1, pp.getErrorIndex()); + assertEquals(5, pp.getIndex()); + assertEquals(12L, parsed.getLong(HOUR_OF_DAY)); + assertEquals(30L, parsed.getLong(MINUTE_OF_HOUR)); } @Test @@ -1126,10 +1137,10 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('Z').toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("12309Z", pp); - assertEquals(pp.getErrorIndex(), -1); - assertEquals(pp.getIndex(), 6); - assertEquals(parsed.getLong(HOUR_OF_DAY), 123L); - assertEquals(parsed.getLong(MINUTE_OF_HOUR), 9L); + assertEquals(-1, pp.getErrorIndex()); + assertEquals(6, pp.getIndex()); + assertEquals(123L, parsed.getLong(HOUR_OF_DAY)); + assertEquals(9L, parsed.getLong(MINUTE_OF_HOUR)); } @Test @@ -1138,8 +1149,8 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('9').toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("12309", pp); - assertEquals(pp.getErrorIndex(), 5); - assertEquals(parsed, null); + assertEquals(5, pp.getErrorIndex()); + assertEquals(null, parsed); } @Test @@ -1148,10 +1159,10 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.parseLenient().appendValue(HOUR_OF_DAY, 2).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('9').toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("12309", pp); - assertEquals(pp.getErrorIndex(), -1); - assertEquals(pp.getIndex(), 5); - assertEquals(parsed.getLong(HOUR_OF_DAY), 12L); - assertEquals(parsed.getLong(MINUTE_OF_HOUR), 30L); + assertEquals(-1, pp.getErrorIndex()); + assertEquals(5, pp.getIndex()); + assertEquals(12L, parsed.getLong(HOUR_OF_DAY)); + assertEquals(30L, parsed.getLong(MINUTE_OF_HOUR)); } @Test @@ -1160,10 +1171,10 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.parseLenient().appendValue(HOUR_OF_DAY).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('Z').toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("12309Z", pp); - assertEquals(pp.getErrorIndex(), -1); - assertEquals(pp.getIndex(), 6); - assertEquals(parsed.getLong(HOUR_OF_DAY), 123L); - assertEquals(parsed.getLong(MINUTE_OF_HOUR), 9L); + assertEquals(-1, pp.getErrorIndex()); + assertEquals(6, pp.getIndex()); + assertEquals(123L, parsed.getLong(HOUR_OF_DAY)); + assertEquals(9L, parsed.getLong(MINUTE_OF_HOUR)); } @Test @@ -1172,8 +1183,8 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.parseLenient().appendValue(HOUR_OF_DAY).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('9').toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("12309", pp); - assertEquals(pp.getErrorIndex(), 5); - assertEquals(parsed, null); + assertEquals(5, pp.getErrorIndex()); + assertEquals(null, parsed); } //----------------------------------------------------------------------- @@ -1183,11 +1194,11 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY, 2).appendValue(MINUTE_OF_HOUR, 2).appendFraction(NANO_OF_SECOND, 0, 3, false).toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("1230567", pp); - assertEquals(pp.getErrorIndex(), -1); - assertEquals(pp.getIndex(), 7); - assertEquals(parsed.getLong(HOUR_OF_DAY), 12L); - assertEquals(parsed.getLong(MINUTE_OF_HOUR), 30L); - assertEquals(parsed.getLong(NANO_OF_SECOND), 567_000_000L); + assertEquals(-1, pp.getErrorIndex()); + assertEquals(7, pp.getIndex()); + assertEquals(12L, parsed.getLong(HOUR_OF_DAY)); + assertEquals(30L, parsed.getLong(MINUTE_OF_HOUR)); + assertEquals(567_000_000L, parsed.getLong(NANO_OF_SECOND)); } @Test @@ -1196,11 +1207,11 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY, 2).appendValue(MINUTE_OF_HOUR, 2).appendFraction(NANO_OF_SECOND, 0, 3, false).toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("123056", pp); - assertEquals(pp.getErrorIndex(), -1); - assertEquals(pp.getIndex(), 6); - assertEquals(parsed.getLong(HOUR_OF_DAY), 12L); - assertEquals(parsed.getLong(MINUTE_OF_HOUR), 30L); - assertEquals(parsed.getLong(NANO_OF_SECOND), 560_000_000L); + assertEquals(-1, pp.getErrorIndex()); + assertEquals(6, pp.getIndex()); + assertEquals(12L, parsed.getLong(HOUR_OF_DAY)); + assertEquals(30L, parsed.getLong(MINUTE_OF_HOUR)); + assertEquals(560_000_000L, parsed.getLong(NANO_OF_SECOND)); } @Test @@ -1209,10 +1220,10 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY, 2).appendValue(MINUTE_OF_HOUR, 2).appendFraction(NANO_OF_SECOND, 0, 3, false).toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("1230", pp); - assertEquals(pp.getErrorIndex(), -1); - assertEquals(pp.getIndex(), 4); - assertEquals(parsed.getLong(HOUR_OF_DAY), 12L); - assertEquals(parsed.getLong(MINUTE_OF_HOUR), 30L); + assertEquals(-1, pp.getErrorIndex()); + assertEquals(4, pp.getIndex()); + assertEquals(12L, parsed.getLong(HOUR_OF_DAY)); + assertEquals(30L, parsed.getLong(MINUTE_OF_HOUR)); } @Test @@ -1221,11 +1232,11 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.parseLenient().appendValue(HOUR_OF_DAY, 2).appendValue(MINUTE_OF_HOUR, 2).appendFraction(NANO_OF_SECOND, 3, 3, false).toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("1230567", pp); - assertEquals(pp.getErrorIndex(), -1); - assertEquals(pp.getIndex(), 7); - assertEquals(parsed.getLong(HOUR_OF_DAY), 12L); - assertEquals(parsed.getLong(MINUTE_OF_HOUR), 30L); - assertEquals(parsed.getLong(NANO_OF_SECOND), 567_000_000L); + assertEquals(-1, pp.getErrorIndex()); + assertEquals(7, pp.getIndex()); + assertEquals(12L, parsed.getLong(HOUR_OF_DAY)); + assertEquals(30L, parsed.getLong(MINUTE_OF_HOUR)); + assertEquals(567_000_000L, parsed.getLong(NANO_OF_SECOND)); } @Test @@ -1234,11 +1245,11 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.parseLenient().appendValue(HOUR_OF_DAY, 2).appendValue(MINUTE_OF_HOUR, 2).appendFraction(NANO_OF_SECOND, 3, 3, false).toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("123056", pp); - assertEquals(pp.getErrorIndex(), -1); - assertEquals(pp.getIndex(), 6); - assertEquals(parsed.getLong(HOUR_OF_DAY), 12L); - assertEquals(parsed.getLong(MINUTE_OF_HOUR), 30L); - assertEquals(parsed.getLong(NANO_OF_SECOND), 560_000_000L); + assertEquals(-1, pp.getErrorIndex()); + assertEquals(6, pp.getIndex()); + assertEquals(12L, parsed.getLong(HOUR_OF_DAY)); + assertEquals(30L, parsed.getLong(MINUTE_OF_HOUR)); + assertEquals(560_000_000L, parsed.getLong(NANO_OF_SECOND)); } @Test @@ -1247,13 +1258,12 @@ public class TCKDateTimeFormatterBuilder { DateTimeFormatter f = builder.parseLenient().appendValue(HOUR_OF_DAY, 2).appendValue(MINUTE_OF_HOUR, 2).appendFraction(NANO_OF_SECOND, 3, 3, false).toFormatter(Locale.UK); ParsePosition pp = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("1230", pp); - assertEquals(pp.getErrorIndex(), -1); - assertEquals(pp.getIndex(), 4); - assertEquals(parsed.getLong(HOUR_OF_DAY), 12L); - assertEquals(parsed.getLong(MINUTE_OF_HOUR), 30L); + assertEquals(-1, pp.getErrorIndex()); + assertEquals(4, pp.getIndex()); + assertEquals(12L, parsed.getLong(HOUR_OF_DAY)); + assertEquals(30L, parsed.getLong(MINUTE_OF_HOUR)); } - @DataProvider(name="adjacentFractionParseData") Object[][] data_adjacent_fraction_parse() { return new Object[][] { {"20130812214600025", "yyyyMMddHHmmssSSS", LocalDateTime.of(2013, 8, 12, 21, 46, 00, 25000000)}, @@ -1261,14 +1271,14 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider = "adjacentFractionParseData") + @ParameterizedTest + @MethodSource("data_adjacent_fraction_parse") public void test_adjacent_fraction(String input, String pattern, LocalDateTime expected) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern); LocalDateTime actual = LocalDateTime.parse(input, dtf); - assertEquals(actual, expected); + assertEquals(expected, actual); } - @DataProvider(name="lenientOffsetParseData") Object[][] data_lenient_offset_parse() { return new Object[][] { {"+HH", "+01", 3600}, @@ -1381,7 +1391,6 @@ public class TCKDateTimeFormatterBuilder { }; } - @DataProvider(name="strictDoubleDigitHourOffsetParseData") Object[][] data_strictDoubleDigitHour_offset_parse() { return new Object[][] { {"+HH", "+01", 3600}, @@ -1406,7 +1415,6 @@ public class TCKDateTimeFormatterBuilder { }; } - @DataProvider(name="strictSingleDigitHourOffsetParseData") Object[][] data_strictSingleDigitHour_offset_parse() { return new Object[][] { {"+H", "+01", 3600}, @@ -1450,43 +1458,45 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="lenientOffsetParseData") + @ParameterizedTest + @MethodSource("data_lenient_offset_parse") public void test_lenient_offset_parse_1(String pattern, String offset, int offsetSeconds) { - assertEquals(new DateTimeFormatterBuilder().parseLenient().appendOffset(pattern, "Z").toFormatter().parse(offset).get(OFFSET_SECONDS), - offsetSeconds); + assertEquals(offsetSeconds, new DateTimeFormatterBuilder().parseLenient().appendOffset(pattern, "Z").toFormatter().parse(offset).get(OFFSET_SECONDS)); } @Test public void test_lenient_offset_parse_2() { - assertEquals(new DateTimeFormatterBuilder().parseLenient().appendOffsetId().toFormatter().parse("+01").get(OFFSET_SECONDS), - 3600); + assertEquals(3600, new DateTimeFormatterBuilder().parseLenient().appendOffsetId().toFormatter().parse("+01").get(OFFSET_SECONDS)); } - @Test(dataProvider="strictDoubleDigitHourOffsetParseData") + @ParameterizedTest + @MethodSource("data_strictDoubleDigitHour_offset_parse") public void test_strictDoubleDigitHour_offset_parse_1(String pattern, String offset, int offsetSeconds) { - assertEquals(new DateTimeFormatterBuilder().appendOffset(pattern, "Z").toFormatter() - .parse(offset).get(OFFSET_SECONDS), offsetSeconds); + assertEquals(offsetSeconds, new DateTimeFormatterBuilder().appendOffset(pattern, "Z").toFormatter() + .parse(offset).get(OFFSET_SECONDS)); } - @Test(dataProvider="strictDoubleDigitHourOffsetParseData") + @ParameterizedTest + @MethodSource("data_strictDoubleDigitHour_offset_parse") public void test_strictDoubleDigitHour_offset_parse_2(String pattern, String offset, int offsetSeconds) { - assertEquals(new DateTimeFormatterBuilder().appendOffset(pattern, "Z") - .appendLiteral("text").toFormatter().parse(offset + "text").get(OFFSET_SECONDS), offsetSeconds); + assertEquals(offsetSeconds, new DateTimeFormatterBuilder().appendOffset(pattern, "Z") + .appendLiteral("text").toFormatter().parse(offset + "text").get(OFFSET_SECONDS)); } - @Test(dataProvider="strictSingleDigitHourOffsetParseData") + @ParameterizedTest + @MethodSource("data_strictSingleDigitHour_offset_parse") public void test_strictSingleDigitHour_offset_parse_1(String pattern, String offset, int offsetSeconds) { - assertEquals(new DateTimeFormatterBuilder().appendOffset(pattern, "Z").toFormatter() - .parse(offset).get(OFFSET_SECONDS), offsetSeconds); + assertEquals(offsetSeconds, new DateTimeFormatterBuilder().appendOffset(pattern, "Z").toFormatter() + .parse(offset).get(OFFSET_SECONDS)); } - @Test(dataProvider="strictSingleDigitHourOffsetParseData") + @ParameterizedTest + @MethodSource("data_strictSingleDigitHour_offset_parse") public void test_strictSingleDigitHour_offset_parse_2(String pattern, String offset, int offsetSeconds) { - assertEquals(new DateTimeFormatterBuilder().appendOffset(pattern, "Z") - .appendLiteral("text").toFormatter().parse(offset + "text").get(OFFSET_SECONDS), offsetSeconds); + assertEquals(offsetSeconds, new DateTimeFormatterBuilder().appendOffset(pattern, "Z") + .appendLiteral("text").toFormatter().parse(offset + "text").get(OFFSET_SECONDS)); } - @DataProvider(name="strictOffsetAdjacentParseValidPatternData") Object[][] data_strict_offset_adjacentParse_validPattern() { return new Object[][] { {"+HH", "+01", 3600}, @@ -1530,15 +1540,15 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="strictOffsetAdjacentParseValidPatternData") + @ParameterizedTest + @MethodSource("data_strict_offset_adjacentParse_validPattern") public void test_strict_offset_adjacentValidPattern_parse(String pattern, String offset, int offsetSeconds) { TemporalAccessor tmp = new DateTimeFormatterBuilder().appendOffset(pattern, "Z") .appendValue(HOUR_OF_DAY, 2).toFormatter().parse(offset + "12"); - assertEquals(tmp.get(OFFSET_SECONDS), offsetSeconds); - assertEquals(tmp.get(HOUR_OF_DAY), 12); + assertEquals(offsetSeconds, tmp.get(OFFSET_SECONDS)); + assertEquals(12, tmp.get(HOUR_OF_DAY)); } - @DataProvider(name="strictOffsetAdjacentParseInvalidPatternData") Object[][] data_strict_offset_adjacentParse_invalidPattern() { return new Object[][] { {"+HHmm", "+01", 3600}, @@ -1564,13 +1574,13 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="strictOffsetAdjacentParseInvalidPatternData", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("data_strict_offset_adjacentParse_invalidPattern") public void test_strict_offset_adjacentInvalidPattern_parse(String pattern, String offset, int offsetSeconds) { - new DateTimeFormatterBuilder().appendOffset(pattern, "Z").appendValue(HOUR_OF_DAY, 2) - .toFormatter().parse(offset + "12"); + Assertions.assertThrows(DateTimeParseException.class, () -> new DateTimeFormatterBuilder().appendOffset(pattern, "Z").appendValue(HOUR_OF_DAY, 2) + .toFormatter().parse(offset + "12")); } - @DataProvider(name="lenientOffsetAdjacentParseValidPatternData") Object[][] data_lenient_offset_adjacentParse_validPattern() { return new Object[][] { {"+HH:mm", "+01", 3600}, @@ -1606,12 +1616,13 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="lenientOffsetAdjacentParseValidPatternData") + @ParameterizedTest + @MethodSource("data_lenient_offset_adjacentParse_validPattern") public void test_lenient_offset_adjacentValidPattern_parse(String pattern, String offset, int offsetSeconds) { TemporalAccessor tmp = new DateTimeFormatterBuilder().parseLenient() .appendOffset(pattern, "Z").appendValue(HOUR_OF_DAY, 2).toFormatter().parse(offset + "12"); - assertEquals(tmp.get(OFFSET_SECONDS), offsetSeconds); - assertEquals(tmp.get(HOUR_OF_DAY), 12); + assertEquals(offsetSeconds, tmp.get(OFFSET_SECONDS)); + assertEquals(12, tmp.get(HOUR_OF_DAY)); } @Test @@ -1620,12 +1631,11 @@ public class TCKDateTimeFormatterBuilder { .appendOffset("+HMMSS", "Z").appendValue(HOUR_OF_DAY, 2).toFormatter().parse("+10101" + "12"); //Equivalent to +101011. In lenient mode, offset will parse upto 6 digit if possible. //It will take 1 digit from HOUR_OF_DAY. - assertEquals(tmp.get(OFFSET_SECONDS), 36611); - assertEquals(tmp.get(HOUR_OF_DAY), 2); + assertEquals(36611, tmp.get(OFFSET_SECONDS)); + assertEquals(2, tmp.get(HOUR_OF_DAY)); } - @DataProvider(name="lenientOffsetAdjacentParseInvalidPatternData") - Object[][] data_lenient_offset_adjacentParse_invalidPattern() { + Object[][] data_lenient_offset_adjacentParse_invalidPattern() { return new Object[][] { {"+HH", "+01", 3600}, {"+HHmm", "+0101", 3660}, @@ -1636,13 +1646,13 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="lenientOffsetAdjacentParseInvalidPatternData", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("data_lenient_offset_adjacentParse_invalidPattern") public void test_lenient_offset_adjacentInvalidPattern_parse(String pattern, String offset, int offsetSeconds) { - new DateTimeFormatterBuilder().parseLenient().appendOffset(pattern, "Z") - .appendValue(HOUR_OF_DAY, 2).toFormatter().parse(offset + "12"); + Assertions.assertThrows(DateTimeParseException.class, () -> new DateTimeFormatterBuilder().parseLenient().appendOffset(pattern, "Z") + .appendValue(HOUR_OF_DAY, 2).toFormatter().parse(offset + "12")); } - @DataProvider(name="badValues") Object[][] data_badOffsetValues() { return new Object[][] { {"+HH", "+24"}, @@ -1654,40 +1664,41 @@ public class TCKDateTimeFormatterBuilder { }; } - @Test(dataProvider="badValues", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("data_badOffsetValues") public void test_badOffset_parse(String pattern, String offset) { - new DateTimeFormatterBuilder().appendOffset(pattern, "Z").toFormatter().parse(offset); + Assertions.assertThrows(DateTimeParseException.class, () -> new DateTimeFormatterBuilder().appendOffset(pattern, "Z").toFormatter().parse(offset)); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_strict_appendOffsetId() { - new DateTimeFormatterBuilder().appendOffsetId().toFormatter().parse("+01"); + Assertions.assertThrows(DateTimeParseException.class, () -> new DateTimeFormatterBuilder().appendOffsetId().toFormatter().parse("+01")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_strict_appendOffset_1() { - new DateTimeFormatterBuilder().appendOffset("+HH:MM:ss", "Z").toFormatter().parse("+01"); + Assertions.assertThrows(DateTimeParseException.class, () -> new DateTimeFormatterBuilder().appendOffset("+HH:MM:ss", "Z").toFormatter().parse("+01")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_strict_appendOffset_2() { - new DateTimeFormatterBuilder().appendOffset("+HHMMss", "Z").toFormatter().parse("+01"); + Assertions.assertThrows(DateTimeParseException.class, () -> new DateTimeFormatterBuilder().appendOffset("+HHMMss", "Z").toFormatter().parse("+01")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_strict_appendOffset_3() { - new DateTimeFormatterBuilder().appendOffset("+H:MM:ss", "Z").toFormatter().parse("+1"); + Assertions.assertThrows(DateTimeParseException.class, () -> new DateTimeFormatterBuilder().appendOffset("+H:MM:ss", "Z").toFormatter().parse("+1")); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_strict_appendOffset_4() { - new DateTimeFormatterBuilder().appendOffset("+HMMss", "Z").toFormatter().parse("+1"); + Assertions.assertThrows(DateTimeParseException.class, () -> new DateTimeFormatterBuilder().appendOffset("+HMMss", "Z").toFormatter().parse("+1")); } @Test public void test_basic_iso_date() { - assertEquals(BASIC_ISO_DATE.parse("20021231+01").get(OFFSET_SECONDS), 3600); - assertEquals(BASIC_ISO_DATE.parse("20021231+0101").get(OFFSET_SECONDS), 3660); + assertEquals(3600, BASIC_ISO_DATE.parse("20021231+01").get(OFFSET_SECONDS)); + assertEquals(3660, BASIC_ISO_DATE.parse("20021231+0101").get(OFFSET_SECONDS)); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatters.java b/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatters.java index e370521b7f0..7171b225f44 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatters.java +++ b/test/jdk/java/time/tck/java/time/format/TCKDateTimeFormatters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -70,9 +70,10 @@ import static java.time.temporal.ChronoField.NANO_OF_SECOND; import static java.time.temporal.ChronoField.OFFSET_SECONDS; import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.text.ParsePosition; import java.time.DateTimeException; @@ -101,24 +102,27 @@ import java.util.Iterator; import java.util.Locale; import java.util.Map; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatter. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKDateTimeFormatters { - @BeforeMethod + @BeforeEach public void setUp() { } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_format_nullTemporalAccessor() { - DateTimeFormatter.ISO_DATE.format((TemporalAccessor) null); + Assertions.assertThrows(NullPointerException.class, () -> DateTimeFormatter.ISO_DATE.format((TemporalAccessor) null)); } //----------------------------------------------------------------------- @@ -128,19 +132,19 @@ public class TCKDateTimeFormatters { public void test_pattern_String() { DateTimeFormatter test = DateTimeFormatter.ofPattern("d MMM yyyy"); Locale fmtLocale = Locale.getDefault(Locale.Category.FORMAT); - assertEquals(test.format(LocalDate.of(2012, 6, 30)), "30 " + - Month.JUNE.getDisplayName(TextStyle.SHORT, fmtLocale) + " 2012"); - assertEquals(test.getLocale(), fmtLocale, "Locale.Category.FORMAT"); + assertEquals("30 " + + Month.JUNE.getDisplayName(TextStyle.SHORT, fmtLocale) + " 2012", test.format(LocalDate.of(2012, 6, 30))); + assertEquals(fmtLocale, test.getLocale(), "Locale.Category.FORMAT"); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_pattern_String_invalid() { - DateTimeFormatter.ofPattern("p"); + Assertions.assertThrows(IllegalArgumentException.class, () -> DateTimeFormatter.ofPattern("p")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_pattern_String_null() { - DateTimeFormatter.ofPattern(null); + Assertions.assertThrows(NullPointerException.class, () -> DateTimeFormatter.ofPattern(null)); } //----------------------------------------------------------------------- @@ -149,23 +153,23 @@ public class TCKDateTimeFormatters { @Test public void test_pattern_StringLocale() { DateTimeFormatter test = DateTimeFormatter.ofPattern("d MMM yyyy", Locale.UK); - assertEquals(test.format(LocalDate.of(2012, 6, 30)), "30 Jun 2012"); - assertEquals(test.getLocale(), Locale.UK); + assertEquals("30 Jun 2012", test.format(LocalDate.of(2012, 6, 30))); + assertEquals(Locale.UK, test.getLocale()); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_pattern_StringLocale_invalid() { - DateTimeFormatter.ofPattern("p", Locale.UK); + Assertions.assertThrows(IllegalArgumentException.class, () -> DateTimeFormatter.ofPattern("p", Locale.UK)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_pattern_StringLocale_nullPattern() { - DateTimeFormatter.ofPattern(null, Locale.UK); + Assertions.assertThrows(NullPointerException.class, () -> DateTimeFormatter.ofPattern(null, Locale.UK)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_pattern_StringLocale_nullLocale() { - DateTimeFormatter.ofPattern("yyyy", null); + Assertions.assertThrows(NullPointerException.class, () -> DateTimeFormatter.ofPattern("yyyy", null)); } //----------------------------------------------------------------------- @@ -173,36 +177,35 @@ public class TCKDateTimeFormatters { //----------------------------------------------------------------------- @Test public void test_ofLocalizedDate_basics() { - assertEquals(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).getZone(), null); - assertEquals(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).getResolverStyle(), ResolverStyle.SMART); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).getChronology()); + assertEquals(null, DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).getZone()); + assertEquals(ResolverStyle.SMART, DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).getResolverStyle()); } @Test public void test_ofLocalizedTime_basics() { - assertEquals(DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL).getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL).getZone(), null); - assertEquals(DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL).getResolverStyle(), ResolverStyle.SMART); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL).getChronology()); + assertEquals(null, DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL).getZone()); + assertEquals(ResolverStyle.SMART, DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL).getResolverStyle()); } @Test public void test_ofLocalizedDateTime1_basics() { - assertEquals(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).getZone(), null); - assertEquals(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).getResolverStyle(), ResolverStyle.SMART); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).getChronology()); + assertEquals(null, DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).getZone()); + assertEquals(ResolverStyle.SMART, DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).getResolverStyle()); } @Test public void test_ofLocalizedDateTime2_basics() { - assertEquals(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM).getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM).getZone(), null); - assertEquals(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM).getResolverStyle(), ResolverStyle.SMART); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM).getChronology()); + assertEquals(null, DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM).getZone()); + assertEquals(ResolverStyle.SMART, DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM).getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoLocalDate") Object[][] provider_sample_isoLocalDate() { return new Object[][]{ {2008, null, null, null, null, null, DateTimeException.class}, @@ -222,13 +225,14 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoLocalDate") + @ParameterizedTest + @MethodSource("provider_sample_isoLocalDate") public void test_print_isoLocalDate( Integer year, Integer month, Integer day, String offsetId, String zoneId, String expected, Class expectedEx) { TemporalAccessor test = buildAccessor(year, month, day, null, null, null, null, offsetId, zoneId); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_LOCAL_DATE.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_LOCAL_DATE.format(test)); } else { try { DateTimeFormatter.ISO_LOCAL_DATE.format(test); @@ -239,7 +243,8 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoLocalDate") + @ParameterizedTest + @MethodSource("provider_sample_isoLocalDate") public void test_parse_isoLocalDate( Integer year, Integer month, Integer day, String offsetId, String zoneId, String input, Class invalid) { @@ -254,7 +259,7 @@ public class TCKDateTimeFormatters { public void test_parse_isoLocalDate_999999999() { Expected expected = createDate(999999999, 8, 6); assertParseMatch(DateTimeFormatter.ISO_LOCAL_DATE.parseUnresolved("+999999999-08-06", new ParsePosition(0)), expected); - assertEquals(LocalDate.parse("+999999999-08-06"), LocalDate.of(999999999, 8, 6)); + assertEquals(LocalDate.of(999999999, 8, 6), LocalDate.parse("+999999999-08-06")); } @Test @@ -263,16 +268,16 @@ public class TCKDateTimeFormatters { assertParseMatch(DateTimeFormatter.ISO_LOCAL_DATE.parseUnresolved("+1000000000-08-06", new ParsePosition(0)), expected); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_parse_isoLocalDate_1000000000_failedCreate() { - LocalDate.parse("+1000000000-08-06"); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.parse("+1000000000-08-06")); } @Test public void test_parse_isoLocalDate_M999999999() { Expected expected = createDate(-999999999, 8, 6); assertParseMatch(DateTimeFormatter.ISO_LOCAL_DATE.parseUnresolved("-999999999-08-06", new ParsePosition(0)), expected); - assertEquals(LocalDate.parse("-999999999-08-06"), LocalDate.of(-999999999, 8, 6)); + assertEquals(LocalDate.of(-999999999, 8, 6), LocalDate.parse("-999999999-08-06")); } @Test @@ -281,22 +286,21 @@ public class TCKDateTimeFormatters { assertParseMatch(DateTimeFormatter.ISO_LOCAL_DATE.parseUnresolved("-1000000000-08-06", new ParsePosition(0)), expected); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_parse_isoLocalDate_M1000000000_failedCreate() { - LocalDate.parse("-1000000000-08-06"); + Assertions.assertThrows(DateTimeException.class, () -> LocalDate.parse("-1000000000-08-06")); } @Test public void test_isoLocalDate_basics() { - assertEquals(DateTimeFormatter.ISO_LOCAL_DATE.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ISO_LOCAL_DATE.getZone(), null); - assertEquals(DateTimeFormatter.ISO_LOCAL_DATE.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ISO_LOCAL_DATE.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_LOCAL_DATE.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_LOCAL_DATE.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoOffsetDate") Object[][] provider_sample_isoOffsetDate() { return new Object[][]{ {2008, null, null, null, null, null, DateTimeException.class}, @@ -316,13 +320,14 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoOffsetDate") + @ParameterizedTest + @MethodSource("provider_sample_isoOffsetDate") public void test_print_isoOffsetDate( Integer year, Integer month, Integer day, String offsetId, String zoneId, String expected, Class expectedEx) { TemporalAccessor test = buildAccessor(year, month, day, null, null, null, null, offsetId, zoneId); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_OFFSET_DATE.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_OFFSET_DATE.format(test)); } else { try { DateTimeFormatter.ISO_OFFSET_DATE.format(test); @@ -333,7 +338,8 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoOffsetDate") + @ParameterizedTest + @MethodSource("provider_sample_isoOffsetDate") public void test_parse_isoOffsetDate( Integer year, Integer month, Integer day, String offsetId, String zoneId, String input, Class invalid) { @@ -346,15 +352,14 @@ public class TCKDateTimeFormatters { @Test public void test_isoOffsetDate_basics() { - assertEquals(DateTimeFormatter.ISO_OFFSET_DATE.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ISO_OFFSET_DATE.getZone(), null); - assertEquals(DateTimeFormatter.ISO_OFFSET_DATE.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ISO_OFFSET_DATE.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_OFFSET_DATE.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_OFFSET_DATE.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoDate") Object[][] provider_sample_isoDate() { return new Object[][]{ {2008, null, null, null, null, null, DateTimeException.class}, @@ -374,13 +379,14 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoDate") + @ParameterizedTest + @MethodSource("provider_sample_isoDate") public void test_print_isoDate( Integer year, Integer month, Integer day, String offsetId, String zoneId, String expected, Class expectedEx) { TemporalAccessor test = buildAccessor(year, month, day, null, null, null, null, offsetId, zoneId); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_DATE.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_DATE.format(test)); } else { try { DateTimeFormatter.ISO_DATE.format(test); @@ -391,7 +397,8 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoDate") + @ParameterizedTest + @MethodSource("provider_sample_isoDate") public void test_parse_isoDate( Integer year, Integer month, Integer day, String offsetId, String zoneId, String input, Class invalid) { @@ -406,15 +413,14 @@ public class TCKDateTimeFormatters { @Test public void test_isoDate_basics() { - assertEquals(DateTimeFormatter.ISO_DATE.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ISO_DATE.getZone(), null); - assertEquals(DateTimeFormatter.ISO_DATE.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ISO_DATE.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_DATE.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_DATE.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoLocalTime") Object[][] provider_sample_isoLocalTime() { return new Object[][]{ {11, null, null, null, null, null, null, DateTimeException.class}, @@ -446,13 +452,14 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoLocalTime") + @ParameterizedTest + @MethodSource("provider_sample_isoLocalTime") public void test_print_isoLocalTime( Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String expected, Class expectedEx) { TemporalAccessor test = buildAccessor(null, null, null, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_LOCAL_TIME.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_LOCAL_TIME.format(test)); } else { try { DateTimeFormatter.ISO_LOCAL_TIME.format(test); @@ -463,7 +470,8 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoLocalTime") + @ParameterizedTest + @MethodSource("provider_sample_isoLocalTime") public void test_parse_isoLocalTime( Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String input, Class invalid) { @@ -476,15 +484,14 @@ public class TCKDateTimeFormatters { @Test public void test_isoLocalTime_basics() { - assertEquals(DateTimeFormatter.ISO_LOCAL_TIME.getChronology(), null); - assertEquals(DateTimeFormatter.ISO_LOCAL_TIME.getZone(), null); - assertEquals(DateTimeFormatter.ISO_LOCAL_TIME.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(null, DateTimeFormatter.ISO_LOCAL_TIME.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_LOCAL_TIME.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_LOCAL_TIME.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoOffsetTime") Object[][] provider_sample_isoOffsetTime() { return new Object[][]{ {11, null, null, null, null, null, null, DateTimeException.class}, @@ -516,13 +523,14 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoOffsetTime") + @ParameterizedTest + @MethodSource("provider_sample_isoOffsetTime") public void test_print_isoOffsetTime( Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String expected, Class expectedEx) { TemporalAccessor test = buildAccessor(null, null, null, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_OFFSET_TIME.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_OFFSET_TIME.format(test)); } else { try { DateTimeFormatter.ISO_OFFSET_TIME.format(test); @@ -533,7 +541,8 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoOffsetTime") + @ParameterizedTest + @MethodSource("provider_sample_isoOffsetTime") public void test_parse_isoOffsetTime( Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String input, Class invalid) { @@ -546,15 +555,14 @@ public class TCKDateTimeFormatters { @Test public void test_isoOffsetTime_basics() { - assertEquals(DateTimeFormatter.ISO_OFFSET_TIME.getChronology(), null); - assertEquals(DateTimeFormatter.ISO_OFFSET_TIME.getZone(), null); - assertEquals(DateTimeFormatter.ISO_OFFSET_TIME.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(null, DateTimeFormatter.ISO_OFFSET_TIME.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_OFFSET_TIME.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_OFFSET_TIME.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoTime") Object[][] provider_sample_isoTime() { return new Object[][]{ {11, null, null, null, null, null, null, DateTimeException.class}, @@ -586,13 +594,14 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoTime") + @ParameterizedTest + @MethodSource("provider_sample_isoTime") public void test_print_isoTime( Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String expected, Class expectedEx) { TemporalAccessor test = buildAccessor(null, null, null, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_TIME.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_TIME.format(test)); } else { try { DateTimeFormatter.ISO_TIME.format(test); @@ -603,7 +612,8 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoTime") + @ParameterizedTest + @MethodSource("provider_sample_isoTime") public void test_parse_isoTime( Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String input, Class invalid) { @@ -618,15 +628,14 @@ public class TCKDateTimeFormatters { @Test public void test_isoTime_basics() { - assertEquals(DateTimeFormatter.ISO_TIME.getChronology(), null); - assertEquals(DateTimeFormatter.ISO_TIME.getZone(), null); - assertEquals(DateTimeFormatter.ISO_TIME.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(null, DateTimeFormatter.ISO_TIME.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_TIME.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_TIME.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoLocalDateTime") Object[][] provider_sample_isoLocalDateTime() { return new Object[][]{ {2008, null, null, null, null, null, null, null, null, null, DateTimeException.class}, @@ -666,14 +675,15 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoLocalDateTime") + @ParameterizedTest + @MethodSource("provider_sample_isoLocalDateTime") public void test_print_isoLocalDateTime( Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String expected, Class expectedEx) { TemporalAccessor test = buildAccessor(year, month, day, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(test)); } else { try { DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(test); @@ -684,7 +694,8 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoLocalDateTime") + @ParameterizedTest + @MethodSource("provider_sample_isoLocalDateTime") public void test_parse_isoLocalDateTime( Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, @@ -697,15 +708,14 @@ public class TCKDateTimeFormatters { @Test public void test_isoLocalDateTime_basics() { - assertEquals(DateTimeFormatter.ISO_LOCAL_DATE_TIME.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ISO_LOCAL_DATE_TIME.getZone(), null); - assertEquals(DateTimeFormatter.ISO_LOCAL_DATE_TIME.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ISO_LOCAL_DATE_TIME.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_LOCAL_DATE_TIME.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_LOCAL_DATE_TIME.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoOffsetDateTime") Object[][] provider_sample_isoOffsetDateTime() { return new Object[][]{ {2008, null, null, null, null, null, null, null, null, null, DateTimeException.class}, @@ -745,14 +755,15 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoOffsetDateTime") + @ParameterizedTest + @MethodSource("provider_sample_isoOffsetDateTime") public void test_print_isoOffsetDateTime( Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String expected, Class expectedEx) { TemporalAccessor test = buildAccessor(year, month, day, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(test)); } else { try { DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(test); @@ -763,7 +774,8 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoOffsetDateTime") + @ParameterizedTest + @MethodSource("provider_sample_isoOffsetDateTime") public void test_parse_isoOffsetDateTime( Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, @@ -777,15 +789,14 @@ public class TCKDateTimeFormatters { @Test public void test_isoOffsetDateTime_basics() { - assertEquals(DateTimeFormatter.ISO_OFFSET_DATE_TIME.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ISO_OFFSET_DATE_TIME.getZone(), null); - assertEquals(DateTimeFormatter.ISO_OFFSET_DATE_TIME.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ISO_OFFSET_DATE_TIME.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_OFFSET_DATE_TIME.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_OFFSET_DATE_TIME.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoZonedDateTime") Object[][] provider_sample_isoZonedDateTime() { return new Object[][]{ {2008, null, null, null, null, null, null, null, null, null, DateTimeException.class}, @@ -834,14 +845,15 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoZonedDateTime") + @ParameterizedTest + @MethodSource("provider_sample_isoZonedDateTime") public void test_print_isoZonedDateTime( Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String expected, Class expectedEx) { TemporalAccessor test = buildAccessor(year, month, day, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_ZONED_DATE_TIME.format(test)); } else { try { DateTimeFormatter.ISO_ZONED_DATE_TIME.format(test); @@ -852,7 +864,8 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoZonedDateTime") + @ParameterizedTest + @MethodSource("provider_sample_isoZonedDateTime") public void test_parse_isoZonedDateTime( Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, @@ -870,15 +883,14 @@ public class TCKDateTimeFormatters { @Test public void test_isoZonedDateTime_basics() { - assertEquals(DateTimeFormatter.ISO_ZONED_DATE_TIME.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ISO_ZONED_DATE_TIME.getZone(), null); - assertEquals(DateTimeFormatter.ISO_ZONED_DATE_TIME.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ISO_ZONED_DATE_TIME.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_ZONED_DATE_TIME.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_ZONED_DATE_TIME.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoDateTime") Object[][] provider_sample_isoDateTime() { return new Object[][]{ {2008, null, null, null, null, null, null, null, null, null, DateTimeException.class}, @@ -918,14 +930,15 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoDateTime") + @ParameterizedTest + @MethodSource("provider_sample_isoDateTime") public void test_print_isoDateTime( Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String expected, Class expectedEx) { TemporalAccessor test = buildAccessor(year, month, day, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_DATE_TIME.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_DATE_TIME.format(test)); } else { try { DateTimeFormatter.ISO_DATE_TIME.format(test); @@ -936,7 +949,8 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoDateTime") + @ParameterizedTest + @MethodSource("provider_sample_isoDateTime") public void test_parse_isoDateTime( Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, @@ -955,9 +969,9 @@ public class TCKDateTimeFormatters { @Test public void test_isoDateTime_basics() { - assertEquals(DateTimeFormatter.ISO_DATE_TIME.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ISO_DATE_TIME.getZone(), null); - assertEquals(DateTimeFormatter.ISO_DATE_TIME.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ISO_DATE_TIME.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_DATE_TIME.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_DATE_TIME.getResolverStyle()); } //----------------------------------------------------------------------- @@ -966,25 +980,25 @@ public class TCKDateTimeFormatters { @Test public void test_print_isoOrdinalDate() { TemporalAccessor test = buildAccessor(LocalDateTime.of(2008, 6, 3, 11, 5, 30), null, null); - assertEquals(DateTimeFormatter.ISO_ORDINAL_DATE.format(test), "2008-155"); + assertEquals("2008-155", DateTimeFormatter.ISO_ORDINAL_DATE.format(test)); } @Test public void test_print_isoOrdinalDate_offset() { TemporalAccessor test = buildAccessor(LocalDateTime.of(2008, 6, 3, 11, 5, 30), "Z", null); - assertEquals(DateTimeFormatter.ISO_ORDINAL_DATE.format(test), "2008-155Z"); + assertEquals("2008-155Z", DateTimeFormatter.ISO_ORDINAL_DATE.format(test)); } @Test public void test_print_isoOrdinalDate_zoned() { TemporalAccessor test = buildAccessor(LocalDateTime.of(2008, 6, 3, 11, 5, 30), "+02:00", "Europe/Paris"); - assertEquals(DateTimeFormatter.ISO_ORDINAL_DATE.format(test), "2008-155+02:00"); + assertEquals("2008-155+02:00", DateTimeFormatter.ISO_ORDINAL_DATE.format(test)); } @Test public void test_print_isoOrdinalDate_zoned_largeYear() { TemporalAccessor test = buildAccessor(LocalDateTime.of(123456, 6, 3, 11, 5, 30), "Z", null); - assertEquals(DateTimeFormatter.ISO_ORDINAL_DATE.format(test), "+123456-155Z"); + assertEquals("+123456-155Z", DateTimeFormatter.ISO_ORDINAL_DATE.format(test)); } @Test @@ -1006,13 +1020,15 @@ public class TCKDateTimeFormatters { throw new DateTimeException("Unsupported"); } }; - assertEquals(DateTimeFormatter.ISO_ORDINAL_DATE.format(test), "2008-231"); + assertEquals("2008-231", DateTimeFormatter.ISO_ORDINAL_DATE.format(test)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_isoOrdinalDate_missingField() { - TemporalAccessor test = Year.of(2008); - DateTimeFormatter.ISO_ORDINAL_DATE.format(test); + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAccessor test = Year.of(2008); + DateTimeFormatter.ISO_ORDINAL_DATE.format(test); + }); } //----------------------------------------------------------------------- @@ -1030,9 +1046,9 @@ public class TCKDateTimeFormatters { @Test public void test_isoOrdinalDate_basics() { - assertEquals(DateTimeFormatter.ISO_ORDINAL_DATE.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ISO_ORDINAL_DATE.getZone(), null); - assertEquals(DateTimeFormatter.ISO_ORDINAL_DATE.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ISO_ORDINAL_DATE.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_ORDINAL_DATE.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_ORDINAL_DATE.getResolverStyle()); } //----------------------------------------------------------------------- @@ -1041,69 +1057,74 @@ public class TCKDateTimeFormatters { @Test public void test_print_basicIsoDate() { TemporalAccessor test = buildAccessor(LocalDateTime.of(2008, 6, 3, 11, 5, 30), null, null); - assertEquals(DateTimeFormatter.BASIC_ISO_DATE.format(test), "20080603"); + assertEquals("20080603", DateTimeFormatter.BASIC_ISO_DATE.format(test)); } @Test public void test_print_basicIsoDate_offset() { TemporalAccessor test = buildAccessor(LocalDateTime.of(2008, 6, 3, 11, 5, 30), "Z", null); - assertEquals(DateTimeFormatter.BASIC_ISO_DATE.format(test), "20080603Z"); + assertEquals("20080603Z", DateTimeFormatter.BASIC_ISO_DATE.format(test)); } @Test public void test_print_basicIsoDate_zoned() { TemporalAccessor test = buildAccessor(LocalDateTime.of(2008, 6, 3, 11, 5, 30), "+02:00", "Europe/Paris"); - assertEquals(DateTimeFormatter.BASIC_ISO_DATE.format(test), "20080603+0200"); + assertEquals("20080603+0200", DateTimeFormatter.BASIC_ISO_DATE.format(test)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_basicIsoDate_largeYear() { - TemporalAccessor test = buildAccessor(LocalDateTime.of(123456, 6, 3, 11, 5, 30), "Z", null); - DateTimeFormatter.BASIC_ISO_DATE.format(test); + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAccessor test = buildAccessor(LocalDateTime.of(123456, 6, 3, 11, 5, 30), "Z", null); + DateTimeFormatter.BASIC_ISO_DATE.format(test); + }); } @Test public void test_print_basicIsoDate_fields() { TemporalAccessor test = buildAccessor(LocalDate.of(2008, 6, 3), null, null); - assertEquals(DateTimeFormatter.BASIC_ISO_DATE.format(test), "20080603"); + assertEquals("20080603", DateTimeFormatter.BASIC_ISO_DATE.format(test)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_basicIsoDate_missingField() { - TemporalAccessor test = YearMonth.of(2008, 6); - DateTimeFormatter.BASIC_ISO_DATE.format(test); + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAccessor test = YearMonth.of(2008, 6); + DateTimeFormatter.BASIC_ISO_DATE.format(test); + }); } //----------------------------------------------------------------------- @Test public void test_parse_basicIsoDate() { LocalDate expected = LocalDate.of(2008, 6, 3); - assertEquals(DateTimeFormatter.BASIC_ISO_DATE.parse("20080603", LocalDate::from), expected); + assertEquals(expected, DateTimeFormatter.BASIC_ISO_DATE.parse("20080603", LocalDate::from)); } - @Test(expectedExceptions=DateTimeParseException.class) + @Test public void test_parse_basicIsoDate_largeYear() { - try { - LocalDate expected = LocalDate.of(123456, 6, 3); - assertEquals(DateTimeFormatter.BASIC_ISO_DATE.parse("+1234560603", LocalDate::from), expected); - } catch (DateTimeParseException ex) { - assertEquals(ex.getErrorIndex(), 0); - assertEquals(ex.getParsedString(), "+1234560603"); - throw ex; - } + Assertions.assertThrows(DateTimeParseException.class, () -> { + try { + LocalDate expected = LocalDate.of(123456, 6, 3); + assertEquals(expected, DateTimeFormatter.BASIC_ISO_DATE.parse("+1234560603", LocalDate::from)); + } catch (DateTimeParseException ex) { + assertEquals(0, ex.getErrorIndex()); + assertEquals("+1234560603", ex.getParsedString()); + throw ex; + } + }); } @Test public void test_basicIsoDate_basics() { - assertEquals(DateTimeFormatter.BASIC_ISO_DATE.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.BASIC_ISO_DATE.getZone(), null); - assertEquals(DateTimeFormatter.BASIC_ISO_DATE.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.BASIC_ISO_DATE.getChronology()); + assertEquals(null, DateTimeFormatter.BASIC_ISO_DATE.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.BASIC_ISO_DATE.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="weekDate") Iterator weekDate() { return new Iterator() { private ZonedDateTime date = ZonedDateTime.of(LocalDateTime.of(2003, 12, 29, 11, 5, 30), ZoneId.of("Europe/Paris")); @@ -1135,55 +1156,57 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="weekDate") + @ParameterizedTest + @MethodSource("weekDate") public void test_print_isoWeekDate(TemporalAccessor test, String expected) { - assertEquals(DateTimeFormatter.ISO_WEEK_DATE.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_WEEK_DATE.format(test)); } @Test public void test_print_isoWeekDate_zoned_largeYear() { TemporalAccessor test = buildAccessor(LocalDateTime.of(123456, 6, 3, 11, 5, 30), "Z", null); - assertEquals(DateTimeFormatter.ISO_WEEK_DATE.format(test), "+123456-W23-2Z"); + assertEquals("+123456-W23-2Z", DateTimeFormatter.ISO_WEEK_DATE.format(test)); } @Test public void test_print_isoWeekDate_fields() { TemporalAccessor test = buildAccessor(LocalDate.of(2004, 1, 27), null, null); - assertEquals(DateTimeFormatter.ISO_WEEK_DATE.format(test), "2004-W05-2"); + assertEquals("2004-W05-2", DateTimeFormatter.ISO_WEEK_DATE.format(test)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_isoWeekDate_missingField() { - TemporalAccessor test = YearMonth.of(2008, 6); - DateTimeFormatter.ISO_WEEK_DATE.format(test); + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAccessor test = YearMonth.of(2008, 6); + DateTimeFormatter.ISO_WEEK_DATE.format(test); + }); } //----------------------------------------------------------------------- @Test public void test_parse_weekDate() { LocalDate expected = LocalDate.of(2004, 1, 28); - assertEquals(DateTimeFormatter.ISO_WEEK_DATE.parse("2004-W05-3", LocalDate::from), expected); + assertEquals(expected, DateTimeFormatter.ISO_WEEK_DATE.parse("2004-W05-3", LocalDate::from)); } @Test public void test_parse_weekDate_largeYear() { TemporalAccessor parsed = DateTimeFormatter.ISO_WEEK_DATE.parseUnresolved("+123456-W04-5", new ParsePosition(0)); - assertEquals(parsed.getLong(IsoFields.WEEK_BASED_YEAR), 123456L); - assertEquals(parsed.getLong(IsoFields.WEEK_OF_WEEK_BASED_YEAR), 4L); - assertEquals(parsed.getLong(DAY_OF_WEEK), 5L); + assertEquals(123456L, parsed.getLong(IsoFields.WEEK_BASED_YEAR)); + assertEquals(4L, parsed.getLong(IsoFields.WEEK_OF_WEEK_BASED_YEAR)); + assertEquals(5L, parsed.getLong(DAY_OF_WEEK)); } @Test public void test_isoWeekDate_basics() { - assertEquals(DateTimeFormatter.ISO_WEEK_DATE.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.ISO_WEEK_DATE.getZone(), null); - assertEquals(DateTimeFormatter.ISO_WEEK_DATE.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.ISO_WEEK_DATE.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_WEEK_DATE.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_WEEK_DATE.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="sample_isoInstant") Object[][] provider_sample_isoInstant() { return new Object[][]{ {0, 0, "1970-01-01T00:00:00Z", null}, @@ -1203,12 +1226,13 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="sample_isoInstant") + @ParameterizedTest + @MethodSource("provider_sample_isoInstant") public void test_print_isoInstant( long instantSecs, Integer nano, String expected, Class expectedEx) { TemporalAccessor test = buildAccessorInstant(instantSecs, nano); if (expectedEx == null) { - assertEquals(DateTimeFormatter.ISO_INSTANT.format(test), expected); + assertEquals(expected, DateTimeFormatter.ISO_INSTANT.format(test)); } else { try { DateTimeFormatter.ISO_INSTANT.format(test); @@ -1219,27 +1243,27 @@ public class TCKDateTimeFormatters { } } - @Test(dataProvider="sample_isoInstant") + @ParameterizedTest + @MethodSource("provider_sample_isoInstant") public void test_parse_isoInstant( long instantSecs, Integer nano, String input, Class invalid) { if (input != null) { TemporalAccessor parsed = DateTimeFormatter.ISO_INSTANT.parseUnresolved(input, new ParsePosition(0)); - assertEquals(parsed.getLong(INSTANT_SECONDS), instantSecs); - assertEquals(parsed.getLong(NANO_OF_SECOND), (nano == null ? 0 : nano)); + assertEquals(instantSecs, parsed.getLong(INSTANT_SECONDS)); + assertEquals((nano == null ? 0 : nano), parsed.getLong(NANO_OF_SECOND)); } } @Test public void test_isoInstant_basics() { - assertEquals(DateTimeFormatter.ISO_INSTANT.getChronology(), null); - assertEquals(DateTimeFormatter.ISO_INSTANT.getZone(), null); - assertEquals(DateTimeFormatter.ISO_INSTANT.getResolverStyle(), ResolverStyle.STRICT); + assertEquals(null, DateTimeFormatter.ISO_INSTANT.getChronology()); + assertEquals(null, DateTimeFormatter.ISO_INSTANT.getZone()); + assertEquals(ResolverStyle.STRICT, DateTimeFormatter.ISO_INSTANT.getResolverStyle()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="rfc") Object[][] data_rfc() { return new Object[][] { {LocalDateTime.of(2008, 6, 3, 11, 5, 30), "Z", "Tue, 3 Jun 2008 11:05:30 GMT"}, @@ -1249,29 +1273,33 @@ public class TCKDateTimeFormatters { }; } - @Test(dataProvider="rfc") + @ParameterizedTest + @MethodSource("data_rfc") public void test_print_rfc1123(LocalDateTime base, String offsetId, String expected) { TemporalAccessor test = buildAccessor(base, offsetId, null); - assertEquals(DateTimeFormatter.RFC_1123_DATE_TIME.format(test), expected); + assertEquals(expected, DateTimeFormatter.RFC_1123_DATE_TIME.format(test)); } - @Test(dataProvider="rfc") + @ParameterizedTest + @MethodSource("data_rfc") public void test_print_rfc1123_french(LocalDateTime base, String offsetId, String expected) { TemporalAccessor test = buildAccessor(base, offsetId, null); - assertEquals(DateTimeFormatter.RFC_1123_DATE_TIME.withLocale(Locale.FRENCH).format(test), expected); + assertEquals(expected, DateTimeFormatter.RFC_1123_DATE_TIME.withLocale(Locale.FRENCH).format(test)); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_rfc1123_missingField() { - TemporalAccessor test = YearMonth.of(2008, 6); - DateTimeFormatter.RFC_1123_DATE_TIME.format(test); + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAccessor test = YearMonth.of(2008, 6); + DateTimeFormatter.RFC_1123_DATE_TIME.format(test); + }); } @Test public void test_rfc1123_basics() { - assertEquals(DateTimeFormatter.RFC_1123_DATE_TIME.getChronology(), IsoChronology.INSTANCE); - assertEquals(DateTimeFormatter.RFC_1123_DATE_TIME.getZone(), null); - assertEquals(DateTimeFormatter.RFC_1123_DATE_TIME.getResolverStyle(), ResolverStyle.SMART); + assertEquals(IsoChronology.INSTANCE, DateTimeFormatter.RFC_1123_DATE_TIME.getChronology()); + assertEquals(null, DateTimeFormatter.RFC_1123_DATE_TIME.getZone()); + assertEquals(ResolverStyle.SMART, DateTimeFormatter.RFC_1123_DATE_TIME.getResolverStyle()); } //----------------------------------------------------------------------- @@ -1403,11 +1431,11 @@ public class TCKDateTimeFormatters { private void assertParseMatch(TemporalAccessor parsed, Expected expected) { for (TemporalField field : expected.fieldValues.keySet()) { - assertEquals(parsed.isSupported(field), true); + assertEquals(true, parsed.isSupported(field)); parsed.getLong(field); } - assertEquals(parsed.query(TemporalQueries.chronology()), expected.chrono); - assertEquals(parsed.query(TemporalQueries.zoneId()), expected.zone); + assertEquals(expected.chrono, parsed.query(TemporalQueries.chronology())); + assertEquals(expected.zone, parsed.query(TemporalQueries.zoneId())); } //------------------------------------------------------------------------- diff --git a/test/jdk/java/time/tck/java/time/format/TCKDateTimeParseResolver.java b/test/jdk/java/time/tck/java/time/format/TCKDateTimeParseResolver.java index 7a33064dfd8..ec473851b2e 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKDateTimeParseResolver.java +++ b/test/jdk/java/time/tck/java/time/format/TCKDateTimeParseResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -91,8 +91,9 @@ import static java.time.temporal.ChronoField.SECOND_OF_DAY; import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoField.YEAR_OF_ERA; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.time.Instant; import java.time.LocalDate; @@ -122,13 +123,16 @@ import java.time.temporal.TemporalUnit; import java.time.temporal.ValueRange; import java.util.Map; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test parse resolving. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKDateTimeParseResolver { // TODO: tests with weird TenporalField implementations // TODO: tests with non-ISO chronologies @@ -137,7 +141,6 @@ public class TCKDateTimeParseResolver { private static final ZoneId EUROPE_PARIS = ZoneId.of("Europe/Paris"); //----------------------------------------------------------------------- - @DataProvider(name="resolveOneNoChange") Object[][] data_resolveOneNoChange() { return new Object[][]{ {YEAR, 2012}, @@ -148,20 +151,20 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveOneNoChange") + @ParameterizedTest + @MethodSource("data_resolveOneNoChange") public void test_resolveOneNoChange(TemporalField field1, long value1) { String str = Long.toString(value1); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field1).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.isSupported(field1), true); - assertEquals(accessor.getLong(field1), value1); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(true, accessor.isSupported(field1)); + assertEquals(value1, accessor.getLong(field1)); } //----------------------------------------------------------------------- - @DataProvider(name="resolveTwoNoChange") Object[][] data_resolveTwoNoChange() { return new Object[][]{ {YEAR, 2012, MONTH_OF_YEAR, 5}, @@ -185,7 +188,8 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveTwoNoChange") + @ParameterizedTest + @MethodSource("data_resolveTwoNoChange") public void test_resolveTwoNoChange(TemporalField field1, long value1, TemporalField field2, long value2) { String str = value1 + " " + value2; DateTimeFormatter f = new DateTimeFormatterBuilder() @@ -193,16 +197,15 @@ public class TCKDateTimeParseResolver { .appendValue(field2).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.isSupported(field1), true); - assertEquals(accessor.isSupported(field2), true); - assertEquals(accessor.getLong(field1), value1); - assertEquals(accessor.getLong(field2), value2); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(true, accessor.isSupported(field1)); + assertEquals(true, accessor.isSupported(field2)); + assertEquals(value1, accessor.getLong(field1)); + assertEquals(value2, accessor.getLong(field2)); } //----------------------------------------------------------------------- - @DataProvider(name="resolveThreeNoChange") Object[][] data_resolveThreeNoChange() { return new Object[][]{ {YEAR, 2012, MONTH_OF_YEAR, 5, DAY_OF_WEEK, 5}, @@ -216,7 +219,8 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveThreeNoChange") + @ParameterizedTest + @MethodSource("data_resolveThreeNoChange") public void test_resolveThreeNoChange(TemporalField field1, long value1, TemporalField field2, long value2, TemporalField field3, long value3) { String str = value1 + " " + value2 + " " + value3; DateTimeFormatter f = new DateTimeFormatterBuilder() @@ -225,20 +229,19 @@ public class TCKDateTimeParseResolver { .appendValue(field3).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.isSupported(field1), true); - assertEquals(accessor.isSupported(field2), true); - assertEquals(accessor.isSupported(field3), true); - assertEquals(accessor.getLong(field1), value1); - assertEquals(accessor.getLong(field2), value2); - assertEquals(accessor.getLong(field3), value3); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(true, accessor.isSupported(field1)); + assertEquals(true, accessor.isSupported(field2)); + assertEquals(true, accessor.isSupported(field3)); + assertEquals(value1, accessor.getLong(field1)); + assertEquals(value2, accessor.getLong(field2)); + assertEquals(value3, accessor.getLong(field3)); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="resolveOneToField") Object[][] data_resolveOneToField() { return new Object[][]{ {YEAR_OF_ERA, 2012, YEAR, 2012L, null, null}, @@ -251,7 +254,8 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveOneToField") + @ParameterizedTest + @MethodSource("data_resolveOneToField") public void test_resolveOneToField(TemporalField field1, long value1, TemporalField expectedField1, Long expectedValue1, TemporalField expectedField2, Long expectedValue2) { @@ -259,38 +263,37 @@ public class TCKDateTimeParseResolver { DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field1).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), null); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); if (expectedField1 != null) { - assertEquals(accessor.isSupported(expectedField1), true); - assertEquals(accessor.getLong(expectedField1), expectedValue1.longValue()); + assertEquals(true, accessor.isSupported(expectedField1)); + assertEquals(expectedValue1.longValue(), accessor.getLong(expectedField1)); } if (expectedField2 != null) { - assertEquals(accessor.isSupported(expectedField2), true); - assertEquals(accessor.getLong(expectedField2), expectedValue2.longValue()); + assertEquals(true, accessor.isSupported(expectedField2)); + assertEquals(expectedValue2.longValue(), accessor.getLong(expectedField2)); } } //----------------------------------------------------------------------- - @DataProvider(name="resolveOneToDate") Object[][] data_resolveOneToDate() { return new Object[][]{ {EPOCH_DAY, 32, LocalDate.of(1970, 2, 2)}, }; } - @Test(dataProvider="resolveOneToDate") + @ParameterizedTest + @MethodSource("data_resolveOneToDate") public void test_resolveOneToDate(TemporalField field1, long value1, LocalDate expectedDate) { String str = Long.toString(value1); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field1).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), expectedDate); - assertEquals(accessor.query(TemporalQueries.localTime()), null); + assertEquals(expectedDate, accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); } //----------------------------------------------------------------------- - @DataProvider(name="resolveOneToTime") Object[][] data_resolveOneToTime() { return new Object[][]{ {HOUR_OF_DAY, 8, LocalTime.of(8, 0)}, @@ -304,20 +307,20 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveOneToTime") + @ParameterizedTest + @MethodSource("data_resolveOneToTime") public void test_resolveOneToTime(TemporalField field1, long value1, LocalTime expectedTime) { String str = Long.toString(value1); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field1).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(expectedTime, accessor.query(TemporalQueries.localTime())); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="resolveTwoToField") Object[][] data_resolveTwoToField() { return new Object[][]{ // cross-check @@ -330,7 +333,8 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveTwoToField") + @ParameterizedTest + @MethodSource("data_resolveTwoToField") public void test_resolveTwoToField(TemporalField field1, long value1, TemporalField field2, long value2, TemporalField expectedField1, Long expectedValue1, @@ -341,20 +345,19 @@ public class TCKDateTimeParseResolver { .appendValue(field2).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), null); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); if (expectedField1 != null) { - assertEquals(accessor.isSupported(expectedField1), true); - assertEquals(accessor.getLong(expectedField1), expectedValue1.longValue()); + assertEquals(true, accessor.isSupported(expectedField1)); + assertEquals(expectedValue1.longValue(), accessor.getLong(expectedField1)); } if (expectedField2 != null) { - assertEquals(accessor.isSupported(expectedField2), true); - assertEquals(accessor.getLong(expectedField2), expectedValue2.longValue()); + assertEquals(true, accessor.isSupported(expectedField2)); + assertEquals(expectedValue2.longValue(), accessor.getLong(expectedField2)); } } //----------------------------------------------------------------------- - @DataProvider(name="resolveTwoToDate") Object[][] data_resolveTwoToDate() { return new Object[][]{ // merge @@ -379,7 +382,8 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveTwoToDate") + @ParameterizedTest + @MethodSource("data_resolveTwoToDate") public void test_resolveTwoToDate(TemporalField field1, long value1, TemporalField field2, long value2, LocalDate expectedDate) { @@ -389,12 +393,11 @@ public class TCKDateTimeParseResolver { .appendValue(field2).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), expectedDate); - assertEquals(accessor.query(TemporalQueries.localTime()), null); + assertEquals(expectedDate, accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); } //----------------------------------------------------------------------- - @DataProvider(name="resolveTwoToTime") Object[][] data_resolveTwoToTime() { return new Object[][]{ // merge @@ -466,7 +469,8 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveTwoToTime") + @ParameterizedTest + @MethodSource("data_resolveTwoToTime") public void test_resolveTwoToTime(TemporalField field1, long value1, TemporalField field2, long value2, LocalTime expectedTime) { @@ -476,12 +480,11 @@ public class TCKDateTimeParseResolver { .appendValue(field2).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(expectedTime, accessor.query(TemporalQueries.localTime())); } //----------------------------------------------------------------------- - @DataProvider(name="resolveThreeToDate") Object[][] data_resolveThreeToDate() { return new Object[][]{ // merge @@ -497,7 +500,8 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveThreeToDate") + @ParameterizedTest + @MethodSource("data_resolveThreeToDate") public void test_resolveThreeToDate(TemporalField field1, long value1, TemporalField field2, long value2, TemporalField field3, long value3, @@ -509,12 +513,11 @@ public class TCKDateTimeParseResolver { .appendValue(field3).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), expectedDate); - assertEquals(accessor.query(TemporalQueries.localTime()), null); + assertEquals(expectedDate, accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); } //----------------------------------------------------------------------- - @DataProvider(name="resolveFourToDate") Object[][] data_resolveFourToDate() { return new Object[][]{ // merge @@ -528,7 +531,8 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveFourToDate") + @ParameterizedTest + @MethodSource("data_resolveFourToDate") public void test_resolveFourToDate(TemporalField field1, long value1, TemporalField field2, long value2, TemporalField field3, long value3, @@ -542,12 +546,11 @@ public class TCKDateTimeParseResolver { .appendValue(field4).toFormatter(); TemporalAccessor accessor = f.parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), expectedDate); - assertEquals(accessor.query(TemporalQueries.localTime()), null); + assertEquals(expectedDate, accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); } //----------------------------------------------------------------------- - @DataProvider(name="resolveFourToTime") Object[][] data_resolveFourToTime() { return new Object[][]{ // merge @@ -597,7 +600,8 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveFourToTime") + @ParameterizedTest + @MethodSource("data_resolveFourToTime") public void test_resolveFourToTime(ResolverStyle style, long hour, long min, long sec, long nano, LocalTime expectedTime, Period excessPeriod) { DateTimeFormatter f = new DateTimeFormatterBuilder() @@ -610,9 +614,9 @@ public class TCKDateTimeParseResolver { for (ResolverStyle s : styles) { if (expectedTime != null) { TemporalAccessor accessor = f.withResolverStyle(s).parse(""); - assertEquals(accessor.query(TemporalQueries.localDate()), null, "ResolverStyle: " + s); - assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime, "ResolverStyle: " + s); - assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), excessPeriod, "ResolverStyle: " + s); + assertEquals(null, accessor.query(TemporalQueries.localDate()), "ResolverStyle: " + s); + assertEquals(expectedTime, accessor.query(TemporalQueries.localTime()), "ResolverStyle: " + s); + assertEquals(excessPeriod, accessor.query(DateTimeFormatter.parsedExcessDays()), "ResolverStyle: " + s); } else { try { f.withResolverStyle(style).parse(""); @@ -624,7 +628,8 @@ public class TCKDateTimeParseResolver { } } - @Test(dataProvider="resolveFourToTime") + @ParameterizedTest + @MethodSource("data_resolveFourToTime") public void test_resolveThreeToTime(ResolverStyle style, long hour, long min, long sec, long nano, LocalTime expectedTime, Period excessPeriod) { DateTimeFormatter f = new DateTimeFormatterBuilder() @@ -636,9 +641,9 @@ public class TCKDateTimeParseResolver { for (ResolverStyle s : styles) { if (expectedTime != null) { TemporalAccessor accessor = f.withResolverStyle(s).parse(""); - assertEquals(accessor.query(TemporalQueries.localDate()), null, "ResolverStyle: " + s); - assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime.minusNanos(nano), "ResolverStyle: " + s); - assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), excessPeriod, "ResolverStyle: " + s); + assertEquals(null, accessor.query(TemporalQueries.localDate()), "ResolverStyle: " + s); + assertEquals(expectedTime.minusNanos(nano), accessor.query(TemporalQueries.localTime()), "ResolverStyle: " + s); + assertEquals(excessPeriod, accessor.query(DateTimeFormatter.parsedExcessDays()), "ResolverStyle: " + s); } else { try { f.withResolverStyle(style).parse(""); @@ -650,7 +655,8 @@ public class TCKDateTimeParseResolver { } } - @Test(dataProvider="resolveFourToTime") + @ParameterizedTest + @MethodSource("data_resolveFourToTime") public void test_resolveFourToDateTime(ResolverStyle style, long hour, long min, long sec, long nano, LocalTime expectedTime, Period excessPeriod) { DateTimeFormatter f = new DateTimeFormatterBuilder() @@ -665,15 +671,14 @@ public class TCKDateTimeParseResolver { LocalDate expectedDate = LocalDate.of(2012, 6, 30).plus(excessPeriod); for (ResolverStyle s : styles) { TemporalAccessor accessor = f.withResolverStyle(s).parse(""); - assertEquals(accessor.query(TemporalQueries.localDate()), expectedDate, "ResolverStyle: " + s); - assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime, "ResolverStyle: " + s); - assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ZERO, "ResolverStyle: " + s); + assertEquals(expectedDate, accessor.query(TemporalQueries.localDate()), "ResolverStyle: " + s); + assertEquals(expectedTime, accessor.query(TemporalQueries.localTime()), "ResolverStyle: " + s); + assertEquals(Period.ZERO, accessor.query(DateTimeFormatter.parsedExcessDays()), "ResolverStyle: " + s); } } } //----------------------------------------------------------------------- - @DataProvider(name="resolveSecondOfDay") Object[][] data_resolveSecondOfDay() { return new Object[][]{ {STRICT, 0, 0, 0}, @@ -696,16 +701,17 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveSecondOfDay") + @ParameterizedTest + @MethodSource("data_resolveSecondOfDay") public void test_resolveSecondOfDay(ResolverStyle style, long value, Integer expectedSecond, int expectedDays) { String str = Long.toString(value); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(SECOND_OF_DAY).toFormatter(); if (expectedSecond != null) { TemporalAccessor accessor = f.withResolverStyle(style).parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.ofSecondOfDay(expectedSecond)); - assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays)); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(LocalTime.ofSecondOfDay(expectedSecond), accessor.query(TemporalQueries.localTime())); + assertEquals(Period.ofDays(expectedDays), accessor.query(DateTimeFormatter.parsedExcessDays())); } else { try { f.withResolverStyle(style).parse(str); @@ -717,7 +723,6 @@ public class TCKDateTimeParseResolver { } //----------------------------------------------------------------------- - @DataProvider(name="resolveMinuteOfDay") Object[][] data_resolveMinuteOfDay() { return new Object[][]{ {STRICT, 0, 0, 0}, @@ -740,16 +745,17 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveMinuteOfDay") + @ParameterizedTest + @MethodSource("data_resolveMinuteOfDay") public void test_resolveMinuteOfDay(ResolverStyle style, long value, Integer expectedMinute, int expectedDays) { String str = Long.toString(value); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(MINUTE_OF_DAY).toFormatter(); if (expectedMinute != null) { TemporalAccessor accessor = f.withResolverStyle(style).parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.ofSecondOfDay(expectedMinute * 60)); - assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays)); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(LocalTime.ofSecondOfDay(expectedMinute * 60), accessor.query(TemporalQueries.localTime())); + assertEquals(Period.ofDays(expectedDays), accessor.query(DateTimeFormatter.parsedExcessDays())); } else { try { f.withResolverStyle(style).parse(str); @@ -761,7 +767,6 @@ public class TCKDateTimeParseResolver { } //----------------------------------------------------------------------- - @DataProvider(name="resolveClockHourOfDay") Object[][] data_resolveClockHourOfDay() { return new Object[][]{ {STRICT, 1, 1, 0}, @@ -784,16 +789,17 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveClockHourOfDay") + @ParameterizedTest + @MethodSource("data_resolveClockHourOfDay") public void test_resolveClockHourOfDay(ResolverStyle style, long value, Integer expectedHour, int expectedDays) { String str = Long.toString(value); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(CLOCK_HOUR_OF_DAY).toFormatter(); if (expectedHour != null) { TemporalAccessor accessor = f.withResolverStyle(style).parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.of(expectedHour, 0)); - assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays)); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(LocalTime.of(expectedHour, 0), accessor.query(TemporalQueries.localTime())); + assertEquals(Period.ofDays(expectedDays), accessor.query(DateTimeFormatter.parsedExcessDays())); } else { try { f.withResolverStyle(style).parse(str); @@ -805,7 +811,6 @@ public class TCKDateTimeParseResolver { } //----------------------------------------------------------------------- - @DataProvider(name="resolveClockHourOfAmPm") Object[][] data_resolveClockHourOfAmPm() { return new Object[][]{ {STRICT, 1, 1}, @@ -828,18 +833,19 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveClockHourOfAmPm") + @ParameterizedTest + @MethodSource("data_resolveClockHourOfAmPm") public void test_resolveClockHourOfAmPm(ResolverStyle style, long value, Integer expectedValue) { String str = Long.toString(value); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(CLOCK_HOUR_OF_AMPM).toFormatter(); if (expectedValue != null) { TemporalAccessor accessor = f.withResolverStyle(style).parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.isSupported(CLOCK_HOUR_OF_AMPM), false); - assertEquals(accessor.isSupported(HOUR_OF_AMPM), true); - assertEquals(accessor.getLong(HOUR_OF_AMPM), expectedValue.longValue()); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(false, accessor.isSupported(CLOCK_HOUR_OF_AMPM)); + assertEquals(true, accessor.isSupported(HOUR_OF_AMPM)); + assertEquals(expectedValue.longValue(), accessor.getLong(HOUR_OF_AMPM)); } else { try { f.withResolverStyle(style).parse(str); @@ -851,7 +857,6 @@ public class TCKDateTimeParseResolver { } //----------------------------------------------------------------------- - @DataProvider(name="resolveAmPm") Object[][] data_resolveAmPm() { return new Object[][]{ {STRICT, 0, null, 0}, @@ -871,17 +876,18 @@ public class TCKDateTimeParseResolver { }; } - @Test(dataProvider="resolveAmPm") + @ParameterizedTest + @MethodSource("data_resolveAmPm") public void test_resolveAmPm(ResolverStyle style, long value, LocalTime expectedTime, Integer expectedValue) { String str = Long.toString(value); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(AMPM_OF_DAY).toFormatter(); if (expectedValue != null) { TemporalAccessor accessor = f.withResolverStyle(style).parse(str); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime); - assertEquals(accessor.isSupported(AMPM_OF_DAY), true); - assertEquals(accessor.getLong(AMPM_OF_DAY), expectedValue.longValue()); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(expectedTime, accessor.query(TemporalQueries.localTime())); + assertEquals(true, accessor.isSupported(AMPM_OF_DAY)); + assertEquals(expectedValue.longValue(), accessor.getLong(AMPM_OF_DAY)); } else { try { f.withResolverStyle(style).parse(str); @@ -898,9 +904,9 @@ public class TCKDateTimeParseResolver { public void test_withChronology_noOverride() { DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY, 2).toFormatter(); TemporalAccessor accessor = f.parse(""); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(1970, 1, 3)); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.query(TemporalQueries.chronology()), IsoChronology.INSTANCE); + assertEquals(LocalDate.of(1970, 1, 3), accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(IsoChronology.INSTANCE, accessor.query(TemporalQueries.chronology())); } @Test @@ -908,18 +914,18 @@ public class TCKDateTimeParseResolver { DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY, 2).toFormatter(); f = f.withChronology(MinguoChronology.INSTANCE); TemporalAccessor accessor = f.parse(""); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(1970, 1, 3)); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.query(TemporalQueries.chronology()), MinguoChronology.INSTANCE); + assertEquals(LocalDate.of(1970, 1, 3), accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(MinguoChronology.INSTANCE, accessor.query(TemporalQueries.chronology())); } @Test public void test_withChronology_parsedChronology_noOverride() { DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY, 2).appendChronologyId().toFormatter(); TemporalAccessor accessor = f.parse("ThaiBuddhist"); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(1970, 1, 3)); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.query(TemporalQueries.chronology()), ThaiBuddhistChronology.INSTANCE); + assertEquals(LocalDate.of(1970, 1, 3), accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(ThaiBuddhistChronology.INSTANCE, accessor.query(TemporalQueries.chronology())); } @Test @@ -927,9 +933,9 @@ public class TCKDateTimeParseResolver { DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY, 2).appendChronologyId().toFormatter(); f = f.withChronology(MinguoChronology.INSTANCE); TemporalAccessor accessor = f.parse("ThaiBuddhist"); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(1970, 1, 3)); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.query(TemporalQueries.chronology()), ThaiBuddhistChronology.INSTANCE); + assertEquals(LocalDate.of(1970, 1, 3), accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(ThaiBuddhistChronology.INSTANCE, accessor.query(TemporalQueries.chronology())); } //----------------------------------------------------------------------- @@ -938,9 +944,9 @@ public class TCKDateTimeParseResolver { public void test_withZone_noOverride() { DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY, 2).toFormatter(); TemporalAccessor accessor = f.parse(""); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(1970, 1, 3)); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.query(TemporalQueries.zoneId()), null); + assertEquals(LocalDate.of(1970, 1, 3), accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(null, accessor.query(TemporalQueries.zoneId())); } @Test @@ -948,18 +954,18 @@ public class TCKDateTimeParseResolver { DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY, 2).toFormatter(); f = f.withZone(EUROPE_ATHENS); TemporalAccessor accessor = f.parse(""); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(1970, 1, 3)); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.query(TemporalQueries.zoneId()), EUROPE_ATHENS); + assertEquals(LocalDate.of(1970, 1, 3), accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(EUROPE_ATHENS, accessor.query(TemporalQueries.zoneId())); } @Test public void test_withZone_parsedZone_noOverride() { DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY, 2).appendZoneId().toFormatter(); TemporalAccessor accessor = f.parse("Europe/Paris"); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(1970, 1, 3)); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.query(TemporalQueries.zoneId()), EUROPE_PARIS); + assertEquals(LocalDate.of(1970, 1, 3), accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(EUROPE_PARIS, accessor.query(TemporalQueries.zoneId())); } @Test @@ -967,9 +973,9 @@ public class TCKDateTimeParseResolver { DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY, 2).appendZoneId().toFormatter(); f = f.withZone(EUROPE_ATHENS); TemporalAccessor accessor = f.parse("Europe/Paris"); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(1970, 1, 3)); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.query(TemporalQueries.zoneId()), EUROPE_PARIS); + assertEquals(LocalDate.of(1970, 1, 3), accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(EUROPE_PARIS, accessor.query(TemporalQueries.zoneId())); } //----------------------------------------------------------------------- @@ -978,8 +984,8 @@ public class TCKDateTimeParseResolver { LocalTime lt = LocalTime.of(12, 30, 40); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(lt)).toFormatter(); TemporalAccessor accessor = f.parse("1234567890"); - assertEquals(accessor.query(TemporalQueries.localDate()), null); - assertEquals(accessor.query(TemporalQueries.localTime()), lt); + assertEquals(null, accessor.query(TemporalQueries.localDate())); + assertEquals(lt, accessor.query(TemporalQueries.localTime())); } //------------------------------------------------------------------------- @@ -988,9 +994,9 @@ public class TCKDateTimeParseResolver { LocalDate ldt = LocalDate.of(2010, 6, 30); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(ldt)).toFormatter(); TemporalAccessor accessor = f.parse("1234567890"); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(2010, 6, 30)); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.query(TemporalQueries.chronology()), IsoChronology.INSTANCE); + assertEquals(LocalDate.of(2010, 6, 30), accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(IsoChronology.INSTANCE, accessor.query(TemporalQueries.chronology())); } @Test @@ -999,24 +1005,28 @@ public class TCKDateTimeParseResolver { DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(mdt)).toFormatter(); f = f.withChronology(MinguoChronology.INSTANCE); TemporalAccessor accessor = f.parse("1234567890"); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.from(mdt)); - assertEquals(accessor.query(TemporalQueries.localTime()), null); - assertEquals(accessor.query(TemporalQueries.chronology()), MinguoChronology.INSTANCE); + assertEquals(LocalDate.from(mdt), accessor.query(TemporalQueries.localDate())); + assertEquals(null, accessor.query(TemporalQueries.localTime())); + assertEquals(MinguoChronology.INSTANCE, accessor.query(TemporalQueries.chronology())); } - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_fieldResolvesToChronoLocalDate_noOverrideChrono_wrongChrono() { - ChronoLocalDate cld = ThaiBuddhistChronology.INSTANCE.dateNow(); - DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cld)).toFormatter(); - f.parse("1234567890"); + Assertions.assertThrows(DateTimeParseException.class, () -> { + ChronoLocalDate cld = ThaiBuddhistChronology.INSTANCE.dateNow(); + DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cld)).toFormatter(); + f.parse("1234567890"); + }); } - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_fieldResolvesToChronoLocalDate_overrideChrono_wrongChrono() { - ChronoLocalDate cld = ThaiBuddhistChronology.INSTANCE.dateNow(); - DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cld)).toFormatter(); - f = f.withChronology(MinguoChronology.INSTANCE); - f.parse("1234567890"); + Assertions.assertThrows(DateTimeParseException.class, () -> { + ChronoLocalDate cld = ThaiBuddhistChronology.INSTANCE.dateNow(); + DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cld)).toFormatter(); + f = f.withChronology(MinguoChronology.INSTANCE); + f.parse("1234567890"); + }); } //------------------------------------------------------------------------- @@ -1025,9 +1035,9 @@ public class TCKDateTimeParseResolver { LocalDateTime ldt = LocalDateTime.of(2010, 6, 30, 12, 30); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(ldt)).toFormatter(); TemporalAccessor accessor = f.parse("1234567890"); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(2010, 6, 30)); - assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.of(12, 30)); - assertEquals(accessor.query(TemporalQueries.chronology()), IsoChronology.INSTANCE); + assertEquals(LocalDate.of(2010, 6, 30), accessor.query(TemporalQueries.localDate())); + assertEquals(LocalTime.of(12, 30), accessor.query(TemporalQueries.localTime())); + assertEquals(IsoChronology.INSTANCE, accessor.query(TemporalQueries.chronology())); } @Test @@ -1036,24 +1046,28 @@ public class TCKDateTimeParseResolver { DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(mdt.atTime(LocalTime.NOON))).toFormatter(); f = f.withChronology(MinguoChronology.INSTANCE); TemporalAccessor accessor = f.parse("1234567890"); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.from(mdt)); - assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.NOON); - assertEquals(accessor.query(TemporalQueries.chronology()), MinguoChronology.INSTANCE); + assertEquals(LocalDate.from(mdt), accessor.query(TemporalQueries.localDate())); + assertEquals(LocalTime.NOON, accessor.query(TemporalQueries.localTime())); + assertEquals(MinguoChronology.INSTANCE, accessor.query(TemporalQueries.chronology())); } - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_fieldResolvesToChronoLocalDateTime_noOverrideChrono_wrongChrono() { - ChronoLocalDateTime cldt = ThaiBuddhistChronology.INSTANCE.dateNow().atTime(LocalTime.NOON); - DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cldt)).toFormatter(); - f.parse("1234567890"); + Assertions.assertThrows(DateTimeParseException.class, () -> { + ChronoLocalDateTime cldt = ThaiBuddhistChronology.INSTANCE.dateNow().atTime(LocalTime.NOON); + DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cldt)).toFormatter(); + f.parse("1234567890"); + }); } - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_fieldResolvesToChronoLocalDateTime_overrideChrono_wrongChrono() { - ChronoLocalDateTime cldt = ThaiBuddhistChronology.INSTANCE.dateNow().atTime(LocalTime.NOON); - DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cldt)).toFormatter(); - f = f.withChronology(MinguoChronology.INSTANCE); - f.parse("1234567890"); + Assertions.assertThrows(DateTimeParseException.class, () -> { + ChronoLocalDateTime cldt = ThaiBuddhistChronology.INSTANCE.dateNow().atTime(LocalTime.NOON); + DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cldt)).toFormatter(); + f = f.withChronology(MinguoChronology.INSTANCE); + f.parse("1234567890"); + }); } //------------------------------------------------------------------------- @@ -1062,10 +1076,10 @@ public class TCKDateTimeParseResolver { ZonedDateTime zdt = ZonedDateTime.of(2010, 6, 30, 12, 30, 0, 0, EUROPE_PARIS); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(zdt)).toFormatter(); TemporalAccessor accessor = f.parse("1234567890"); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(2010, 6, 30)); - assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.of(12, 30)); - assertEquals(accessor.query(TemporalQueries.chronology()), IsoChronology.INSTANCE); - assertEquals(accessor.query(TemporalQueries.zoneId()), EUROPE_PARIS); + assertEquals(LocalDate.of(2010, 6, 30), accessor.query(TemporalQueries.localDate())); + assertEquals(LocalTime.of(12, 30), accessor.query(TemporalQueries.localTime())); + assertEquals(IsoChronology.INSTANCE, accessor.query(TemporalQueries.chronology())); + assertEquals(EUROPE_PARIS, accessor.query(TemporalQueries.zoneId())); } @Test @@ -1075,25 +1089,29 @@ public class TCKDateTimeParseResolver { DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(mzdt)).toFormatter(); f = f.withChronology(MinguoChronology.INSTANCE); TemporalAccessor accessor = f.parse("1234567890"); - assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.from(mdt)); - assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.NOON); - assertEquals(accessor.query(TemporalQueries.chronology()), MinguoChronology.INSTANCE); - assertEquals(accessor.query(TemporalQueries.zoneId()), EUROPE_PARIS); + assertEquals(LocalDate.from(mdt), accessor.query(TemporalQueries.localDate())); + assertEquals(LocalTime.NOON, accessor.query(TemporalQueries.localTime())); + assertEquals(MinguoChronology.INSTANCE, accessor.query(TemporalQueries.chronology())); + assertEquals(EUROPE_PARIS, accessor.query(TemporalQueries.zoneId())); } - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_fieldResolvesToChronoZonedDateTime_noOverrideChrono_wrongChrono() { - ChronoZonedDateTime cldt = ThaiBuddhistChronology.INSTANCE.dateNow().atTime(LocalTime.NOON).atZone(EUROPE_PARIS); - DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cldt)).toFormatter(); - f.parse("1234567890"); + Assertions.assertThrows(DateTimeParseException.class, () -> { + ChronoZonedDateTime cldt = ThaiBuddhistChronology.INSTANCE.dateNow().atTime(LocalTime.NOON).atZone(EUROPE_PARIS); + DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cldt)).toFormatter(); + f.parse("1234567890"); + }); } - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_fieldResolvesToChronoZonedDateTime_overrideChrono_wrongChrono() { - ChronoZonedDateTime cldt = ThaiBuddhistChronology.INSTANCE.dateNow().atTime(LocalTime.NOON).atZone(EUROPE_PARIS); - DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cldt)).toFormatter(); - f = f.withChronology(MinguoChronology.INSTANCE); - f.parse("1234567890"); + Assertions.assertThrows(DateTimeParseException.class, () -> { + ChronoZonedDateTime cldt = ThaiBuddhistChronology.INSTANCE.dateNow().atTime(LocalTime.NOON).atZone(EUROPE_PARIS); + DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cldt)).toFormatter(); + f = f.withChronology(MinguoChronology.INSTANCE); + f.parse("1234567890"); + }); } @Test @@ -1101,15 +1119,17 @@ public class TCKDateTimeParseResolver { ZonedDateTime zdt = ZonedDateTime.of(2010, 6, 30, 12, 30, 0, 0, EUROPE_PARIS); DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(zdt)).toFormatter(); f = f.withZone(EUROPE_PARIS); - assertEquals(f.parse("1234567890", ZonedDateTime::from), zdt); + assertEquals(zdt, f.parse("1234567890", ZonedDateTime::from)); } - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_fieldResolvesToChronoZonedDateTime_overrideZone_wrongZone() { - ZonedDateTime zdt = ZonedDateTime.of(2010, 6, 30, 12, 30, 0, 0, EUROPE_PARIS); - DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(zdt)).toFormatter(); - f = f.withZone(ZoneId.of("Europe/London")); - f.parse("1234567890"); + Assertions.assertThrows(DateTimeParseException.class, () -> { + ZonedDateTime zdt = ZonedDateTime.of(2010, 6, 30, 12, 30, 0, 0, EUROPE_PARIS); + DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(zdt)).toFormatter(); + f = f.withZone(ZoneId.of("Europe/London")); + f.parse("1234567890"); + }); } //------------------------------------------------------------------------- @@ -1170,15 +1190,15 @@ public class TCKDateTimeParseResolver { .appendValue(INSTANT_SECONDS).toFormatter(); TemporalAccessor acc = fmt.parse("86402"); Instant expected = Instant.ofEpochSecond(86402); - assertEquals(acc.isSupported(INSTANT_SECONDS), true); - assertEquals(acc.isSupported(NANO_OF_SECOND), true); - assertEquals(acc.isSupported(MICRO_OF_SECOND), true); - assertEquals(acc.isSupported(MILLI_OF_SECOND), true); - assertEquals(acc.getLong(INSTANT_SECONDS), 86402L); - assertEquals(acc.getLong(NANO_OF_SECOND), 0L); - assertEquals(acc.getLong(MICRO_OF_SECOND), 0L); - assertEquals(acc.getLong(MILLI_OF_SECOND), 0L); - assertEquals(Instant.from(acc), expected); + assertEquals(true, acc.isSupported(INSTANT_SECONDS)); + assertEquals(true, acc.isSupported(NANO_OF_SECOND)); + assertEquals(true, acc.isSupported(MICRO_OF_SECOND)); + assertEquals(true, acc.isSupported(MILLI_OF_SECOND)); + assertEquals(86402L, acc.getLong(INSTANT_SECONDS)); + assertEquals(0L, acc.getLong(NANO_OF_SECOND)); + assertEquals(0L, acc.getLong(MICRO_OF_SECOND)); + assertEquals(0L, acc.getLong(MILLI_OF_SECOND)); + assertEquals(expected, Instant.from(acc)); } @Test @@ -1187,15 +1207,15 @@ public class TCKDateTimeParseResolver { .appendValue(INSTANT_SECONDS).appendLiteral('.').appendValue(NANO_OF_SECOND).toFormatter(); TemporalAccessor acc = fmt.parse("86402.123456789"); Instant expected = Instant.ofEpochSecond(86402, 123456789); - assertEquals(acc.isSupported(INSTANT_SECONDS), true); - assertEquals(acc.isSupported(NANO_OF_SECOND), true); - assertEquals(acc.isSupported(MICRO_OF_SECOND), true); - assertEquals(acc.isSupported(MILLI_OF_SECOND), true); - assertEquals(acc.getLong(INSTANT_SECONDS), 86402L); - assertEquals(acc.getLong(NANO_OF_SECOND), 123456789L); - assertEquals(acc.getLong(MICRO_OF_SECOND), 123456L); - assertEquals(acc.getLong(MILLI_OF_SECOND), 123L); - assertEquals(Instant.from(acc), expected); + assertEquals(true, acc.isSupported(INSTANT_SECONDS)); + assertEquals(true, acc.isSupported(NANO_OF_SECOND)); + assertEquals(true, acc.isSupported(MICRO_OF_SECOND)); + assertEquals(true, acc.isSupported(MILLI_OF_SECOND)); + assertEquals(86402L, acc.getLong(INSTANT_SECONDS)); + assertEquals(123456789L, acc.getLong(NANO_OF_SECOND)); + assertEquals(123456L, acc.getLong(MICRO_OF_SECOND)); + assertEquals(123L, acc.getLong(MILLI_OF_SECOND)); + assertEquals(expected, Instant.from(acc)); } // SPEC: ChronoField.SECOND_OF_DAY @@ -1204,14 +1224,14 @@ public class TCKDateTimeParseResolver { DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendValue(SECOND_OF_DAY).toFormatter(); TemporalAccessor acc = fmt.parse("864"); - assertEquals(acc.isSupported(SECOND_OF_DAY), true); - assertEquals(acc.isSupported(NANO_OF_SECOND), true); - assertEquals(acc.isSupported(MICRO_OF_SECOND), true); - assertEquals(acc.isSupported(MILLI_OF_SECOND), true); - assertEquals(acc.getLong(SECOND_OF_DAY), 864L); - assertEquals(acc.getLong(NANO_OF_SECOND), 0L); - assertEquals(acc.getLong(MICRO_OF_SECOND), 0L); - assertEquals(acc.getLong(MILLI_OF_SECOND), 0L); + assertEquals(true, acc.isSupported(SECOND_OF_DAY)); + assertEquals(true, acc.isSupported(NANO_OF_SECOND)); + assertEquals(true, acc.isSupported(MICRO_OF_SECOND)); + assertEquals(true, acc.isSupported(MILLI_OF_SECOND)); + assertEquals(864L, acc.getLong(SECOND_OF_DAY)); + assertEquals(0L, acc.getLong(NANO_OF_SECOND)); + assertEquals(0L, acc.getLong(MICRO_OF_SECOND)); + assertEquals(0L, acc.getLong(MILLI_OF_SECOND)); } @Test @@ -1219,14 +1239,14 @@ public class TCKDateTimeParseResolver { DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendValue(SECOND_OF_DAY).appendLiteral('.').appendValue(NANO_OF_SECOND).toFormatter(); TemporalAccessor acc = fmt.parse("864.123456789"); - assertEquals(acc.isSupported(SECOND_OF_DAY), true); - assertEquals(acc.isSupported(NANO_OF_SECOND), true); - assertEquals(acc.isSupported(MICRO_OF_SECOND), true); - assertEquals(acc.isSupported(MILLI_OF_SECOND), true); - assertEquals(acc.getLong(SECOND_OF_DAY), 864L); - assertEquals(acc.getLong(NANO_OF_SECOND), 123456789L); - assertEquals(acc.getLong(MICRO_OF_SECOND), 123456L); - assertEquals(acc.getLong(MILLI_OF_SECOND), 123L); + assertEquals(true, acc.isSupported(SECOND_OF_DAY)); + assertEquals(true, acc.isSupported(NANO_OF_SECOND)); + assertEquals(true, acc.isSupported(MICRO_OF_SECOND)); + assertEquals(true, acc.isSupported(MILLI_OF_SECOND)); + assertEquals(864L, acc.getLong(SECOND_OF_DAY)); + assertEquals(123456789L, acc.getLong(NANO_OF_SECOND)); + assertEquals(123456L, acc.getLong(MICRO_OF_SECOND)); + assertEquals(123L, acc.getLong(MILLI_OF_SECOND)); } // SPEC: ChronoField.SECOND_OF_MINUTE @@ -1235,14 +1255,14 @@ public class TCKDateTimeParseResolver { DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendValue(SECOND_OF_MINUTE).toFormatter(); TemporalAccessor acc = fmt.parse("32"); - assertEquals(acc.isSupported(SECOND_OF_MINUTE), true); - assertEquals(acc.isSupported(NANO_OF_SECOND), true); - assertEquals(acc.isSupported(MICRO_OF_SECOND), true); - assertEquals(acc.isSupported(MILLI_OF_SECOND), true); - assertEquals(acc.getLong(SECOND_OF_MINUTE), 32L); - assertEquals(acc.getLong(NANO_OF_SECOND), 0L); - assertEquals(acc.getLong(MICRO_OF_SECOND), 0L); - assertEquals(acc.getLong(MILLI_OF_SECOND), 0L); + assertEquals(true, acc.isSupported(SECOND_OF_MINUTE)); + assertEquals(true, acc.isSupported(NANO_OF_SECOND)); + assertEquals(true, acc.isSupported(MICRO_OF_SECOND)); + assertEquals(true, acc.isSupported(MILLI_OF_SECOND)); + assertEquals(32L, acc.getLong(SECOND_OF_MINUTE)); + assertEquals(0L, acc.getLong(NANO_OF_SECOND)); + assertEquals(0L, acc.getLong(MICRO_OF_SECOND)); + assertEquals(0L, acc.getLong(MILLI_OF_SECOND)); } @Test @@ -1250,14 +1270,14 @@ public class TCKDateTimeParseResolver { DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendValue(SECOND_OF_MINUTE).appendLiteral('.').appendValue(NANO_OF_SECOND).toFormatter(); TemporalAccessor acc = fmt.parse("32.123456789"); - assertEquals(acc.isSupported(SECOND_OF_MINUTE), true); - assertEquals(acc.isSupported(NANO_OF_SECOND), true); - assertEquals(acc.isSupported(MICRO_OF_SECOND), true); - assertEquals(acc.isSupported(MILLI_OF_SECOND), true); - assertEquals(acc.getLong(SECOND_OF_MINUTE), 32L); - assertEquals(acc.getLong(NANO_OF_SECOND), 123456789L); - assertEquals(acc.getLong(MICRO_OF_SECOND), 123456L); - assertEquals(acc.getLong(MILLI_OF_SECOND), 123L); + assertEquals(true, acc.isSupported(SECOND_OF_MINUTE)); + assertEquals(true, acc.isSupported(NANO_OF_SECOND)); + assertEquals(true, acc.isSupported(MICRO_OF_SECOND)); + assertEquals(true, acc.isSupported(MILLI_OF_SECOND)); + assertEquals(32L, acc.getLong(SECOND_OF_MINUTE)); + assertEquals(123456789L, acc.getLong(NANO_OF_SECOND)); + assertEquals(123456L, acc.getLong(MICRO_OF_SECOND)); + assertEquals(123L, acc.getLong(MILLI_OF_SECOND)); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKDateTimeTextPrinting.java b/test/jdk/java/time/tck/java/time/format/TCKDateTimeTextPrinting.java index b547a837fb8..71d0ed69731 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKDateTimeTextPrinting.java +++ b/test/jdk/java/time/tck/java/time/format/TCKDateTimeTextPrinting.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -62,7 +62,8 @@ package tck.java.time.format; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDateTime; import java.time.Month; @@ -74,25 +75,26 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test text printing. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKDateTimeTextPrinting { private DateTimeFormatterBuilder builder; - @BeforeMethod + @BeforeEach public void setUp() { builder = new DateTimeFormatterBuilder(); } //----------------------------------------------------------------------- - @DataProvider(name="printText") Object[][] data_text() { return new Object[][] { {DAY_OF_WEEK, TextStyle.FULL, 1, "Monday"}, @@ -135,23 +137,25 @@ public class TCKDateTimeTextPrinting { }; } - @Test(dataProvider="printText") + @ParameterizedTest + @MethodSource("data_text") public void test_appendText2arg_format(TemporalField field, TextStyle style, int value, String expected) throws Exception { DateTimeFormatter f = builder.appendText(field, style).toFormatter(Locale.ENGLISH); LocalDateTime dt = LocalDateTime.of(2010, 1, 1, 0, 0); dt = dt.with(field, value); String text = f.format(dt); - assertEquals(text, expected); + assertEquals(expected, text); } - @Test(dataProvider="printText") + @ParameterizedTest + @MethodSource("data_text") public void test_appendText1arg_format(TemporalField field, TextStyle style, int value, String expected) throws Exception { if (style == TextStyle.FULL) { DateTimeFormatter f = builder.appendText(field).toFormatter(Locale.ENGLISH); LocalDateTime dt = LocalDateTime.of(2010, 1, 1, 0, 0); dt = dt.with(field, value); String text = f.format(dt); - assertEquals(text, expected); + assertEquals(expected, text); } } @@ -175,7 +179,7 @@ public class TCKDateTimeTextPrinting { DateTimeFormatter f = builder.toFormatter(); LocalDateTime dt = LocalDateTime.of(2010, 1, 1, 0, 0); for (Month month : Month.values()) { - assertEquals(f.format(dt.with(month)), map.get((long) month.getValue())); + assertEquals(map.get((long) month.getValue()), f.format(dt.with(month))); } } @@ -188,9 +192,9 @@ public class TCKDateTimeTextPrinting { builder.appendText(DAY_OF_MONTH, map); DateTimeFormatter f = builder.toFormatter(); LocalDateTime dt = LocalDateTime.of(2010, 1, 1, 0, 0); - assertEquals(f.format(dt.withDayOfMonth(1)), "1st"); - assertEquals(f.format(dt.withDayOfMonth(2)), "2nd"); - assertEquals(f.format(dt.withDayOfMonth(3)), "3rd"); + assertEquals("1st", f.format(dt.withDayOfMonth(1))); + assertEquals("2nd", f.format(dt.withDayOfMonth(2))); + assertEquals("3rd", f.format(dt.withDayOfMonth(3))); } @Test @@ -200,7 +204,7 @@ public class TCKDateTimeTextPrinting { builder.appendText(MONTH_OF_YEAR, map); DateTimeFormatter f = builder.toFormatter(); LocalDateTime dt = LocalDateTime.of(2010, 2, 1, 0, 0); - assertEquals(f.format(dt), "2"); + assertEquals("2", f.format(dt)); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKDecimalStyle.java b/test/jdk/java/time/tck/java/time/format/TCKDecimalStyle.java index f5a4321ad24..bd45c9a6d79 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKDecimalStyle.java +++ b/test/jdk/java/time/tck/java/time/format/TCKDecimalStyle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,71 +59,70 @@ */ package tck.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.format.DecimalStyle; import java.util.Arrays; import java.util.Locale; import java.util.Set; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test DecimalStyle. */ -@Test public class TCKDecimalStyle { @Test public void test_getAvailableLocales() { Set locales = DecimalStyle.getAvailableLocales(); - assertEquals(locales.size() > 0, true, "locales: " + locales); - assertEquals(locales.contains(Locale.US), true, "Locale.US not found in available Locales"); + assertEquals(true, locales.size() > 0, "locales: " + locales); + assertEquals(true, locales.contains(Locale.US), "Locale.US not found in available Locales"); } //----------------------------------------------------------------------- @Test public void test_of_Locale() { DecimalStyle loc1 = DecimalStyle.of(Locale.CANADA); - assertEquals(loc1.getZeroDigit(), '0'); - assertEquals(loc1.getPositiveSign(), '+'); - assertEquals(loc1.getNegativeSign(), '-'); - assertEquals(loc1.getDecimalSeparator(), '.'); + assertEquals('0', loc1.getZeroDigit()); + assertEquals('+', loc1.getPositiveSign()); + assertEquals('-', loc1.getNegativeSign()); + assertEquals('.', loc1.getDecimalSeparator()); } //----------------------------------------------------------------------- @Test public void test_STANDARD() { DecimalStyle loc1 = DecimalStyle.STANDARD; - assertEquals(loc1.getZeroDigit(), '0'); - assertEquals(loc1.getPositiveSign(), '+'); - assertEquals(loc1.getNegativeSign(), '-'); - assertEquals(loc1.getDecimalSeparator(), '.'); + assertEquals('0', loc1.getZeroDigit()); + assertEquals('+', loc1.getPositiveSign()); + assertEquals('-', loc1.getNegativeSign()); + assertEquals('.', loc1.getDecimalSeparator()); } //----------------------------------------------------------------------- @Test public void test_zeroDigit() { DecimalStyle base = DecimalStyle.STANDARD; - assertEquals(base.withZeroDigit('A').getZeroDigit(), 'A'); + assertEquals('A', base.withZeroDigit('A').getZeroDigit()); } @Test public void test_positiveSign() { DecimalStyle base = DecimalStyle.STANDARD; - assertEquals(base.withPositiveSign('A').getPositiveSign(), 'A'); + assertEquals('A', base.withPositiveSign('A').getPositiveSign()); } @Test public void test_negativeSign() { DecimalStyle base = DecimalStyle.STANDARD; - assertEquals(base.withNegativeSign('A').getNegativeSign(), 'A'); + assertEquals('A', base.withNegativeSign('A').getNegativeSign()); } @Test public void test_decimalSeparator() { DecimalStyle base = DecimalStyle.STANDARD; - assertEquals(base.withDecimalSeparator('A').getDecimalSeparator(), 'A'); + assertEquals('A', base.withDecimalSeparator('A').getDecimalSeparator()); } //----------------------------------------------------------------------- @@ -166,46 +165,46 @@ public class TCKDecimalStyle { public void test_equalsHashCode1() { DecimalStyle a = DecimalStyle.STANDARD; DecimalStyle b = DecimalStyle.STANDARD; - assertEquals(a.equals(b), true); - assertEquals(b.equals(a), true); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(true, a.equals(b)); + assertEquals(true, b.equals(a)); + assertEquals(b.hashCode(), a.hashCode()); } @Test public void test_equalsHashCode2() { DecimalStyle a = DecimalStyle.STANDARD.withZeroDigit('A'); DecimalStyle b = DecimalStyle.STANDARD.withZeroDigit('A'); - assertEquals(a.equals(b), true); - assertEquals(b.equals(a), true); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(true, a.equals(b)); + assertEquals(true, b.equals(a)); + assertEquals(b.hashCode(), a.hashCode()); } @Test public void test_equalsHashCode3() { DecimalStyle a = DecimalStyle.STANDARD.withZeroDigit('A'); DecimalStyle b = DecimalStyle.STANDARD.withDecimalSeparator('A'); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); } @Test public void test_equalsHashCode_bad() { DecimalStyle a = DecimalStyle.STANDARD; - assertEquals(a.equals(""), false); - assertEquals(a.equals(null), false); + assertEquals(false, a.equals("")); + assertEquals(false, a.equals(null)); } //----------------------------------------------------------------------- @Test public void test_toString_base() { DecimalStyle base = DecimalStyle.STANDARD; - assertEquals(base.toString(), "DecimalStyle[0+-.]"); + assertEquals("DecimalStyle[0+-.]", base.toString()); } @Test public void test_toString_altered() { DecimalStyle base = DecimalStyle.of(Locale.US).withZeroDigit('A').withDecimalSeparator('@'); - assertEquals(base.toString(), "DecimalStyle[A+-@]"); + assertEquals("DecimalStyle[A+-@]", base.toString()); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKFormatStyle.java b/test/jdk/java/time/tck/java/time/format/TCKFormatStyle.java index d8a754b0271..5c9beae4048 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKFormatStyle.java +++ b/test/jdk/java/time/tck/java/time/format/TCKFormatStyle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -64,15 +64,16 @@ import java.time.format.FormatStyle; import java.time.temporal.Temporal; import java.util.Locale; -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKFormatStyle { private static final ZoneId ZONEID_PARIS = ZoneId.of("Europe/Paris"); @@ -84,11 +85,10 @@ public class TCKFormatStyle { @Test public void test_valueOf() { for (FormatStyle style : FormatStyle.values()) { - assertEquals(FormatStyle.valueOf(style.name()), style); + assertEquals(style, FormatStyle.valueOf(style.name())); } } - @DataProvider(name="formatStyle") Object[][] data_formatStyle() { return new Object[][] { {ZonedDateTime.of(LocalDateTime.of(2001, 10, 2, 1, 2, 3), ZONEID_PARIS), FormatStyle.FULL, "Tuesday, October 2, 2001, 1:02:03\u202fAM Central European Summer Time Europe/Paris"}, @@ -103,11 +103,12 @@ public class TCKFormatStyle { }; } - @Test(dataProvider = "formatStyle") + @ParameterizedTest + @MethodSource("data_formatStyle") public void test_formatStyle(Temporal temporal, FormatStyle style, String formattedStr) { DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); DateTimeFormatter formatter = builder.appendLocalized(style, style).appendLiteral(" ").appendZoneOrOffsetId().toFormatter(); formatter = formatter.withLocale(Locale.US); - assertEquals(formatter.format(temporal), formattedStr); + assertEquals(formattedStr, formatter.format(temporal)); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKInstantPrinterParser.java b/test/jdk/java/time/tck/java/time/format/TCKInstantPrinterParser.java index 49b772bf82b..56034337646 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKInstantPrinterParser.java +++ b/test/jdk/java/time/tck/java/time/format/TCKInstantPrinterParser.java @@ -59,10 +59,8 @@ */ package tck.java.time.format; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; -import java.time.DateTimeException; import java.time.Instant; import java.time.OffsetDateTime; import java.time.Period; @@ -73,8 +71,11 @@ import java.time.format.DateTimeParseException; import java.time.format.ResolverStyle; import java.time.temporal.TemporalAccessor; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /* * @test @@ -84,10 +85,9 @@ import org.testng.annotations.Test; /** * Test DateTimeFormatterBuilder.appendInstant(). */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKInstantPrinterParser { - @DataProvider(name="printGrouped") Object[][] data_printGrouped() { return new Object[][] { {0, 0, "1970-01-01T00:00:00Z"}, @@ -113,15 +113,15 @@ public class TCKInstantPrinterParser { }; } - @Test(dataProvider="printGrouped") + @ParameterizedTest + @MethodSource("data_printGrouped") public void test_print_grouped(long instantSecs, int nano, String expected) { Instant instant = Instant.ofEpochSecond(instantSecs, nano); DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant().toFormatter(); - assertEquals(f.format(instant), expected); + assertEquals(expected, f.format(instant)); } //----------------------------------------------------------------------- - @DataProvider(name="printDigits") Object[][] data_printDigits() { return new Object[][] { {-1, 0, 0, "1970-01-01T00:00:00Z"}, @@ -191,15 +191,15 @@ public class TCKInstantPrinterParser { }; } - @Test(dataProvider="printDigits") + @ParameterizedTest + @MethodSource("data_printDigits") public void test_print_digits(int fractionalDigits, long instantSecs, int nano, String expected) { Instant instant = Instant.ofEpochSecond(instantSecs, nano); DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant(fractionalDigits).toFormatter(); - assertEquals(f.format(instant), expected); + assertEquals(expected, f.format(instant)); } //----------------------------------------------------------------------- - @DataProvider(name="parseDigits") Object[][] data_parse_digits() { return new Object[][] { {0, 0, "1970-01-01T00:00:00Z"}, @@ -236,16 +236,16 @@ public class TCKInstantPrinterParser { }; } - @Test(dataProvider="parseDigits") + @ParameterizedTest + @MethodSource("data_parse_digits") public void test_parse_digitsMinusOne(long instantSecs, int nano, String input) { Instant expected = Instant.ofEpochSecond(instantSecs, nano); DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant(-1).toFormatter(); - assertEquals(f.parse(input, Instant::from), expected); - assertEquals(f.parse(input).query(DateTimeFormatter.parsedExcessDays()), Period.ZERO); - assertEquals(f.parse(input).query(DateTimeFormatter.parsedLeapSecond()), Boolean.FALSE); + assertEquals(expected, f.parse(input, Instant::from)); + assertEquals(Period.ZERO, f.parse(input).query(DateTimeFormatter.parsedExcessDays())); + assertEquals(Boolean.FALSE, f.parse(input).query(DateTimeFormatter.parsedLeapSecond())); } - @DataProvider(name="parseNineDigits") Object[][] data_parse_ninedigits() { return new Object[][] { {0, 0, "1970-01-01T00:00:00.000000000Z"}, @@ -264,16 +264,16 @@ public class TCKInstantPrinterParser { }; } - @Test(dataProvider="parseNineDigits") + @ParameterizedTest + @MethodSource("data_parse_ninedigits") public void test_parse_digitsNine(long instantSecs, int nano, String input) { DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant(9).toFormatter(); Instant expected = Instant.ofEpochSecond(instantSecs, nano); - assertEquals(f.parse(input, Instant::from), expected); - assertEquals(f.parse(input).query(DateTimeFormatter.parsedExcessDays()), Period.ZERO); - assertEquals(f.parse(input).query(DateTimeFormatter.parsedLeapSecond()), Boolean.FALSE); + assertEquals(expected, f.parse(input, Instant::from)); + assertEquals(Period.ZERO, f.parse(input).query(DateTimeFormatter.parsedExcessDays())); + assertEquals(Boolean.FALSE, f.parse(input).query(DateTimeFormatter.parsedLeapSecond())); } - @DataProvider(name="parseMaxMinInstant") Object[][] data_parse_MaxMinInstant() { return new Object[][] { {"+1000000000-12-31T23:59:59.999999999-01:00"}, @@ -281,10 +281,13 @@ public class TCKInstantPrinterParser { }; } - @Test(dataProvider="parseMaxMinInstant", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("data_parse_MaxMinInstant") public void test_invalid_Instant(String input) { - DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant(-1).toFormatter(); - f.parse(input, Instant::from); + Assertions.assertThrows(DateTimeParseException.class, () -> { + DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant(-1).toFormatter(); + f.parse(input, Instant::from); + }); } @Test @@ -293,9 +296,9 @@ public class TCKInstantPrinterParser { DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant(-1).toFormatter(); for (ResolverStyle style : ResolverStyle.values()) { TemporalAccessor parsed = f.withResolverStyle(style).parse("1970-02-03T24:00:00Z"); - assertEquals(parsed.query(Instant::from), expected); - assertEquals(parsed.query(DateTimeFormatter.parsedExcessDays()), Period.ZERO); - assertEquals(parsed.query(DateTimeFormatter.parsedLeapSecond()), Boolean.FALSE); + assertEquals(expected, parsed.query(Instant::from)); + assertEquals(Period.ZERO, parsed.query(DateTimeFormatter.parsedExcessDays())); + assertEquals(Boolean.FALSE, parsed.query(DateTimeFormatter.parsedLeapSecond())); } } @@ -305,9 +308,9 @@ public class TCKInstantPrinterParser { DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant(-1).toFormatter(); for (ResolverStyle style : ResolverStyle.values()) { TemporalAccessor parsed = f.withResolverStyle(style).parse("1970-02-03T23:59:60.123456789Z"); - assertEquals(parsed.query(Instant::from), expected); - assertEquals(parsed.query(DateTimeFormatter.parsedExcessDays()), Period.ZERO); - assertEquals(parsed.query(DateTimeFormatter.parsedLeapSecond()), Boolean.TRUE); + assertEquals(expected, parsed.query(Instant::from)); + assertEquals(Period.ZERO, parsed.query(DateTimeFormatter.parsedExcessDays())); + assertEquals(Boolean.TRUE, parsed.query(DateTimeFormatter.parsedLeapSecond())); } } @@ -464,14 +467,14 @@ public class TCKInstantPrinterParser { } //----------------------------------------------------------------------- - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendInstant_tooSmall() { - new DateTimeFormatterBuilder().appendInstant(-2); + Assertions.assertThrows(IllegalArgumentException.class, () -> new DateTimeFormatterBuilder().appendInstant(-2)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendInstant_tooBig() { - new DateTimeFormatterBuilder().appendInstant(10); + Assertions.assertThrows(IllegalArgumentException.class, () -> new DateTimeFormatterBuilder().appendInstant(10)); } //------------------------------------------------------------------------ @@ -479,7 +482,7 @@ public class TCKInstantPrinterParser { public void test_equality() { Instant instant1 = Instant.parse("2018-09-12T22:15:51+05:30"); Instant instant2 = Instant.parse("2018-09-12T16:45:51Z"); - assertEquals(instant2, instant1); + assertEquals(instant1, instant2); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKLocalizedFieldParser.java b/test/jdk/java/time/tck/java/time/format/TCKLocalizedFieldParser.java index 6286a1dd321..af1e48107bf 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKLocalizedFieldParser.java +++ b/test/jdk/java/time/tck/java/time/format/TCKLocalizedFieldParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -60,7 +60,8 @@ package tck.java.time.format; import static java.time.temporal.ChronoField.YEAR_OF_ERA; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.ParsePosition; import java.time.LocalDate; @@ -72,21 +73,24 @@ import java.time.temporal.TemporalField; import java.time.temporal.WeekFields; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.format.AbstractTestPrinterParser; /** * Test TCKLocalizedFieldParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKLocalizedFieldParser extends AbstractTestPrinterParser { public static final WeekFields WEEKDEF = WeekFields.of(Locale.US); public static final TemporalField WEEK_BASED_YEAR = WEEKDEF.weekBasedYear(); public static final TemporalField WEEK_OF_WEEK_BASED_YEAR = WEEKDEF.weekOfWeekBasedYear(); public static final TemporalField DAY_OF_WEEK = WEEKDEF.dayOfWeek(); //----------------------------------------------------------------------- - @DataProvider(name="FieldPatterns") Object[][] provider_fieldPatterns() { return new Object[][] { {"e", "6", 0, 1, 6}, @@ -101,7 +105,8 @@ public class TCKLocalizedFieldParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="FieldPatterns") + @ParameterizedTest + @MethodSource("provider_fieldPatterns") public void test_parse_textField(String pattern, String text, int pos, int expectedPos, long expectedValue) { WeekFields weekDef = WeekFields.of(locale); TemporalField field = null; @@ -128,16 +133,15 @@ public class TCKLocalizedFieldParser extends AbstractTestPrinterParser { DateTimeFormatter dtf = b.toFormatter(locale); TemporalAccessor parsed = dtf.parseUnresolved(text, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), expectedPos); + assertEquals(expectedPos, ppos.getErrorIndex()); } else { - assertEquals(ppos.getIndex(), expectedPos, "Incorrect ending parse position"); + assertEquals(expectedPos, ppos.getIndex(), "Incorrect ending parse position"); long value = parsed.getLong(field); - assertEquals(value, expectedValue, "Value incorrect for " + field); + assertEquals(expectedValue, value, "Value incorrect for " + field); } } //----------------------------------------------------------------------- - @DataProvider(name="LocalWeekMonthYearPatterns") Object[][] provider_patternLocalDate() { return new Object[][] { {"e W M y", "1 1 1 2012", 0, 10, LocalDate.of(2012, 1, 1)}, @@ -153,28 +157,28 @@ public class TCKLocalizedFieldParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="LocalWeekMonthYearPatterns") + @ParameterizedTest + @MethodSource("provider_patternLocalDate") public void test_parse_textLocalDate(String pattern, String text, int pos, int expectedPos, LocalDate expectedValue) { ParsePosition ppos = new ParsePosition(pos); DateTimeFormatterBuilder b = new DateTimeFormatterBuilder().appendPattern(pattern); DateTimeFormatter dtf = b.toFormatter(locale); TemporalAccessor parsed = dtf.parseUnresolved(text, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), expectedPos); + assertEquals(expectedPos, ppos.getErrorIndex()); } else { - assertEquals(ppos.getIndex(), expectedPos, "Incorrect ending parse position"); - assertEquals(parsed.isSupported(YEAR_OF_ERA), true); - assertEquals(parsed.isSupported(WeekFields.of(locale).dayOfWeek()), true); - assertEquals(parsed.isSupported(WeekFields.of(locale).weekOfMonth()) || - parsed.isSupported(WeekFields.of(locale).weekOfYear()), true); + assertEquals(expectedPos, ppos.getIndex(), "Incorrect ending parse position"); + assertEquals(true, parsed.isSupported(YEAR_OF_ERA)); + assertEquals(true, parsed.isSupported(WeekFields.of(locale).dayOfWeek())); + assertEquals(true, parsed.isSupported(WeekFields.of(locale).weekOfMonth()) || + parsed.isSupported(WeekFields.of(locale).weekOfYear())); // ensure combination resolves into a date LocalDate result = LocalDate.parse(text, dtf); - assertEquals(result, expectedValue, "LocalDate incorrect for " + pattern); + assertEquals(expectedValue, result, "LocalDate incorrect for " + pattern); } } //----------------------------------------------------------------------- - @DataProvider(name="LocalWeekBasedYearPatterns") Object[][] provider_patternLocalWeekBasedYearDate() { return new Object[][] { //{"w Y", "29 2012", 0, 7, LocalDate.of(2012, 7, 20)}, // Default lenient dayOfWeek not supported @@ -190,28 +194,28 @@ public class TCKLocalizedFieldParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="LocalWeekBasedYearPatterns") + @ParameterizedTest + @MethodSource("provider_patternLocalWeekBasedYearDate") public void test_parse_WeekBasedYear(String pattern, String text, int pos, int expectedPos, LocalDate expectedValue) { ParsePosition ppos = new ParsePosition(pos); DateTimeFormatterBuilder b = new DateTimeFormatterBuilder().appendPattern(pattern); DateTimeFormatter dtf = b.toFormatter(locale); TemporalAccessor parsed = dtf.parseUnresolved(text, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), expectedPos); + assertEquals(expectedPos, ppos.getErrorIndex()); } else { WeekFields weekDef = WeekFields.of(locale); - assertEquals(ppos.getIndex(), expectedPos, "Incorrect ending parse position"); - assertEquals(parsed.isSupported(weekDef.dayOfWeek()), pattern.indexOf('e') >= 0); - assertEquals(parsed.isSupported(weekDef.weekOfWeekBasedYear()), pattern.indexOf('w') >= 0); - assertEquals(parsed.isSupported(weekDef.weekBasedYear()), pattern.indexOf('Y') >= 0); + assertEquals(expectedPos, ppos.getIndex(), "Incorrect ending parse position"); + assertEquals(pattern.indexOf('e') >= 0, parsed.isSupported(weekDef.dayOfWeek())); + assertEquals(pattern.indexOf('w') >= 0, parsed.isSupported(weekDef.weekOfWeekBasedYear())); + assertEquals(pattern.indexOf('Y') >= 0, parsed.isSupported(weekDef.weekBasedYear())); // ensure combination resolves into a date LocalDate result = LocalDate.parse(text, dtf); - assertEquals(result, expectedValue, "LocalDate incorrect for " + pattern + ", weekDef: " + weekDef); + assertEquals(expectedValue, result, "LocalDate incorrect for " + pattern + ", weekDef: " + weekDef); } } //----------------------------------------------------------------------- - @DataProvider(name = "adjacentValuePatterns1") Object[][] provider_adjacentValuePatterns1() { return new Object[][] { {"YYww", WEEK_BASED_YEAR, WEEK_OF_WEEK_BASED_YEAR, "1612", 2016, 12}, @@ -219,18 +223,18 @@ public class TCKLocalizedFieldParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider = "adjacentValuePatterns1") + @ParameterizedTest + @MethodSource("provider_adjacentValuePatterns1") public void test_adjacentValuePatterns1(String pattern, TemporalField field1, TemporalField field2, String text, int expected1, int expected2) { DateTimeFormatter df = new DateTimeFormatterBuilder() .appendPattern(pattern).toFormatter(Locale.US); ParsePosition ppos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(text, ppos); - assertEquals(parsed.get(field1), expected1); - assertEquals(parsed.get(field2), expected2); + assertEquals(expected1, parsed.get(field1)); + assertEquals(expected2, parsed.get(field2)); } - @DataProvider(name = "adjacentValuePatterns2") Object[][] provider_adjacentValuePatterns2() { return new Object[][] { {"YYYYwwc", WEEK_BASED_YEAR, WEEK_OF_WEEK_BASED_YEAR, DAY_OF_WEEK, @@ -242,16 +246,17 @@ public class TCKLocalizedFieldParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider = "adjacentValuePatterns2") + @ParameterizedTest + @MethodSource("provider_adjacentValuePatterns2") public void test_adjacentValuePatterns2(String pattern, TemporalField field1, TemporalField field2, TemporalField field3, String text, int expected1, int expected2, int expected3) { DateTimeFormatter df = new DateTimeFormatterBuilder() .appendPattern(pattern).toFormatter(Locale.US); ParsePosition ppos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(text, ppos); - assertEquals(parsed.get(field1), expected1); - assertEquals(parsed.get(field2), expected2); - assertEquals(parsed.get(field3), expected3); + assertEquals(expected1, parsed.get(field1)); + assertEquals(expected2, parsed.get(field2)); + assertEquals(expected3, parsed.get(field3)); } @Test @@ -262,14 +267,13 @@ public class TCKLocalizedFieldParser extends AbstractTestPrinterParser { .appendPattern(pattern).toFormatter(Locale.US); ParsePosition ppos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(text, ppos); - assertEquals(parsed.get(DAY_OF_WEEK), 6); - assertEquals(parsed.get(WEEK_OF_WEEK_BASED_YEAR), 29); + assertEquals(6, parsed.get(DAY_OF_WEEK)); + assertEquals(29, parsed.get(WEEK_OF_WEEK_BASED_YEAR)); LocalDate result = LocalDate.parse(text, df); LocalDate expectedValue = LocalDate.of(2012, 07, 20); - assertEquals(result, expectedValue, "LocalDate incorrect for " + pattern); + assertEquals(expectedValue, result, "LocalDate incorrect for " + pattern); } - @DataProvider(name = "invalidPatterns") Object[][] provider_invalidPatterns() { return new Object[][] { {"W", "01"}, @@ -279,8 +283,9 @@ public class TCKLocalizedFieldParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider = "invalidPatterns", expectedExceptions = DateTimeParseException.class) + @ParameterizedTest + @MethodSource("provider_invalidPatterns") public void test_invalidPatterns(String pattern, String value) { - DateTimeFormatter.ofPattern(pattern).parse(value); + Assertions.assertThrows(DateTimeParseException.class, () -> DateTimeFormatter.ofPattern(pattern).parse(value)); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKLocalizedFieldPrinter.java b/test/jdk/java/time/tck/java/time/format/TCKLocalizedFieldPrinter.java index 2b7d0f82ce4..8f9126f20ea 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKLocalizedFieldPrinter.java +++ b/test/jdk/java/time/tck/java/time/format/TCKLocalizedFieldPrinter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,26 +59,26 @@ */ package tck.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.WeekFields; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import test.java.time.format.AbstractTestPrinterParser; /** * Test LocalizedFieldPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKLocalizedFieldPrinter extends AbstractTestPrinterParser { //----------------------------------------------------------------------- - @DataProvider(name="Patterns") Object[][] provider_pad() { return new Object[][] { {"e", "6"}, @@ -92,18 +92,18 @@ public class TCKLocalizedFieldPrinter extends AbstractTestPrinterParser { } //----------------------------------------------------------------------- - @Test(dataProvider="Patterns") + @ParameterizedTest + @MethodSource("provider_pad") public void test_localizedDayOfWeek(String pattern, String expected) { DateTimeFormatterBuilder b = new DateTimeFormatterBuilder().appendPattern(pattern); LocalDate date = LocalDate.of(2012, 7, 20); String result = b.toFormatter(locale).format(date); - assertEquals(result, expected, "Wrong output for pattern '" + pattern + "'."); + assertEquals(expected, result, "Wrong output for pattern '" + pattern + "'."); } //----------------------------------------------------------------------- - @DataProvider(name="LocalWeekBasedYearPatterns") Object[][] provider_patternLocalWeekBasedYearDate() { return new Object[][] { {"e w Y", "6 29 2012", LocalDate.of(2012, 7, 20)}, @@ -119,11 +119,12 @@ public class TCKLocalizedFieldPrinter extends AbstractTestPrinterParser { }; } - @Test(dataProvider = "LocalWeekBasedYearPatterns") + @ParameterizedTest + @MethodSource("provider_patternLocalWeekBasedYearDate") public void test_print_WeekBasedYear(String pattern, String expectedText, LocalDate date) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern, locale); String result = dtf.format(date); WeekFields weekDef = WeekFields.of(locale); - assertEquals(result, expectedText, "Incorrect formatting for " + pattern + ", weekDef: " + weekDef); + assertEquals(expectedText, result, "Incorrect formatting for " + pattern + ", weekDef: " + weekDef); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKLocalizedOffsetIdPrinterParser.java b/test/jdk/java/time/tck/java/time/format/TCKLocalizedOffsetIdPrinterParser.java index d0a1f189e92..7f06c564896 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKLocalizedOffsetIdPrinterParser.java +++ b/test/jdk/java/time/tck/java/time/format/TCKLocalizedOffsetIdPrinterParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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,12 +27,11 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test localized behavior of formatter. */ -@Test public class TCKLocalizedOffsetIdPrinterParser { @Test public void test_localized_offset_parse() { diff --git a/test/jdk/java/time/tck/java/time/format/TCKLocalizedPrinterParser.java b/test/jdk/java/time/tck/java/time/format/TCKLocalizedPrinterParser.java index bd9c79ddcf9..a831b44deec 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKLocalizedPrinterParser.java +++ b/test/jdk/java/time/tck/java/time/format/TCKLocalizedPrinterParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,7 +59,7 @@ */ package tck.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.DateFormat; import java.text.ParsePosition; @@ -72,33 +72,35 @@ import java.time.temporal.TemporalAccessor; import java.util.Date; import java.util.Locale; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test localized behavior of formatter. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKLocalizedPrinterParser { private DateTimeFormatterBuilder builder; private ParsePosition pos; - @BeforeMethod + @BeforeEach public void setUp() { builder = new DateTimeFormatterBuilder(); pos = new ParsePosition(0); } //----------------------------------------------------------------------- - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_parse_negativePosition() { - builder.appendLocalized(null, null); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendLocalized(null, null)); } //----------------------------------------------------------------------- - @DataProvider(name="date") Object[][] data_date() { return new Object[][] { {LocalDate.of(2012, 6, 30), FormatStyle.SHORT, DateFormat.SHORT, Locale.UK}, @@ -124,7 +126,8 @@ public class TCKLocalizedPrinterParser { } @SuppressWarnings("deprecation") - @Test(dataProvider="date") + @ParameterizedTest + @MethodSource("data_date") public void test_date_print(LocalDate date, FormatStyle dateStyle, int dateStyleOld, Locale locale) { DateFormat old = DateFormat.getDateInstance(dateStyleOld, locale); Date oldDate = new Date(date.getYear() - 1900, date.getMonthValue() - 1, date.getDayOfMonth()); @@ -132,11 +135,12 @@ public class TCKLocalizedPrinterParser { DateTimeFormatter f = builder.appendLocalized(dateStyle, null).toFormatter(locale); String formatted = f.format(date); - assertEquals(formatted, text); + assertEquals(text, formatted); } @SuppressWarnings("deprecation") - @Test(dataProvider="date") + @ParameterizedTest + @MethodSource("data_date") public void test_date_parse(LocalDate date, FormatStyle dateStyle, int dateStyleOld, Locale locale) { DateFormat old = DateFormat.getDateInstance(dateStyleOld, locale); Date oldDate = new Date(date.getYear() - 1900, date.getMonthValue() - 1, date.getDayOfMonth()); @@ -144,13 +148,12 @@ public class TCKLocalizedPrinterParser { DateTimeFormatter f = builder.appendLocalized(dateStyle, null).toFormatter(locale); TemporalAccessor parsed = f.parse(text, pos); - assertEquals(pos.getIndex(), text.length()); - assertEquals(pos.getErrorIndex(), -1); - assertEquals(LocalDate.from(parsed), date); + assertEquals(text.length(), pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); + assertEquals(date, LocalDate.from(parsed)); } //----------------------------------------------------------------------- - @DataProvider(name="time") Object[][] data_time() { return new Object[][] { {LocalTime.of(11, 30), FormatStyle.SHORT, DateFormat.SHORT, Locale.UK}, @@ -177,7 +180,8 @@ public class TCKLocalizedPrinterParser { } @SuppressWarnings("deprecation") - @Test(dataProvider="time") + @ParameterizedTest + @MethodSource("data_time") public void test_time_print(LocalTime time, FormatStyle timeStyle, int timeStyleOld, Locale locale) { DateFormat old = DateFormat.getTimeInstance(timeStyleOld, locale); Date oldDate = new Date(1970 - 1900, 0, 0, time.getHour(), time.getMinute(), time.getSecond()); @@ -185,11 +189,12 @@ public class TCKLocalizedPrinterParser { DateTimeFormatter f = builder.appendLocalized(null, timeStyle).toFormatter(locale); String formatted = f.format(time); - assertEquals(formatted, text); + assertEquals(text, formatted); } @SuppressWarnings("deprecation") - @Test(dataProvider="time") + @ParameterizedTest + @MethodSource("data_time") public void test_time_parse(LocalTime time, FormatStyle timeStyle, int timeStyleOld, Locale locale) { DateFormat old = DateFormat.getTimeInstance(timeStyleOld, locale); Date oldDate = new Date(1970 - 1900, 0, 0, time.getHour(), time.getMinute(), time.getSecond()); @@ -197,9 +202,9 @@ public class TCKLocalizedPrinterParser { DateTimeFormatter f = builder.appendLocalized(null, timeStyle).toFormatter(locale); TemporalAccessor parsed = f.parse(text, pos); - assertEquals(pos.getIndex(), text.length()); - assertEquals(pos.getErrorIndex(), -1); - assertEquals(LocalTime.from(parsed), time); + assertEquals(text.length(), pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); + assertEquals(time, LocalTime.from(parsed)); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKOffsetPrinterParser.java b/test/jdk/java/time/tck/java/time/format/TCKOffsetPrinterParser.java index 21d618a06c0..b817d23bb5f 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKOffsetPrinterParser.java +++ b/test/jdk/java/time/tck/java/time/format/TCKOffsetPrinterParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,7 +59,7 @@ */ package tck.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDateTime; import java.time.OffsetDateTime; @@ -71,14 +71,17 @@ import java.time.format.DateTimeFormatterBuilder; import java.time.format.TextStyle; import java.util.Locale; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatterBuilder.appendOffset(). */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKOffsetPrinterParser { private static final ZoneOffset OFFSET_UTC = ZoneOffset.UTC; @@ -104,13 +107,12 @@ public class TCKOffsetPrinterParser { private static final ZoneOffset OFFSET_M112345 = ZoneOffset.ofHoursMinutesSeconds(-11, -23, -45); private DateTimeFormatterBuilder builder; - @BeforeMethod + @BeforeEach public void setUp() { builder = new DateTimeFormatterBuilder(); } //----------------------------------------------------------------------- - @DataProvider(name="print") Object[][] data_print() { return new Object[][] { {"+HH", "Z", DT_2012_06_30_12_30_40, OFFSET_UTC, "Z"}, @@ -441,7 +443,6 @@ public class TCKOffsetPrinterParser { }; } - @DataProvider(name="print_localized") Object[][] data_print_localized() { return new Object[][] { {TextStyle.FULL, DT_2012_06_30_12_30_40, OFFSET_UTC, "GMT"}, @@ -469,16 +470,18 @@ public class TCKOffsetPrinterParser { }; } - @Test(dataProvider="print") + @ParameterizedTest + @MethodSource("data_print") public void test_print(String offsetPattern, String noOffset, LocalDateTime ldt, ZoneId zone, String expected) { ZonedDateTime zdt = ldt.atZone(zone); builder.appendOffset(offsetPattern, noOffset); String output = builder.toFormatter().format(zdt); - assertEquals(output, expected); + assertEquals(expected, output); } //----------------------------------------------------------------------- - @Test(dataProvider="print") + @ParameterizedTest + @MethodSource("data_print") public void test_print_pattern_X(String offsetPattern, String noOffset, LocalDateTime ldt, ZoneId zone, String expected) { String pattern = null; if (offsetPattern.equals("+HHmm") && noOffset.equals("Z")) { @@ -496,11 +499,12 @@ public class TCKOffsetPrinterParser { ZonedDateTime zdt = ldt.atZone(zone); builder.appendPattern(pattern); String output = builder.toFormatter().format(zdt); - assertEquals(output, expected); + assertEquals(expected, output); } } - @Test(dataProvider="print") + @ParameterizedTest + @MethodSource("data_print") public void test_print_pattern_x(String offsetPattern, String noOffset, LocalDateTime ldt, ZoneId zone, String expected) { String pattern = null; String zero = null; @@ -524,117 +528,119 @@ public class TCKOffsetPrinterParser { ZonedDateTime zdt = ldt.atZone(zone); builder.appendPattern(pattern); String output = builder.toFormatter().format(zdt); - assertEquals(output, (expected.equals("Z") ? zero : expected)); + assertEquals((expected.equals("Z") ? zero : expected), output); } } - @Test(dataProvider="print") + @ParameterizedTest + @MethodSource("data_print") public void test_print_pattern_Z(String offsetPattern, String noOffset, LocalDateTime ldt, ZoneId zone, String expected) { String pattern = null; if (offsetPattern.equals("+HHMM") && noOffset.equals("Z")) { ZonedDateTime zdt = ldt.atZone(zone); DateTimeFormatter f1 = new DateTimeFormatterBuilder().appendPattern("Z").toFormatter(); String output1 = f1.format(zdt); - assertEquals(output1, (expected.equals("Z") ? "+0000" : expected)); + assertEquals((expected.equals("Z") ? "+0000" : expected), output1); DateTimeFormatter f2 = new DateTimeFormatterBuilder().appendPattern("ZZ").toFormatter(); String output2 = f2.format(zdt); - assertEquals(output2, (expected.equals("Z") ? "+0000" : expected)); + assertEquals((expected.equals("Z") ? "+0000" : expected), output2); DateTimeFormatter f3 = new DateTimeFormatterBuilder().appendPattern("ZZZ").toFormatter(); String output3 = f3.format(zdt); - assertEquals(output3, (expected.equals("Z") ? "+0000" : expected)); + assertEquals((expected.equals("Z") ? "+0000" : expected), output3); } else if (offsetPattern.equals("+HH:MM:ss") && noOffset.equals("Z")) { ZonedDateTime zdt = ldt.atZone(zone); DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("ZZZZZ").toFormatter(); String output = f.format(zdt); - assertEquals(output, expected); + assertEquals(expected, output); } } - @Test(dataProvider="print_localized") + @ParameterizedTest + @MethodSource("data_print_localized") public void test_print_localized(TextStyle style, LocalDateTime ldt, ZoneOffset offset, String expected) { OffsetDateTime odt = OffsetDateTime.of(ldt, offset); ZonedDateTime zdt = ldt.atZone(offset); DateTimeFormatter f = new DateTimeFormatterBuilder().appendLocalizedOffset(style) .toFormatter(Locale.US); - assertEquals(f.format(odt), expected); - assertEquals(f.format(zdt), expected); - assertEquals(f.parse(expected, ZoneOffset::from), offset); + assertEquals(expected, f.format(odt)); + assertEquals(expected, f.format(zdt)); + assertEquals(offset, f.parse(expected, ZoneOffset::from)); if (style == TextStyle.FULL) { f = new DateTimeFormatterBuilder().appendPattern("ZZZZ") .toFormatter(Locale.US); - assertEquals(f.format(odt), expected); - assertEquals(f.format(zdt), expected); - assertEquals(f.parse(expected, ZoneOffset::from), offset); + assertEquals(expected, f.format(odt)); + assertEquals(expected, f.format(zdt)); + assertEquals(offset, f.parse(expected, ZoneOffset::from)); f = new DateTimeFormatterBuilder().appendPattern("OOOO") .toFormatter(Locale.US); - assertEquals(f.format(odt), expected); - assertEquals(f.format(zdt), expected); - assertEquals(f.parse(expected, ZoneOffset::from), offset); + assertEquals(expected, f.format(odt)); + assertEquals(expected, f.format(zdt)); + assertEquals(offset, f.parse(expected, ZoneOffset::from)); } if (style == TextStyle.SHORT) { f = new DateTimeFormatterBuilder().appendPattern("O") .toFormatter(Locale.US); - assertEquals(f.format(odt), expected); - assertEquals(f.format(zdt), expected); - assertEquals(f.parse(expected, ZoneOffset::from), offset); + assertEquals(expected, f.format(odt)); + assertEquals(expected, f.format(zdt)); + assertEquals(offset, f.parse(expected, ZoneOffset::from)); } } //----------------------------------------------------------------------- - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_X6rejected() { - builder.appendPattern("XXXXXX"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendPattern("XXXXXX")); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_x6rejected() { - builder.appendPattern("xxxxxx"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendPattern("xxxxxx")); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_Z6rejected() { - builder.appendPattern("ZZZZZZ"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendPattern("ZZZZZZ")); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_O2rejected() { - builder.appendPattern("OO"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendPattern("OO")); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_O3rejected() { - builder.appendPattern("OOO"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendPattern("OOO")); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_O5rejected() { - builder.appendPattern("OOOOO"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendPattern("OOOOO")); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_localzed_full_standline() { - builder.appendLocalizedOffset(TextStyle.FULL_STANDALONE); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendLocalizedOffset(TextStyle.FULL_STANDALONE)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_localzed_short_standalone() { - builder.appendLocalizedOffset(TextStyle.SHORT_STANDALONE); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendLocalizedOffset(TextStyle.SHORT_STANDALONE)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_localzed_narrow() { - builder.appendLocalizedOffset(TextStyle.NARROW); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendLocalizedOffset(TextStyle.NARROW)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_localzed_narrow_standalone() { - builder.appendLocalizedOffset(TextStyle.NARROW_STANDALONE); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendLocalizedOffset(TextStyle.NARROW_STANDALONE)); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKPadPrinterParser.java b/test/jdk/java/time/tck/java/time/format/TCKPadPrinterParser.java index d6641f65e63..c92cd5a4d43 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKPadPrinterParser.java +++ b/test/jdk/java/time/tck/java/time/format/TCKPadPrinterParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -61,48 +61,55 @@ package tck.java.time.format; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.text.ParsePosition; import java.time.format.DateTimeFormatterBuilder; import java.time.format.SignStyle; import java.time.temporal.TemporalAccessor; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test padding behavior of formatter. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKPadPrinterParser { private DateTimeFormatterBuilder builder; private ParsePosition pos; - @BeforeMethod + @BeforeEach public void setUp() { builder = new DateTimeFormatterBuilder(); pos = new ParsePosition(0); } //----------------------------------------------------------------------- - @Test(expectedExceptions=IndexOutOfBoundsException.class) + @Test public void test_parse_negativePosition() { - builder.padNext(3, '-').appendLiteral('Z'); - builder.toFormatter().parseUnresolved("--Z", new ParsePosition(-1)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { + builder.padNext(3, '-').appendLiteral('Z'); + builder.toFormatter().parseUnresolved("--Z", new ParsePosition(-1)); + }); } - @Test(expectedExceptions=IndexOutOfBoundsException.class) + @Test public void test_parse_offEndPosition() { - builder.padNext(3, '-').appendLiteral('Z'); - builder.toFormatter().parseUnresolved("--Z", new ParsePosition(4)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { + builder.padNext(3, '-').appendLiteral('Z'); + builder.toFormatter().parseUnresolved("--Z", new ParsePosition(4)); + }); } //----------------------------------------------------------------------- - @DataProvider(name="parseStrict") Object[][] data_parseStrict() { return new Object[][] { {"222", 3, -1, 222}, @@ -126,22 +133,22 @@ public class TCKPadPrinterParser { }; } - @Test(dataProvider="parseStrict") + @ParameterizedTest + @MethodSource("data_parseStrict") public void test_parseStrict(String text, int expectedIndex, int expectedErrorIndex, Number expectedMonth) { builder.padNext(3, '#').appendValue(MONTH_OF_YEAR, 1, 3, SignStyle.NORMAL); TemporalAccessor parsed = builder.toFormatter().parseUnresolved(text, pos); - assertEquals(pos.getIndex(), expectedIndex); - assertEquals(pos.getErrorIndex(), expectedErrorIndex); + assertEquals(expectedIndex, pos.getIndex()); + assertEquals(expectedErrorIndex, pos.getErrorIndex()); if (expectedMonth != null) { - assertEquals(parsed.isSupported(MONTH_OF_YEAR), true); - assertEquals(parsed.getLong(MONTH_OF_YEAR), expectedMonth.longValue()); + assertEquals(true, parsed.isSupported(MONTH_OF_YEAR)); + assertEquals(expectedMonth.longValue(), parsed.getLong(MONTH_OF_YEAR)); } else { - assertEquals(parsed, null); + assertEquals(null, parsed); } } //----------------------------------------------------------------------- - @DataProvider(name="parseLenient") Object[][] data_parseLenient() { return new Object[][] { {"222", 3, -1, 222}, @@ -167,17 +174,18 @@ public class TCKPadPrinterParser { }; } - @Test(dataProvider="parseLenient") + @ParameterizedTest + @MethodSource("data_parseLenient") public void test_parseLenient(String text, int expectedIndex, int expectedErrorIndex, Number expectedMonth) { builder.parseLenient().padNext(3, '#').appendValue(MONTH_OF_YEAR, 1, 3, SignStyle.NORMAL); TemporalAccessor parsed = builder.toFormatter().parseUnresolved(text, pos); - assertEquals(pos.getIndex(), expectedIndex); - assertEquals(pos.getErrorIndex(), expectedErrorIndex); + assertEquals(expectedIndex, pos.getIndex()); + assertEquals(expectedErrorIndex, pos.getErrorIndex()); if (expectedMonth != null) { - assertEquals(parsed.isSupported(MONTH_OF_YEAR), true); - assertEquals(parsed.getLong(MONTH_OF_YEAR), expectedMonth.longValue()); + assertEquals(true, parsed.isSupported(MONTH_OF_YEAR)); + assertEquals(expectedMonth.longValue(), parsed.getLong(MONTH_OF_YEAR)); } else { - assertEquals(parsed, null); + assertEquals(null, parsed); } } @@ -186,19 +194,19 @@ public class TCKPadPrinterParser { public void test_parse_decoratedStartsWithPad() { builder.padNext(8, '-').appendLiteral("-HELLO-"); TemporalAccessor parsed = builder.toFormatter().parseUnresolved("--HELLO-", pos); - assertEquals(pos.getIndex(), 0); - assertEquals(pos.getErrorIndex(), 2); - assertEquals(parsed, null); + assertEquals(0, pos.getIndex()); + assertEquals(2, pos.getErrorIndex()); + assertEquals(null, parsed); } @Test public void test_parse_decoratedStartsWithPad_number() { builder.padNext(3, '-').appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL); TemporalAccessor parsed = builder.toFormatter().parseUnresolved("--2", pos); - assertEquals(pos.getIndex(), 3); - assertEquals(pos.getErrorIndex(), -1); - assertEquals(parsed.isSupported(MONTH_OF_YEAR), true); - assertEquals(parsed.getLong(MONTH_OF_YEAR), 2L); // +2, not -2 + assertEquals(3, pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); + assertEquals(true, parsed.isSupported(MONTH_OF_YEAR)); + assertEquals(2L, parsed.getLong(MONTH_OF_YEAR)); // +2, not -2 } //----------------------------------------------------------------------- @@ -206,8 +214,8 @@ public class TCKPadPrinterParser { public void test_parse_decoratedEmpty_strict() { builder.padNext(4, '-').optionalStart().appendValue(DAY_OF_MONTH).optionalEnd(); TemporalAccessor parsed = builder.toFormatter().parseUnresolved("----", pos); - assertEquals(pos.getIndex(), 4); - assertEquals(pos.getErrorIndex(), -1); + assertEquals(4, pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); assertNotNull(parsed); } @@ -215,8 +223,8 @@ public class TCKPadPrinterParser { public void test_parse_decoratedEmpty_lenient() { builder.parseLenient().padNext(4, '-').optionalStart().appendValue(DAY_OF_MONTH).optionalEnd(); TemporalAccessor parsed = builder.toFormatter().parseUnresolved("----", pos); - assertEquals(pos.getIndex(), 4); - assertEquals(pos.getErrorIndex(), -1); + assertEquals(4, pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); assertNotNull(parsed); } diff --git a/test/jdk/java/time/tck/java/time/format/TCKResolverStyle.java b/test/jdk/java/time/tck/java/time/format/TCKResolverStyle.java index c2b2e6266c6..114ec073167 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKResolverStyle.java +++ b/test/jdk/java/time/tck/java/time/format/TCKResolverStyle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -64,17 +64,18 @@ import java.time.format.ResolverStyle; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKResolverStyle { //----------------------------------------------------------------------- @@ -83,11 +84,10 @@ public class TCKResolverStyle { @Test public void test_valueOf() { for (ResolverStyle style : ResolverStyle.values()) { - assertEquals(ResolverStyle.valueOf(style.name()), style); + assertEquals(style, ResolverStyle.valueOf(style.name())); } } - @DataProvider(name="resolverStyle") Object[][] data_resolverStyle() { return new Object[][] { {"2000/15/30", ResolverStyle.LENIENT, null, 2001, 3, 30}, @@ -104,7 +104,8 @@ public class TCKResolverStyle { }; } - @Test(dataProvider = "resolverStyle") + @ParameterizedTest + @MethodSource("data_resolverStyle") public void test_resolverStyle(String str, ResolverStyle style, Class expectedEx, int year, int month, int day) { DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); builder.appendValue(ChronoField.YEAR_OF_ERA); @@ -122,9 +123,9 @@ public class TCKResolverStyle { formatter = formatter.withResolverStyle(style); if (expectedEx == null) { TemporalAccessor accessor = formatter.parse(str); - assertEquals(accessor.get(ChronoField.YEAR_OF_ERA), year); - assertEquals(accessor.get(ChronoField.MONTH_OF_YEAR), month); - assertEquals(accessor.get(ChronoField.DAY_OF_MONTH), day); + assertEquals(year, accessor.get(ChronoField.YEAR_OF_ERA)); + assertEquals(month, accessor.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(day, accessor.get(ChronoField.DAY_OF_MONTH)); } else { try { formatter.parse(str); diff --git a/test/jdk/java/time/tck/java/time/format/TCKSignStyle.java b/test/jdk/java/time/tck/java/time/format/TCKSignStyle.java index 602e8f70d42..c649f8de7d0 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKSignStyle.java +++ b/test/jdk/java/time/tck/java/time/format/TCKSignStyle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -62,17 +62,18 @@ import java.time.format.DateTimeFormatterBuilder; import java.time.format.SignStyle; import java.time.temporal.ChronoField; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKSignStyle { //----------------------------------------------------------------------- @@ -81,11 +82,10 @@ public class TCKSignStyle { @Test public void test_valueOf() { for (SignStyle style : SignStyle.values()) { - assertEquals(SignStyle.valueOf(style.name()), style); + assertEquals(style, SignStyle.valueOf(style.name())); } } - @DataProvider(name="signStyle") Object[][] data_signStyle() { return new Object[][] { {LocalDate.of(0, 10, 2), SignStyle.ALWAYS, null, "+00"}, @@ -113,7 +113,8 @@ public class TCKSignStyle { }; } - @Test(dataProvider = "signStyle") + @ParameterizedTest + @MethodSource("data_signStyle") public void test_signStyle(LocalDate localDate, SignStyle style, Class expectedEx, String expectedStr) { DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); DateTimeFormatter formatter = builder.appendValue(ChronoField.YEAR, 2, 4, style) @@ -121,7 +122,7 @@ public class TCKSignStyle { formatter = formatter.withZone(ZoneOffset.UTC); if (expectedEx == null) { String output = formatter.format(localDate); - assertEquals(output, expectedStr); + assertEquals(expectedStr, output); } else { try { formatter.format(localDate); diff --git a/test/jdk/java/time/tck/java/time/format/TCKTextStyle.java b/test/jdk/java/time/tck/java/time/format/TCKTextStyle.java index 68da619751a..e358f7b7a6f 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKTextStyle.java +++ b/test/jdk/java/time/tck/java/time/format/TCKTextStyle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -59,28 +59,27 @@ */ package tck.java.time.format; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.format.TextStyle; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test DecimalStyle. */ -@Test public class TCKTextStyle { @Test public void test_standaloneNormal() { - assertEquals(TextStyle.FULL, TextStyle.FULL_STANDALONE.asNormal()); - assertEquals(TextStyle.SHORT, TextStyle.SHORT.asNormal()); - assertEquals(TextStyle.NARROW, TextStyle.NARROW.asNormal()); + assertEquals(TextStyle.FULL_STANDALONE.asNormal(), TextStyle.FULL); + assertEquals(TextStyle.SHORT.asNormal(), TextStyle.SHORT); + assertEquals(TextStyle.NARROW.asNormal(), TextStyle.NARROW); - assertEquals(TextStyle.FULL_STANDALONE, TextStyle.FULL_STANDALONE.asStandalone()); - assertEquals(TextStyle.SHORT_STANDALONE, TextStyle.SHORT.asStandalone()); - assertEquals(TextStyle.NARROW_STANDALONE, TextStyle.NARROW.asStandalone()); + assertEquals(TextStyle.FULL_STANDALONE.asStandalone(), TextStyle.FULL_STANDALONE); + assertEquals(TextStyle.SHORT.asStandalone(), TextStyle.SHORT_STANDALONE); + assertEquals(TextStyle.NARROW.asStandalone(), TextStyle.NARROW_STANDALONE); assertTrue(TextStyle.FULL_STANDALONE.isStandalone()); assertTrue(TextStyle.SHORT_STANDALONE.isStandalone()); @@ -97,7 +96,7 @@ public class TCKTextStyle { @Test public void test_valueOf() { for (TextStyle style : TextStyle.values()) { - assertEquals(TextStyle.valueOf(style.name()), style); + assertEquals(style, TextStyle.valueOf(style.name())); } } diff --git a/test/jdk/java/time/tck/java/time/format/TCKZoneIdPrinterParser.java b/test/jdk/java/time/tck/java/time/format/TCKZoneIdPrinterParser.java index c1656885c07..9c2690891ee 100644 --- a/test/jdk/java/time/tck/java/time/format/TCKZoneIdPrinterParser.java +++ b/test/jdk/java/time/tck/java/time/format/TCKZoneIdPrinterParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,30 +59,29 @@ */ package tck.java.time.format; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.ParsePosition; -import java.time.DateTimeException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalQueries; import java.util.Locale; -import java.util.Objects; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatterBuilder.appendZoneId(). */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKZoneIdPrinterParser { private static final ZoneOffset OFFSET_UTC = ZoneOffset.UTC; @@ -94,14 +93,13 @@ public class TCKZoneIdPrinterParser { private DateTimeFormatterBuilder builder; private ParsePosition pos; - @BeforeMethod + @BeforeEach public void setUp() { builder = new DateTimeFormatterBuilder(); pos = new ParsePosition(0); } //----------------------------------------------------------------------- - @DataProvider(name="print") Object[][] data_print() { return new Object[][] { {DT_2012_06_30_12_30_40, EUROPE_PARIS, "Europe/Paris"}, @@ -111,45 +109,46 @@ public class TCKZoneIdPrinterParser { }; } - @Test(dataProvider="print") + @ParameterizedTest + @MethodSource("data_print") public void test_print(LocalDateTime ldt, ZoneId zone, String expected) { ZonedDateTime zdt = ldt.atZone(zone); builder.appendZoneId(); String output = builder.toFormatter().format(zdt); - assertEquals(output, expected); + assertEquals(expected, output); } - @Test(dataProvider="print") + @ParameterizedTest + @MethodSource("data_print") public void test_print_pattern_VV(LocalDateTime ldt, ZoneId zone, String expected) { ZonedDateTime zdt = ldt.atZone(zone); builder.appendPattern("VV"); String output = builder.toFormatter().format(zdt); - assertEquals(output, expected); + assertEquals(expected, output); } //----------------------------------------------------------------------- - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_V1rejected() { - builder.appendPattern("V"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendPattern("V")); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_V3rejected() { - builder.appendPattern("VVV"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendPattern("VVV")); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_V4rejected() { - builder.appendPattern("VVVV"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendPattern("VVVV")); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_print_pattern_V5rejected() { - builder.appendPattern("VVVVV"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendPattern("VVVVV")); } //----------------------------------------------------------------------- - @DataProvider(name="parseSuccess") Object[][] data_parseSuccess() { return new Object[][] { {"Z", 1, -1, ZoneId.of("Z"), true}, @@ -208,7 +207,8 @@ public class TCKZoneIdPrinterParser { }; } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void test_ZoneId_parseSuccess_plain( String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { @@ -216,7 +216,8 @@ public class TCKZoneIdPrinterParser { test(text, expectedIndex, expectedErrorIndex, expected, isZoneOffset); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void test_ZoneId_parseSuccess_prefix( String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { @@ -228,7 +229,8 @@ public class TCKZoneIdPrinterParser { expected, isZoneOffset); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void test_ZoneId_parseSuccess_suffix( String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { @@ -236,7 +238,8 @@ public class TCKZoneIdPrinterParser { test(text + "XXX", expectedIndex, expectedErrorIndex, expected, isZoneOffset); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void test_ZoneId_parseSuccess_caseSensitive( String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { @@ -245,15 +248,16 @@ public class TCKZoneIdPrinterParser { if (text.matches("[^A-Z]*[A-Z].*")) { // if input has letters String lcText = text.toLowerCase(Locale.ENGLISH); TemporalAccessor parsed = builder.toFormatter().parseUnresolved(lcText, pos); - assertEquals(pos.getErrorIndex() >= 0, true); - assertEquals(pos.getIndex(), 0); - assertEquals(parsed, null); + assertEquals(true, pos.getErrorIndex() >= 0); + assertEquals(0, pos.getIndex()); + assertEquals(null, parsed); } else { test(text.toLowerCase(Locale.ENGLISH), expectedIndex, expectedErrorIndex, expected, isZoneOffset); } } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void test_ZoneId_parseSuccess_caseInsensitive( String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { @@ -261,7 +265,8 @@ public class TCKZoneIdPrinterParser { test(text.toLowerCase(Locale.ENGLISH), expectedIndex, expectedErrorIndex, expected, isZoneOffset); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void test_ZoneOrOffsetId_parseSuccess_plain( String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { @@ -269,7 +274,8 @@ public class TCKZoneIdPrinterParser { test(text, expectedIndex, expectedErrorIndex, expected, isZoneOffset); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void test_ZoneOrOffsetId_parseSuccess_prefix( String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { @@ -281,7 +287,8 @@ public class TCKZoneIdPrinterParser { expected, isZoneOffset); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void test_ZoneOrOffsetId_parseSuccess_suffix( String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { @@ -289,7 +296,8 @@ public class TCKZoneIdPrinterParser { test(text + "XXX", expectedIndex, expectedErrorIndex, expected, isZoneOffset); } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void test_ZoneOrOffsetId_parseSuccess_caseSensitive( String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { @@ -297,15 +305,16 @@ public class TCKZoneIdPrinterParser { if (text.matches("[^A-Z]*[A-Z].*")) { // if input has letters String lcText = text.toLowerCase(Locale.ENGLISH); TemporalAccessor parsed = builder.toFormatter().parseUnresolved(lcText, pos); - assertEquals(pos.getErrorIndex() >= 0, true); - assertEquals(pos.getIndex(), 0); - assertEquals(parsed, null); + assertEquals(true, pos.getErrorIndex() >= 0); + assertEquals(0, pos.getIndex()); + assertEquals(null, parsed); } else { test(text.toLowerCase(Locale.ENGLISH), expectedIndex, expectedErrorIndex, expected, isZoneOffset); } } - @Test(dataProvider="parseSuccess") + @ParameterizedTest + @MethodSource("data_parseSuccess") public void test_ZoneOrOffsetIdparseSuccess_caseInsensitive( String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { @@ -316,20 +325,17 @@ public class TCKZoneIdPrinterParser { private void test(String text, int expectedIndex, int expectedErrorIndex, ZoneId expected, boolean isZoneOffset) { TemporalAccessor parsed = builder.toFormatter().parseUnresolved(text, pos); - assertEquals(pos.getErrorIndex(), expectedErrorIndex, "Incorrect error index parsing: " + text); - assertEquals(pos.getIndex(), expectedIndex, "Incorrect index parsing: " + text); + assertEquals(expectedErrorIndex, pos.getErrorIndex(), "Incorrect error index parsing: " + text); + assertEquals(expectedIndex, pos.getIndex(), "Incorrect index parsing: " + text); if (expected != null) { - assertEquals(parsed.query(TemporalQueries.zoneId()), - expected, + assertEquals(expected, parsed.query(TemporalQueries.zoneId()), "Incorrect zoneId parsing: " + text); - assertEquals(parsed.query(TemporalQueries.offset()), - isZoneOffset ? expected : null, + assertEquals(isZoneOffset ? expected : null, parsed.query(TemporalQueries.offset()), "Incorrect offset parsing: " + text); - assertEquals(parsed.query(TemporalQueries.zone()), - expected, + assertEquals(expected, parsed.query(TemporalQueries.zone()), "Incorrect zone parsing: " + text); } else { - assertEquals(parsed, null); + assertEquals(null, parsed); } } diff --git a/test/jdk/java/time/tck/java/time/serial/TCKClockSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKClockSerialization.java index d3ef560fb3f..6fcfe70478f 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKClockSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKClockSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -69,14 +69,13 @@ import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; import tck.java.time.AbstractTCKTest; /** * Test system and offset clocks serialization. */ -@Test public class TCKClockSerialization extends AbstractTCKTest { private static final ZoneId MOSCOW = ZoneId.of("Europe/Moscow"); @@ -87,6 +86,7 @@ public class TCKClockSerialization extends AbstractTCKTest { private static final Instant INSTANT = ZDT.toInstant(); //----------------------------------------------------------------------- + @Test public void test_systemClockSerializable() throws IOException, ClassNotFoundException { assertSerializable(Clock.systemUTC()); assertSerializable(Clock.systemDefaultZone()); @@ -94,11 +94,13 @@ public class TCKClockSerialization extends AbstractTCKTest { } //----------------------------------------------------------------------- + @Test public void test_offsetClockSerializable() throws IOException, ClassNotFoundException { assertSerializable(Clock.offset(Clock.system(PARIS), AMOUNT)); } //----------------------------------------------------------------------- + @Test public void test_tickClockSerializable() throws IOException, ClassNotFoundException { assertSerializable(Clock.tickSeconds(PARIS)); assertSerializable(Clock.tickMinutes(MOSCOW)); @@ -106,6 +108,7 @@ public class TCKClockSerialization extends AbstractTCKTest { } //----------------------------------------------------------------------- + @Test public void test_fixedClockSerializable() throws IOException, ClassNotFoundException { assertSerializable(Clock.fixed(INSTANT, ZoneOffset.UTC)); assertSerializable(Clock.fixed(INSTANT, PARIS)); diff --git a/test/jdk/java/time/tck/java/time/serial/TCKDurationSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKDurationSerialization.java index b2251181572..0c491d6558f 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKDurationSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKDurationSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,9 +59,8 @@ */ package tck.java.time.serial; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; @@ -69,10 +68,11 @@ import java.io.DataOutputStream; import java.io.Serializable; import java.time.Duration; +import org.junit.jupiter.api.Test; + /** * Test Duration serialization. */ -@Test public class TCKDurationSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- diff --git a/test/jdk/java/time/tck/java/time/serial/TCKInstantSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKInstantSerialization.java index bb4eb47c8dd..ef5da109afb 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKInstantSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKInstantSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,18 +59,17 @@ */ package tck.java.time.serial; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.time.Instant; +import org.junit.jupiter.api.Test; + /** * Test Instant serialization. */ -@Test public class TCKInstantSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- diff --git a/test/jdk/java/time/tck/java/time/serial/TCKLocalDateSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKLocalDateSerialization.java index 7a82822944b..cd2d9e1a924 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKLocalDateSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKLocalDateSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,23 +59,23 @@ */ package tck.java.time.serial; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.time.LocalDate; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + /** * Test LocalDate serialization. */ -@Test public class TCKLocalDateSerialization extends AbstractTCKTest { private LocalDate TEST_2007_07_15; - @BeforeMethod + @BeforeEach public void setUp() { TEST_2007_07_15 = LocalDate.of(2007, 7, 15); } diff --git a/test/jdk/java/time/tck/java/time/serial/TCKLocalDateTimeSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKLocalDateTimeSerialization.java index c2078913808..88b1e4a40cc 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKLocalDateTimeSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKLocalDateTimeSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,17 +59,17 @@ */ package tck.java.time.serial; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.time.LocalDateTime; +import org.junit.jupiter.api.Test; + /** * Test serialization of LocalDateTime. */ -@Test public class TCKLocalDateTimeSerialization extends AbstractTCKTest { private LocalDateTime TEST_2007_07_15_12_30_40_987654321 = LocalDateTime.of(2007, 7, 15, 12, 30, 40, 987654321); diff --git a/test/jdk/java/time/tck/java/time/serial/TCKLocalTimeSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKLocalTimeSerialization.java index f03eb070233..a62a41ab4a8 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKLocalTimeSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKLocalTimeSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,25 +59,25 @@ */ package tck.java.time.serial; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.time.LocalTime; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + /** * Test LocalTime serialization. */ -@Test public class TCKLocalTimeSerialization extends AbstractTCKTest { private LocalTime TEST_12_30_40_987654321; - @BeforeMethod + @BeforeEach public void setUp() { TEST_12_30_40_987654321 = LocalTime.of(12, 30, 40, 987654321); } diff --git a/test/jdk/java/time/tck/java/time/serial/TCKMonthDaySerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKMonthDaySerialization.java index fff7ff5afa3..74519b73889 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKMonthDaySerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKMonthDaySerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,6 @@ */ package tck.java.time.serial; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; @@ -68,15 +66,17 @@ import java.io.DataOutputStream; import java.io.IOException; import java.time.MonthDay; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + /** * Test MonthDay serialization. */ -@Test public class TCKMonthDaySerialization extends AbstractTCKTest { private MonthDay TEST_07_15; - @BeforeMethod + @BeforeEach public void setUp() { TEST_07_15 = MonthDay.of(7, 15); } diff --git a/test/jdk/java/time/tck/java/time/serial/TCKOffsetDateTimeSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKOffsetDateTimeSerialization.java index 1f08bd08fc0..4e9b61249dd 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKOffsetDateTimeSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKOffsetDateTimeSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -66,20 +66,20 @@ import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import tck.java.time.AbstractTCKTest; /** * Test OffsetDateTime serialization. */ -@Test public class TCKOffsetDateTimeSerialization extends AbstractTCKTest { private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); private OffsetDateTime TEST_2008_6_30_11_30_59_000000500; - @BeforeMethod + @BeforeEach public void setUp() { TEST_2008_6_30_11_30_59_000000500 = OffsetDateTime.of(2008, 6, 30, 11, 30, 59, 500, OFFSET_PONE); } diff --git a/test/jdk/java/time/tck/java/time/serial/TCKOffsetTimeSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKOffsetTimeSerialization.java index 2052da6ac2e..a4cacfd3ed4 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKOffsetTimeSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKOffsetTimeSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,6 @@ */ package tck.java.time.serial; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; @@ -68,16 +66,18 @@ import java.io.DataOutputStream; import java.time.OffsetTime; import java.time.ZoneOffset; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + /** * Test OffsetTime serialization. */ -@Test public class TCKOffsetTimeSerialization extends AbstractTCKTest { private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); private OffsetTime TEST_11_30_59_500_PONE; - @BeforeMethod + @BeforeEach public void setUp() { TEST_11_30_59_500_PONE = OffsetTime.of(11, 30, 59, 500, OFFSET_PONE); } diff --git a/test/jdk/java/time/tck/java/time/serial/TCKPeriodSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKPeriodSerialization.java index df1c6785567..abb8634f944 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKPeriodSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKPeriodSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,15 +59,15 @@ */ package tck.java.time.serial; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.time.Period; +import org.junit.jupiter.api.Test; + /** * Test serialization of Period. */ -@Test public class TCKPeriodSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- diff --git a/test/jdk/java/time/tck/java/time/serial/TCKYearMonthSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKYearMonthSerialization.java index 677aee4655f..e3bfb7aea05 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKYearMonthSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKYearMonthSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,6 @@ */ package tck.java.time.serial; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; @@ -68,15 +66,17 @@ import java.io.DataOutputStream; import java.io.IOException; import java.time.YearMonth; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + /** * Test serialization of YearMonth. */ -@Test public class TCKYearMonthSerialization extends AbstractTCKTest { private YearMonth TEST_2008_06; - @BeforeMethod + @BeforeEach public void setUp() { TEST_2008_06 = YearMonth.of(2008, 6); } diff --git a/test/jdk/java/time/tck/java/time/serial/TCKYearSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKYearSerialization.java index 4167e35eb18..db7ea5b3e99 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKYearSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKYearSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,17 +59,17 @@ */ package tck.java.time.serial; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.time.Year; +import org.junit.jupiter.api.Test; + /** * Test Year serialization. */ -@Test public class TCKYearSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- diff --git a/test/jdk/java/time/tck/java/time/serial/TCKZoneIdSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKZoneIdSerialization.java index 34c79c396e1..3f3d2e8d80f 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKZoneIdSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKZoneIdSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,6 @@ */ package tck.java.time.serial; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayInputStream; @@ -72,13 +70,18 @@ import java.time.DateTimeException; import java.time.ZoneId; import java.time.zone.ZoneRulesException; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test serialization of ZoneId. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKZoneIdSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- @@ -105,11 +108,11 @@ public class TCKZoneIdSerialization extends AbstractTCKTest { String id = "QWERTYUIOPASDFGHJKLZXCVBNM~/._+-"; ZoneId deser = deserialize(id); // getId, equals, hashCode, toString and normalized are OK - assertEquals(deser.getId(), id); - assertEquals(deser.toString(), id); + assertEquals(id, deser.getId()); + assertEquals(id, deser.toString()); assertEquals(deser, deser); assertEquals(deser.hashCode(), deser.hashCode()); - assertEquals(deser.normalized(), deser); + assertEquals(deser, deser.normalized()); // getting the rules is not try { deser.getRules(); @@ -119,39 +122,45 @@ public class TCKZoneIdSerialization extends AbstractTCKTest { } } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_deserialization_lenient_badCharacters() throws Exception { - // an ID can be loaded without validation during deserialization - // but there is a check to ensure the ID format is valid - deserialize("|!?"); + Assertions.assertThrows(DateTimeException.class, () -> { + // an ID can be loaded without validation during deserialization + // but there is a check to ensure the ID format is valid + deserialize("|!?"); + }); } - @Test(dataProvider="offsetBasedValid") + @ParameterizedTest + @MethodSource("data_offsetBasedValid") public void test_deserialization_lenient_offsetNotAllowed_noPrefix(String input, String resolvedId) throws Exception { ZoneId deserialized = deserialize(input); - assertEquals(deserialized, ZoneId.of(input)); - assertEquals(deserialized, ZoneId.of(resolvedId)); + assertEquals(ZoneId.of(input), deserialized); + assertEquals(ZoneId.of(resolvedId), deserialized); } - @Test(dataProvider="offsetBasedValidPrefix") + @ParameterizedTest + @MethodSource("data_offsetBasedValidPrefix") public void test_deserialization_lenient_offsetNotAllowed_prefixUTC(String input, String resolvedId, String offsetId) throws Exception { ZoneId deserialized = deserialize("UTC" + input); - assertEquals(deserialized, ZoneId.of("UTC" + input)); - assertEquals(deserialized, ZoneId.of("UTC" + resolvedId)); + assertEquals(ZoneId.of("UTC" + input), deserialized); + assertEquals(ZoneId.of("UTC" + resolvedId), deserialized); } - @Test(dataProvider="offsetBasedValidPrefix") + @ParameterizedTest + @MethodSource("data_offsetBasedValidPrefix") public void test_deserialization_lenient_offsetNotAllowed_prefixGMT(String input, String resolvedId, String offsetId) throws Exception { ZoneId deserialized = deserialize("GMT" + input); - assertEquals(deserialized, ZoneId.of("GMT" + input)); - assertEquals(deserialized, ZoneId.of("GMT" + resolvedId)); + assertEquals(ZoneId.of("GMT" + input), deserialized); + assertEquals(ZoneId.of("GMT" + resolvedId), deserialized); } - @Test(dataProvider="offsetBasedValidPrefix") + @ParameterizedTest + @MethodSource("data_offsetBasedValidPrefix") public void test_deserialization_lenient_offsetNotAllowed_prefixUT(String input, String resolvedId, String offsetId) throws Exception { ZoneId deserialized = deserialize("UT" + input); - assertEquals(deserialized, ZoneId.of("UT" + input)); - assertEquals(deserialized, ZoneId.of("UT" + resolvedId)); + assertEquals(ZoneId.of("UT" + input), deserialized); + assertEquals(ZoneId.of("UT" + resolvedId), deserialized); } private ZoneId deserialize(String id) throws Exception { @@ -186,7 +195,6 @@ public class TCKZoneIdSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // regular factory and .normalized() //----------------------------------------------------------------------- - @DataProvider(name="offsetBasedValid") Object[][] data_offsetBasedValid() { return new Object[][] { {"Z", "Z"}, @@ -223,7 +231,6 @@ public class TCKZoneIdSerialization extends AbstractTCKTest { } //----------------------------------------------------------------------- - @DataProvider(name="offsetBasedValidPrefix") Object[][] data_offsetBasedValidPrefix() { return new Object[][] { {"", "", "Z"}, diff --git a/test/jdk/java/time/tck/java/time/serial/TCKZoneOffsetSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKZoneOffsetSerialization.java index c2795c6b00b..2240d592284 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKZoneOffsetSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKZoneOffsetSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,17 +59,17 @@ */ package tck.java.time.serial; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.time.ZoneOffset; +import org.junit.jupiter.api.Test; + /** * Test serialization of ZoneOffset. */ -@Test public class TCKZoneOffsetSerialization extends AbstractTCKTest { diff --git a/test/jdk/java/time/tck/java/time/serial/TCKZonedDateTimeSerialization.java b/test/jdk/java/time/tck/java/time/serial/TCKZonedDateTimeSerialization.java index 8200103cd62..f9a423fb653 100644 --- a/test/jdk/java/time/tck/java/time/serial/TCKZonedDateTimeSerialization.java +++ b/test/jdk/java/time/tck/java/time/serial/TCKZonedDateTimeSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,6 @@ */ package tck.java.time.serial; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.ByteArrayOutputStream; @@ -71,10 +69,12 @@ import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + /** * Test serialization of ZonedDateTime. */ -@Test public class TCKZonedDateTimeSerialization extends AbstractTCKTest { private static final ZoneOffset OFFSET_0100 = ZoneOffset.ofHours(1); @@ -84,7 +84,7 @@ public class TCKZonedDateTimeSerialization extends AbstractTCKTest { private ZonedDateTime TEST_DATE_TIME; - @BeforeMethod + @BeforeEach public void setUp() { TEST_LOCAL_2008_06_30_11_30_59_500 = LocalDateTime.of(2008, 6, 30, 11, 30, 59, 500); TEST_DATE_TIME = ZonedDateTime.of(TEST_LOCAL_2008_06_30_11_30_59_500, ZONE_0100); diff --git a/test/jdk/java/time/tck/java/time/temporal/TCKChronoField.java b/test/jdk/java/time/tck/java/time/temporal/TCKChronoField.java index efc63b192b6..e9d41dbf116 100644 --- a/test/jdk/java/time/tck/java/time/temporal/TCKChronoField.java +++ b/test/jdk/java/time/tck/java/time/temporal/TCKChronoField.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -93,9 +93,8 @@ import static java.time.temporal.ChronoUnit.NANOS; import static java.time.temporal.ChronoUnit.SECONDS; import static java.time.temporal.ChronoUnit.WEEKS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Instant; import java.time.LocalDate; @@ -106,19 +105,20 @@ import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAccessor; import java.time.temporal.ValueRange; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoField { //----------------------------------------------------------------------- // getBaseUnit() and getRangeUnit() //----------------------------------------------------------------------- - @DataProvider(name="fieldUnit") Object[][] data_fieldUnit() { return new Object[][] { {YEAR, YEARS, FOREVER}, @@ -141,16 +141,16 @@ public class TCKChronoField { }; } - @Test(dataProvider = "fieldUnit") + @ParameterizedTest + @MethodSource("data_fieldUnit") public void test_getBaseUnit(ChronoField field, ChronoUnit baseUnit, ChronoUnit rangeUnit) { - assertEquals(field.getBaseUnit(), baseUnit); - assertEquals(field.getRangeUnit(), rangeUnit); + assertEquals(baseUnit, field.getBaseUnit()); + assertEquals(rangeUnit, field.getRangeUnit()); } //----------------------------------------------------------------------- // isDateBased() and isTimeBased() //----------------------------------------------------------------------- - @DataProvider(name="fieldBased") Object[][] data_fieldBased() { return new Object[][] { {DAY_OF_WEEK, true, false}, @@ -185,16 +185,16 @@ public class TCKChronoField { }; } - @Test(dataProvider = "fieldBased") + @ParameterizedTest + @MethodSource("data_fieldBased") public void test_isDateBased(ChronoField field, boolean isDateBased, boolean isTimeBased) { - assertEquals(field.isDateBased(), isDateBased); - assertEquals(field.isTimeBased(), isTimeBased); + assertEquals(isDateBased, field.isDateBased()); + assertEquals(isTimeBased, field.isTimeBased()); } //----------------------------------------------------------------------- // isSupportedBy(TemporalAccessor temporal) and getFrom(TemporalAccessor temporal) //----------------------------------------------------------------------- - @DataProvider(name="fieldAndAccessor") Object[][] data_fieldAndAccessor() { return new Object[][] { {YEAR, LocalDate.of(2000, 2, 29), true, 2000}, @@ -235,11 +235,12 @@ public class TCKChronoField { }; } - @Test(dataProvider = "fieldAndAccessor") + @ParameterizedTest + @MethodSource("data_fieldAndAccessor") public void test_supportedAccessor(ChronoField field, TemporalAccessor accessor, boolean isSupported, long value) { - assertEquals(field.isSupportedBy(accessor), isSupported); + assertEquals(isSupported, field.isSupportedBy(accessor)); if (isSupported) { - assertEquals(field.getFrom(accessor), value); + assertEquals(value, field.getFrom(accessor)); } } @@ -248,11 +249,11 @@ public class TCKChronoField { //----------------------------------------------------------------------- @Test public void test_range() { - assertEquals(MONTH_OF_YEAR.range(), ValueRange.of(1, 12)); - assertEquals(MONTH_OF_YEAR.rangeRefinedBy(LocalDate.of(2000, 2, 29)), ValueRange.of(1, 12)); + assertEquals(ValueRange.of(1, 12), MONTH_OF_YEAR.range()); + assertEquals(ValueRange.of(1, 12), MONTH_OF_YEAR.rangeRefinedBy(LocalDate.of(2000, 2, 29))); - assertEquals(DAY_OF_MONTH.range(), ValueRange.of(1, 28, 31)); - assertEquals(DAY_OF_MONTH.rangeRefinedBy(LocalDate.of(2000, 2, 29)), ValueRange.of(1, 29)); + assertEquals(ValueRange.of(1, 28, 31), DAY_OF_MONTH.range()); + assertEquals(ValueRange.of(1, 29), DAY_OF_MONTH.rangeRefinedBy(LocalDate.of(2000, 2, 29))); } //----------------------------------------------------------------------- @@ -261,7 +262,7 @@ public class TCKChronoField { @Test public void test_valueOf() { for (ChronoField field : ChronoField.values()) { - assertEquals(ChronoField.valueOf(field.name()), field); + assertEquals(field, ChronoField.valueOf(field.name())); } } @@ -269,9 +270,7 @@ public class TCKChronoField { // matches the minimum and maximum supported epoch second by Instant. @Test public void testMinMaxInstantSeconds() { - assertEquals(ChronoField.INSTANT_SECONDS.range().getMinimum(), - Instant.MIN.getLong(ChronoField.INSTANT_SECONDS)); - assertEquals(ChronoField.INSTANT_SECONDS.range().getMaximum(), - Instant.MAX.getLong(ChronoField.INSTANT_SECONDS)); + assertEquals(Instant.MIN.getLong(ChronoField.INSTANT_SECONDS), ChronoField.INSTANT_SECONDS.range().getMinimum()); + assertEquals(Instant.MAX.getLong(ChronoField.INSTANT_SECONDS), ChronoField.INSTANT_SECONDS.range().getMaximum()); } } diff --git a/test/jdk/java/time/tck/java/time/temporal/TCKChronoUnit.java b/test/jdk/java/time/tck/java/time/temporal/TCKChronoUnit.java index 5e52e23bb00..604dbb8cd23 100644 --- a/test/jdk/java/time/tck/java/time/temporal/TCKChronoUnit.java +++ b/test/jdk/java/time/tck/java/time/temporal/TCKChronoUnit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -70,30 +70,28 @@ import static java.time.temporal.ChronoUnit.NANOS; import static java.time.temporal.ChronoUnit.SECONDS; import static java.time.temporal.ChronoUnit.WEEKS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDate; import java.time.LocalTime; -import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.time.temporal.Temporal; -import java.time.temporal.TemporalAccessor; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoUnit { //----------------------------------------------------------------------- // isDateBased(), isTimeBased() and isDurationEstimated() //----------------------------------------------------------------------- - @DataProvider(name="chronoUnit") Object[][] data_chronoUnit() { return new Object[][] { {FOREVER, false, false, true}, @@ -117,17 +115,17 @@ public class TCKChronoUnit { }; } - @Test(dataProvider = "chronoUnit") + @ParameterizedTest + @MethodSource("data_chronoUnit") public void test_unitType(ChronoUnit unit, boolean isDateBased, boolean isTimeBased, boolean isDurationEstimated) { - assertEquals(unit.isDateBased(), isDateBased); - assertEquals(unit.isTimeBased(), isTimeBased); - assertEquals(unit.isDurationEstimated(), isDurationEstimated); + assertEquals(isDateBased, unit.isDateBased()); + assertEquals(isTimeBased, unit.isTimeBased()); + assertEquals(isDurationEstimated, unit.isDurationEstimated()); } //----------------------------------------------------------------------- // isSupportedBy(), addTo() and between() //----------------------------------------------------------------------- - @DataProvider(name="unitAndTemporal") Object[][] data_unitAndTemporal() { return new Object[][] { {CENTURIES, LocalDate.of(2000, 1, 10), true, 1, LocalDate.of(2100, 1, 10)}, @@ -163,13 +161,14 @@ public class TCKChronoUnit { }; } - @Test(dataProvider = "unitAndTemporal") + @ParameterizedTest + @MethodSource("data_unitAndTemporal") public void test_unitAndTemporal(ChronoUnit unit, Temporal base, boolean isSupportedBy, long amount, Temporal target) { - assertEquals(unit.isSupportedBy(base), isSupportedBy); + assertEquals(isSupportedBy, unit.isSupportedBy(base)); if (isSupportedBy) { Temporal result = unit.addTo(base, amount); - assertEquals(result, target); - assertEquals(unit.between(base, result), amount); + assertEquals(target, result); + assertEquals(amount, unit.between(base, result)); } } @@ -179,7 +178,7 @@ public class TCKChronoUnit { @Test public void test_valueOf() { for (ChronoUnit unit : ChronoUnit.values()) { - assertEquals(ChronoUnit.valueOf(unit.name()), unit); + assertEquals(unit, ChronoUnit.valueOf(unit.name())); } } } diff --git a/test/jdk/java/time/tck/java/time/temporal/TCKIsoFields.java b/test/jdk/java/time/tck/java/time/temporal/TCKIsoFields.java index 386af016248..e1a5cfba496 100644 --- a/test/jdk/java/time/tck/java/time/temporal/TCKIsoFields.java +++ b/test/jdk/java/time/tck/java/time/temporal/TCKIsoFields.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -63,8 +63,9 @@ import static java.time.DayOfWeek.TUESDAY; import static java.time.DayOfWeek.WEDNESDAY; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.time.DayOfWeek; import java.time.LocalDate; @@ -80,16 +81,18 @@ import java.time.temporal.TemporalField; import java.time.temporal.UnsupportedTemporalTypeException; import java.time.temporal.ValueRange; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKIsoFields { - @DataProvider(name="quarter") Object[][] data_quarter() { return new Object[][] { {LocalDate.of(1969, 12, 29), 90, 4}, @@ -121,35 +124,40 @@ public class TCKIsoFields { //----------------------------------------------------------------------- // DAY_OF_QUARTER //----------------------------------------------------------------------- - @Test(dataProvider = "quarter") + @ParameterizedTest + @MethodSource("data_quarter") public void test_DOQ(LocalDate date, int doq, int qoy) { - assertEquals(IsoFields.DAY_OF_QUARTER.getFrom(date), doq); - assertEquals(date.get(IsoFields.DAY_OF_QUARTER), doq); + assertEquals(doq, IsoFields.DAY_OF_QUARTER.getFrom(date)); + assertEquals(doq, date.get(IsoFields.DAY_OF_QUARTER)); } + @Test public void test_DOQ_basics() { - assertEquals(IsoFields.DAY_OF_QUARTER.isDateBased(), true); - assertEquals(IsoFields.DAY_OF_QUARTER.isTimeBased(), false); + assertEquals(true, IsoFields.DAY_OF_QUARTER.isDateBased()); + assertEquals(false, IsoFields.DAY_OF_QUARTER.isTimeBased()); } //----------------------------------------------------------------------- // QUARTER_OF_YEAR //----------------------------------------------------------------------- - @Test(dataProvider = "quarter") + @ParameterizedTest + @MethodSource("data_quarter") public void test_QOY(LocalDate date, int doq, int qoy) { - assertEquals(IsoFields.QUARTER_OF_YEAR.getFrom(date), qoy); - assertEquals(date.get(IsoFields.QUARTER_OF_YEAR), qoy); + assertEquals(qoy, IsoFields.QUARTER_OF_YEAR.getFrom(date)); + assertEquals(qoy, date.get(IsoFields.QUARTER_OF_YEAR)); } + @Test public void test_QOY_basics() { - assertEquals(IsoFields.QUARTER_OF_YEAR.isDateBased(), true); - assertEquals(IsoFields.QUARTER_OF_YEAR.isTimeBased(), false); + assertEquals(true, IsoFields.QUARTER_OF_YEAR.isDateBased()); + assertEquals(false, IsoFields.QUARTER_OF_YEAR.isTimeBased()); } //----------------------------------------------------------------------- // parse quarters //----------------------------------------------------------------------- - @Test(dataProvider = "quarter") + @ParameterizedTest + @MethodSource("data_quarter") public void test_parse_quarters(LocalDate date, int doq, int qoy) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral('-') @@ -157,10 +165,11 @@ public class TCKIsoFields { .appendValue(IsoFields.DAY_OF_QUARTER) .toFormatter().withResolverStyle(ResolverStyle.STRICT); LocalDate parsed = LocalDate.parse(date.getYear() + "-" + qoy + "-" + doq, f); - assertEquals(parsed, date); + assertEquals(date, parsed); } - @Test(dataProvider = "quarter") + @ParameterizedTest + @MethodSource("data_quarter") public void test_parse_quarters_SMART(LocalDate date, int doq, int qoy) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral('-') @@ -168,10 +177,11 @@ public class TCKIsoFields { .appendValue(IsoFields.DAY_OF_QUARTER) .toFormatter().withResolverStyle(ResolverStyle.SMART); LocalDate parsed = LocalDate.parse(date.getYear() + "-" + qoy + "-" + doq, f); - assertEquals(parsed, date); + assertEquals(date, parsed); } - @Test(dataProvider = "quarter") + @ParameterizedTest + @MethodSource("data_quarter") public void test_parse_quarters_LENIENT(LocalDate date, int doq, int qoy) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral('-') @@ -179,11 +189,10 @@ public class TCKIsoFields { .appendValue(IsoFields.DAY_OF_QUARTER) .toFormatter().withResolverStyle(ResolverStyle.LENIENT); LocalDate parsed = LocalDate.parse(date.getYear() + "-" + qoy + "-" + doq, f); - assertEquals(parsed, date); + assertEquals(date, parsed); } //----------------------------------------------------------------------- - @DataProvider(name="parseLenientQuarter") Object[][] data_parseLenientQuarter() { return new Object[][] { {"2012:0:1", LocalDate.of(2011, 10, 1), false}, @@ -206,17 +215,21 @@ public class TCKIsoFields { }; } - @Test(dataProvider = "parseLenientQuarter", expectedExceptions = DateTimeParseException.class) + @ParameterizedTest + @MethodSource("data_parseLenientQuarter") public void test_parse_parseLenientQuarter_STRICT(String str, LocalDate expected, boolean smart) { - DateTimeFormatter f = new DateTimeFormatterBuilder() - .appendValue(YEAR).appendLiteral(':') - .appendValue(IsoFields.QUARTER_OF_YEAR).appendLiteral(':') - .appendValue(IsoFields.DAY_OF_QUARTER) - .toFormatter().withResolverStyle(ResolverStyle.STRICT); - LocalDate.parse(str, f); + Assertions.assertThrows(DateTimeParseException.class, () -> { + DateTimeFormatter f = new DateTimeFormatterBuilder() + .appendValue(YEAR).appendLiteral(':') + .appendValue(IsoFields.QUARTER_OF_YEAR).appendLiteral(':') + .appendValue(IsoFields.DAY_OF_QUARTER) + .toFormatter().withResolverStyle(ResolverStyle.STRICT); + LocalDate.parse(str, f); + }); } - @Test(dataProvider = "parseLenientQuarter") + @ParameterizedTest + @MethodSource("data_parseLenientQuarter") public void test_parse_parseLenientQuarter_SMART(String str, LocalDate expected, boolean smart) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') @@ -225,7 +238,7 @@ public class TCKIsoFields { .toFormatter().withResolverStyle(ResolverStyle.SMART); if (smart) { LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, expected); + assertEquals(expected, parsed); } else { try { LocalDate.parse(str, f); @@ -236,7 +249,8 @@ public class TCKIsoFields { } } - @Test(dataProvider = "parseLenientQuarter") + @ParameterizedTest + @MethodSource("data_parseLenientQuarter") public void test_parse_parseLenientQuarter_LENIENT(String str, LocalDate expected, boolean smart) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') @@ -244,13 +258,12 @@ public class TCKIsoFields { .appendValue(IsoFields.DAY_OF_QUARTER) .toFormatter().withResolverStyle(ResolverStyle.LENIENT); LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, expected); + assertEquals(expected, parsed); } //----------------------------------------------------------------------- // quarters between //----------------------------------------------------------------------- - @DataProvider(name="quartersBetween") Object[][] data_quartersBetween() { return new Object[][] { {LocalDate.of(2000, 1, 1), LocalDate.of(2000, 1, 1), 0}, @@ -284,20 +297,21 @@ public class TCKIsoFields { }; } - @Test(dataProvider="quartersBetween") + @ParameterizedTest + @MethodSource("data_quartersBetween") public void test_quarters_between(LocalDate start, Temporal end, long expected) { - assertEquals(IsoFields.QUARTER_YEARS.between(start, end), expected); + assertEquals(expected, IsoFields.QUARTER_YEARS.between(start, end)); } - @Test(dataProvider="quartersBetween") + @ParameterizedTest + @MethodSource("data_quartersBetween") public void test_quarters_between_until(LocalDate start, Temporal end, long expected) { - assertEquals(start.until(end, IsoFields.QUARTER_YEARS), expected); + assertEquals(expected, start.until(end, IsoFields.QUARTER_YEARS)); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="week") Object[][] data_week() { return new Object[][] { {LocalDate.of(1969, 12, 29), MONDAY, 1, 1970}, @@ -318,37 +332,42 @@ public class TCKIsoFields { //----------------------------------------------------------------------- // WEEK_OF_WEEK_BASED_YEAR //----------------------------------------------------------------------- - @Test(dataProvider="week") + @ParameterizedTest + @MethodSource("data_week") public void test_WOWBY(LocalDate date, DayOfWeek dow, int week, int wby) { - assertEquals(date.getDayOfWeek(), dow); - assertEquals(IsoFields.WEEK_OF_WEEK_BASED_YEAR.getFrom(date), week); - assertEquals(date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR), week); + assertEquals(dow, date.getDayOfWeek()); + assertEquals(week, IsoFields.WEEK_OF_WEEK_BASED_YEAR.getFrom(date)); + assertEquals(week, date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)); } + @Test public void test_WOWBY_basics() { - assertEquals(IsoFields.WEEK_OF_WEEK_BASED_YEAR.isDateBased(), true); - assertEquals(IsoFields.WEEK_OF_WEEK_BASED_YEAR.isTimeBased(), false); + assertEquals(true, IsoFields.WEEK_OF_WEEK_BASED_YEAR.isDateBased()); + assertEquals(false, IsoFields.WEEK_OF_WEEK_BASED_YEAR.isTimeBased()); } //----------------------------------------------------------------------- // WEEK_BASED_YEAR //----------------------------------------------------------------------- - @Test(dataProvider="week") + @ParameterizedTest + @MethodSource("data_week") public void test_WBY(LocalDate date, DayOfWeek dow, int week, int wby) { - assertEquals(date.getDayOfWeek(), dow); - assertEquals(IsoFields.WEEK_BASED_YEAR.getFrom(date), wby); - assertEquals(date.get(IsoFields.WEEK_BASED_YEAR), wby); + assertEquals(dow, date.getDayOfWeek()); + assertEquals(wby, IsoFields.WEEK_BASED_YEAR.getFrom(date)); + assertEquals(wby, date.get(IsoFields.WEEK_BASED_YEAR)); } + @Test public void test_WBY_basics() { - assertEquals(IsoFields.WEEK_BASED_YEAR.isDateBased(), true); - assertEquals(IsoFields.WEEK_BASED_YEAR.isTimeBased(), false); + assertEquals(true, IsoFields.WEEK_BASED_YEAR.isDateBased()); + assertEquals(false, IsoFields.WEEK_BASED_YEAR.isTimeBased()); } //----------------------------------------------------------------------- // parse weeks //----------------------------------------------------------------------- - @Test(dataProvider="week") + @ParameterizedTest + @MethodSource("data_week") public void test_parse_weeks_STRICT(LocalDate date, DayOfWeek dow, int week, int wby) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral('-') @@ -356,10 +375,11 @@ public class TCKIsoFields { .appendValue(DAY_OF_WEEK) .toFormatter().withResolverStyle(ResolverStyle.STRICT); LocalDate parsed = LocalDate.parse(wby + "-" + week + "-" + dow.getValue(), f); - assertEquals(parsed, date); + assertEquals(date, parsed); } - @Test(dataProvider="week") + @ParameterizedTest + @MethodSource("data_week") public void test_parse_weeks_SMART(LocalDate date, DayOfWeek dow, int week, int wby) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral('-') @@ -367,10 +387,11 @@ public class TCKIsoFields { .appendValue(DAY_OF_WEEK) .toFormatter().withResolverStyle(ResolverStyle.SMART); LocalDate parsed = LocalDate.parse(wby + "-" + week + "-" + dow.getValue(), f); - assertEquals(parsed, date); + assertEquals(date, parsed); } - @Test(dataProvider="week") + @ParameterizedTest + @MethodSource("data_week") public void test_parse_weeks_LENIENT(LocalDate date, DayOfWeek dow, int week, int wby) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral('-') @@ -378,11 +399,10 @@ public class TCKIsoFields { .appendValue(DAY_OF_WEEK) .toFormatter().withResolverStyle(ResolverStyle.LENIENT); LocalDate parsed = LocalDate.parse(wby + "-" + week + "-" + dow.getValue(), f); - assertEquals(parsed, date); + assertEquals(date, parsed); } //----------------------------------------------------------------------- - @DataProvider(name="parseLenientWeek") Object[][] data_parseLenientWeek() { return new Object[][] { {"2012:52:-1", LocalDate.of(2012, 12, 22), false}, @@ -398,17 +418,21 @@ public class TCKIsoFields { }; } - @Test(dataProvider = "parseLenientWeek", expectedExceptions = DateTimeParseException.class) + @ParameterizedTest + @MethodSource("data_parseLenientWeek") public void test_parse_parseLenientWeek_STRICT(String str, LocalDate expected, boolean smart) { - DateTimeFormatter f = new DateTimeFormatterBuilder() - .appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral(':') - .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral(':') - .appendValue(DAY_OF_WEEK) - .toFormatter().withResolverStyle(ResolverStyle.STRICT); - LocalDate.parse(str, f); + Assertions.assertThrows(DateTimeParseException.class, () -> { + DateTimeFormatter f = new DateTimeFormatterBuilder() + .appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral(':') + .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral(':') + .appendValue(DAY_OF_WEEK) + .toFormatter().withResolverStyle(ResolverStyle.STRICT); + LocalDate.parse(str, f); + }); } - @Test(dataProvider = "parseLenientWeek") + @ParameterizedTest + @MethodSource("data_parseLenientWeek") public void test_parse_parseLenientWeek_SMART(String str, LocalDate expected, boolean smart) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral(':') @@ -417,7 +441,7 @@ public class TCKIsoFields { .toFormatter().withResolverStyle(ResolverStyle.SMART); if (smart) { LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, expected); + assertEquals(expected, parsed); } else { try { LocalDate.parse(str, f); @@ -428,7 +452,8 @@ public class TCKIsoFields { } } - @Test(dataProvider = "parseLenientWeek") + @ParameterizedTest + @MethodSource("data_parseLenientWeek") public void test_parse_parseLenientWeek_LENIENT(String str, LocalDate expected, boolean smart) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral(':') @@ -436,13 +461,12 @@ public class TCKIsoFields { .appendValue(DAY_OF_WEEK) .toFormatter().withResolverStyle(ResolverStyle.LENIENT); LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, expected); + assertEquals(expected, parsed); } //----------------------------------------------------------------------- // rangeRefinedBy //----------------------------------------------------------------------- - @DataProvider(name="isofields") Object[][] data_isofields() { return new Object[][] { {IsoFields.DAY_OF_QUARTER, 49, ValueRange.of(1, 91)}, @@ -453,32 +477,37 @@ public class TCKIsoFields { }; } - @Test(dataProvider = "isofields") + @ParameterizedTest + @MethodSource("data_isofields") public void test_isofields_rangerefinedby(TemporalField field, int value, ValueRange valueRange) { LocalDate date = LocalDate.of(2016, 5, 19); - assertEquals(field.rangeRefinedBy(date), valueRange); + assertEquals(valueRange, field.rangeRefinedBy(date)); } - @Test(dataProvider = "isofields", expectedExceptions = UnsupportedTemporalTypeException.class) + @ParameterizedTest + @MethodSource("data_isofields") public void test_nonisofields_rangerefinedby(TemporalField field, int value, ValueRange valueRange) { - field.rangeRefinedBy(HijrahDate.now()); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> field.rangeRefinedBy(HijrahDate.now())); } //----------------------------------------------------------------------- // getFrom //----------------------------------------------------------------------- - @Test(dataProvider = "isofields") + @ParameterizedTest + @MethodSource("data_isofields") public void test_isofields_getFrom(TemporalField field, int value, ValueRange valueRange) { LocalDate date = LocalDate.of(2016, 5, 19); - assertEquals(field.getFrom(date), value); + assertEquals(value, field.getFrom(date)); } - @Test(dataProvider = "isofields", expectedExceptions = UnsupportedTemporalTypeException.class) + @ParameterizedTest + @MethodSource("data_isofields") public void test_nonisofields_getFrom(TemporalField field, int value, ValueRange valueRange) { - field.getFrom(HijrahDate.now()); + Assertions.assertThrows(UnsupportedTemporalTypeException.class, () -> field.getFrom(HijrahDate.now())); } //----------------------------------------------------------------------- + @Test public void test_loop() { // loop round at least one 400 year cycle, including before 1970 LocalDate date = LocalDate.of(1960, 1, 5); // Tuseday of week 1 1960 @@ -501,11 +530,11 @@ public class TCKIsoFields { wby++; } } - assertEquals(IsoFields.WEEK_OF_WEEK_BASED_YEAR.rangeRefinedBy(date), ValueRange.of(1, weekLen), "Failed on " + date + " " + date.getDayOfWeek()); - assertEquals(IsoFields.WEEK_OF_WEEK_BASED_YEAR.getFrom(date), week, "Failed on " + date + " " + date.getDayOfWeek()); - assertEquals(date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR), week, "Failed on " + date + " " + date.getDayOfWeek()); - assertEquals(IsoFields.WEEK_BASED_YEAR.getFrom(date), wby, "Failed on " + date + " " + date.getDayOfWeek()); - assertEquals(date.get(IsoFields.WEEK_BASED_YEAR), wby, "Failed on " + date + " " + date.getDayOfWeek()); + assertEquals(ValueRange.of(1, weekLen), IsoFields.WEEK_OF_WEEK_BASED_YEAR.rangeRefinedBy(date), "Failed on " + date + " " + date.getDayOfWeek()); + assertEquals(week, IsoFields.WEEK_OF_WEEK_BASED_YEAR.getFrom(date), "Failed on " + date + " " + date.getDayOfWeek()); + assertEquals(week, date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR), "Failed on " + date + " " + date.getDayOfWeek()); + assertEquals(wby, IsoFields.WEEK_BASED_YEAR.getFrom(date), "Failed on " + date + " " + date.getDayOfWeek()); + assertEquals(wby, date.get(IsoFields.WEEK_BASED_YEAR), "Failed on " + date + " " + date.getDayOfWeek()); date = date.plusDays(1); } } diff --git a/test/jdk/java/time/tck/java/time/temporal/TCKJulianFields.java b/test/jdk/java/time/tck/java/time/temporal/TCKJulianFields.java index a15c31dd2c7..546b8d11c7c 100644 --- a/test/jdk/java/time/tck/java/time/temporal/TCKJulianFields.java +++ b/test/jdk/java/time/tck/java/time/temporal/TCKJulianFields.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,7 +59,7 @@ */ package tck.java.time.temporal; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.time.LocalDate; @@ -71,14 +71,17 @@ import java.time.temporal.IsoFields; import java.time.temporal.JulianFields; import java.time.temporal.TemporalField; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import tck.java.time.AbstractTCKTest; /** * Test Julian Fields. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKJulianFields extends AbstractTCKTest { private static final LocalDate JAN01_1970 = LocalDate.of(1970, 1, 1); @@ -86,7 +89,6 @@ public class TCKJulianFields extends AbstractTCKTest { private static final LocalDate NOV12_1945 = LocalDate.of(1945, 11, 12); private static final LocalDate JAN01_0001 = LocalDate.of(1, 1, 1); - @DataProvider(name="samples") Object[][] data_samples() { return new Object[][] { {ChronoField.EPOCH_DAY, JAN01_1970, 0L}, @@ -112,55 +114,61 @@ public class TCKJulianFields extends AbstractTCKTest { } //----------------------------------------------------------------------- + @Test public void test_basics() { - assertEquals(JulianFields.JULIAN_DAY.isDateBased(), true); - assertEquals(JulianFields.JULIAN_DAY.isTimeBased(), false); + assertEquals(true, JulianFields.JULIAN_DAY.isDateBased()); + assertEquals(false, JulianFields.JULIAN_DAY.isTimeBased()); - assertEquals(JulianFields.MODIFIED_JULIAN_DAY.isDateBased(), true); - assertEquals(JulianFields.MODIFIED_JULIAN_DAY.isTimeBased(), false); + assertEquals(true, JulianFields.MODIFIED_JULIAN_DAY.isDateBased()); + assertEquals(false, JulianFields.MODIFIED_JULIAN_DAY.isTimeBased()); - assertEquals(JulianFields.RATA_DIE.isDateBased(), true); - assertEquals(JulianFields.RATA_DIE.isTimeBased(), false); + assertEquals(true, JulianFields.RATA_DIE.isDateBased()); + assertEquals(false, JulianFields.RATA_DIE.isTimeBased()); } //----------------------------------------------------------------------- - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_samples_get(TemporalField field, LocalDate date, long expected) { - assertEquals(date.getLong(field), expected); + assertEquals(expected, date.getLong(field)); } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_samples_set(TemporalField field, LocalDate date, long value) { - assertEquals(field.adjustInto(LocalDate.MAX, value), date); - assertEquals(field.adjustInto(LocalDate.MIN, value), date); - assertEquals(field.adjustInto(JAN01_1970, value), date); - assertEquals(field.adjustInto(DEC31_1969, value), date); - assertEquals(field.adjustInto(NOV12_1945, value), date); + assertEquals(date, field.adjustInto(LocalDate.MAX, value)); + assertEquals(date, field.adjustInto(LocalDate.MIN, value)); + assertEquals(date, field.adjustInto(JAN01_1970, value)); + assertEquals(date, field.adjustInto(DEC31_1969, value)); + assertEquals(date, field.adjustInto(NOV12_1945, value)); } //----------------------------------------------------------------------- - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_samples_parse_STRICT(TemporalField field, LocalDate date, long value) { DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field) .toFormatter().withResolverStyle(ResolverStyle.STRICT); LocalDate parsed = LocalDate.parse(Long.toString(value), f); - assertEquals(parsed, date); + assertEquals(date, parsed); } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_samples_parse_SMART(TemporalField field, LocalDate date, long value) { DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field) .toFormatter().withResolverStyle(ResolverStyle.SMART); LocalDate parsed = LocalDate.parse(Long.toString(value), f); - assertEquals(parsed, date); + assertEquals(date, parsed); } - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_samples_parse_LENIENT(TemporalField field, LocalDate date, long value) { DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field) .toFormatter().withResolverStyle(ResolverStyle.LENIENT); LocalDate parsed = LocalDate.parse(Long.toString(value), f); - assertEquals(parsed, date); + assertEquals(date, parsed); } } diff --git a/test/jdk/java/time/tck/java/time/temporal/TCKTemporalAdjusters.java b/test/jdk/java/time/tck/java/time/temporal/TCKTemporalAdjusters.java index b901125fc30..8f06b4060f0 100644 --- a/test/jdk/java/time/tck/java/time/temporal/TCKTemporalAdjusters.java +++ b/test/jdk/java/time/tck/java/time/temporal/TCKTemporalAdjusters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -63,11 +63,12 @@ import static java.time.DayOfWeek.MONDAY; import static java.time.DayOfWeek.TUESDAY; import static java.time.Month.DECEMBER; import static java.time.Month.JANUARY; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.DayOfWeek; import java.time.LocalDate; @@ -75,13 +76,16 @@ import java.time.Month; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAdjusters; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test TemporalAdjusters. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKTemporalAdjusters { //----------------------------------------------------------------------- @@ -90,12 +94,12 @@ public class TCKTemporalAdjusters { @Test public void factory_ofDateAdjuster() { TemporalAdjuster test = TemporalAdjusters.ofDateAdjuster(date -> date.plusDays(2)); - assertEquals(LocalDate.of(2012, 6, 30).with(test), LocalDate.of(2012, 7, 2)); + assertEquals(LocalDate.of(2012, 7, 2), LocalDate.of(2012, 6, 30).with(test)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void factory_ofDateAdjuster_null() { - TemporalAdjusters.ofDateAdjuster(null); + Assertions.assertThrows(NullPointerException.class, () -> TemporalAdjusters.ofDateAdjuster(null)); } @@ -113,9 +117,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(false); i++) { LocalDate date = date(2007, month, i); LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfMonth().adjustInto(date); - assertEquals(test.getYear(), 2007); - assertEquals(test.getMonth(), month); - assertEquals(test.getDayOfMonth(), 1); + assertEquals(2007, test.getYear()); + assertEquals(month, test.getMonth()); + assertEquals(1, test.getDayOfMonth()); } } } @@ -126,9 +130,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(true); i++) { LocalDate date = date(2008, month, i); LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfMonth().adjustInto(date); - assertEquals(test.getYear(), 2008); - assertEquals(test.getMonth(), month); - assertEquals(test.getDayOfMonth(), 1); + assertEquals(2008, test.getYear()); + assertEquals(month, test.getMonth()); + assertEquals(1, test.getDayOfMonth()); } } } @@ -147,9 +151,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(false); i++) { LocalDate date = date(2007, month, i); LocalDate test = (LocalDate) TemporalAdjusters.lastDayOfMonth().adjustInto(date); - assertEquals(test.getYear(), 2007); - assertEquals(test.getMonth(), month); - assertEquals(test.getDayOfMonth(), month.length(false)); + assertEquals(2007, test.getYear()); + assertEquals(month, test.getMonth()); + assertEquals(month.length(false), test.getDayOfMonth()); } } } @@ -160,9 +164,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(true); i++) { LocalDate date = date(2008, month, i); LocalDate test = (LocalDate) TemporalAdjusters.lastDayOfMonth().adjustInto(date); - assertEquals(test.getYear(), 2008); - assertEquals(test.getMonth(), month); - assertEquals(test.getDayOfMonth(), month.length(true)); + assertEquals(2008, test.getYear()); + assertEquals(month, test.getMonth()); + assertEquals(month.length(true), test.getDayOfMonth()); } } } @@ -181,9 +185,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(false); i++) { LocalDate date = date(2007, month, i); LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfNextMonth().adjustInto(date); - assertEquals(test.getYear(), month == DECEMBER ? 2008 : 2007); - assertEquals(test.getMonth(), month.plus(1)); - assertEquals(test.getDayOfMonth(), 1); + assertEquals(month == DECEMBER ? 2008 : 2007, test.getYear()); + assertEquals(month.plus(1), test.getMonth()); + assertEquals(1, test.getDayOfMonth()); } } } @@ -194,9 +198,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(true); i++) { LocalDate date = date(2008, month, i); LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfNextMonth().adjustInto(date); - assertEquals(test.getYear(), month == DECEMBER ? 2009 : 2008); - assertEquals(test.getMonth(), month.plus(1)); - assertEquals(test.getDayOfMonth(), 1); + assertEquals(month == DECEMBER ? 2009 : 2008, test.getYear()); + assertEquals(month.plus(1), test.getMonth()); + assertEquals(1, test.getDayOfMonth()); } } } @@ -215,9 +219,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(false); i++) { LocalDate date = date(2007, month, i); LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfYear().adjustInto(date); - assertEquals(test.getYear(), 2007); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), 1); + assertEquals(2007, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals(1, test.getDayOfMonth()); } } } @@ -228,9 +232,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(true); i++) { LocalDate date = date(2008, month, i); LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfYear().adjustInto(date); - assertEquals(test.getYear(), 2008); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), 1); + assertEquals(2008, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals(1, test.getDayOfMonth()); } } } @@ -249,9 +253,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(false); i++) { LocalDate date = date(2007, month, i); LocalDate test = (LocalDate) TemporalAdjusters.lastDayOfYear().adjustInto(date); - assertEquals(test.getYear(), 2007); - assertEquals(test.getMonth(), Month.DECEMBER); - assertEquals(test.getDayOfMonth(), 31); + assertEquals(2007, test.getYear()); + assertEquals(Month.DECEMBER, test.getMonth()); + assertEquals(31, test.getDayOfMonth()); } } } @@ -262,9 +266,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(true); i++) { LocalDate date = date(2008, month, i); LocalDate test = (LocalDate) TemporalAdjusters.lastDayOfYear().adjustInto(date); - assertEquals(test.getYear(), 2008); - assertEquals(test.getMonth(), Month.DECEMBER); - assertEquals(test.getDayOfMonth(), 31); + assertEquals(2008, test.getYear()); + assertEquals(Month.DECEMBER, test.getMonth()); + assertEquals(31, test.getDayOfMonth()); } } } @@ -283,9 +287,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(false); i++) { LocalDate date = date(2007, month, i); LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfNextYear().adjustInto(date); - assertEquals(test.getYear(), 2008); - assertEquals(test.getMonth(), JANUARY); - assertEquals(test.getDayOfMonth(), 1); + assertEquals(2008, test.getYear()); + assertEquals(JANUARY, test.getMonth()); + assertEquals(1, test.getDayOfMonth()); } } } @@ -296,9 +300,9 @@ public class TCKTemporalAdjusters { for (int i = 1; i <= month.length(true); i++) { LocalDate date = date(2008, month, i); LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfNextYear().adjustInto(date); - assertEquals(test.getYear(), 2009); - assertEquals(test.getMonth(), JANUARY); - assertEquals(test.getDayOfMonth(), 1); + assertEquals(2009, test.getYear()); + assertEquals(JANUARY, test.getMonth()); + assertEquals(1, test.getDayOfMonth()); } } } @@ -311,12 +315,11 @@ public class TCKTemporalAdjusters { assertNotNull(TemporalAdjusters.dayOfWeekInMonth(1, MONDAY)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_dayOfWeekInMonth_nullDayOfWeek() { - TemporalAdjusters.dayOfWeekInMonth(1, null); + Assertions.assertThrows(NullPointerException.class, () -> TemporalAdjusters.dayOfWeekInMonth(1, null)); } - @DataProvider(name = "dayOfWeekInMonth_positive") Object[][] data_dayOfWeekInMonth_positive() { return new Object[][] { {2011, 1, TUESDAY, date(2011, 1, 4)}, @@ -334,18 +337,18 @@ public class TCKTemporalAdjusters { }; } - @Test(dataProvider = "dayOfWeekInMonth_positive") + @ParameterizedTest + @MethodSource("data_dayOfWeekInMonth_positive") public void test_dayOfWeekInMonth_positive(int year, int month, DayOfWeek dow, LocalDate expected) { for (int ordinal = 1; ordinal <= 5; ordinal++) { for (int day = 1; day <= Month.of(month).length(false); day++) { LocalDate date = date(year, month, day); LocalDate test = (LocalDate) TemporalAdjusters.dayOfWeekInMonth(ordinal, dow).adjustInto(date); - assertEquals(test, expected.plusWeeks(ordinal - 1)); + assertEquals(expected.plusWeeks(ordinal - 1), test); } } } - @DataProvider(name = "dayOfWeekInMonth_zero") Object[][] data_dayOfWeekInMonth_zero() { return new Object[][] { {2011, 1, TUESDAY, date(2010, 12, 28)}, @@ -363,16 +366,16 @@ public class TCKTemporalAdjusters { }; } - @Test(dataProvider = "dayOfWeekInMonth_zero") + @ParameterizedTest + @MethodSource("data_dayOfWeekInMonth_zero") public void test_dayOfWeekInMonth_zero(int year, int month, DayOfWeek dow, LocalDate expected) { for (int day = 1; day <= Month.of(month).length(false); day++) { LocalDate date = date(year, month, day); LocalDate test = (LocalDate) TemporalAdjusters.dayOfWeekInMonth(0, dow).adjustInto(date); - assertEquals(test, expected); + assertEquals(expected, test); } } - @DataProvider(name = "dayOfWeekInMonth_negative") Object[][] data_dayOfWeekInMonth_negative() { return new Object[][] { {2011, 1, TUESDAY, date(2011, 1, 25)}, @@ -390,13 +393,14 @@ public class TCKTemporalAdjusters { }; } - @Test(dataProvider = "dayOfWeekInMonth_negative") + @ParameterizedTest + @MethodSource("data_dayOfWeekInMonth_negative") public void test_dayOfWeekInMonth_negative(int year, int month, DayOfWeek dow, LocalDate expected) { for (int ordinal = 0; ordinal < 5; ordinal++) { for (int day = 1; day <= Month.of(month).length(false); day++) { LocalDate date = date(year, month, day); LocalDate test = (LocalDate) TemporalAdjusters.dayOfWeekInMonth(-1 - ordinal, dow).adjustInto(date); - assertEquals(test, expected.minusWeeks(ordinal)); + assertEquals(expected.minusWeeks(ordinal), test); } } } @@ -409,17 +413,18 @@ public class TCKTemporalAdjusters { assertNotNull(TemporalAdjusters.firstInMonth(MONDAY)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_firstInMonth_nullDayOfWeek() { - TemporalAdjusters.firstInMonth(null); + Assertions.assertThrows(NullPointerException.class, () -> TemporalAdjusters.firstInMonth(null)); } - @Test(dataProvider = "dayOfWeekInMonth_positive") + @ParameterizedTest + @MethodSource("data_dayOfWeekInMonth_positive") public void test_firstInMonth(int year, int month, DayOfWeek dow, LocalDate expected) { for (int day = 1; day <= Month.of(month).length(false); day++) { LocalDate date = date(year, month, day); LocalDate test = (LocalDate) TemporalAdjusters.firstInMonth(dow).adjustInto(date); - assertEquals(test, expected, "day-of-month=" + day); + assertEquals(expected, test, "day-of-month=" + day); } } @@ -431,17 +436,18 @@ public class TCKTemporalAdjusters { assertNotNull(TemporalAdjusters.lastInMonth(MONDAY)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_lastInMonth_nullDayOfWeek() { - TemporalAdjusters.lastInMonth(null); + Assertions.assertThrows(NullPointerException.class, () -> TemporalAdjusters.lastInMonth(null)); } - @Test(dataProvider = "dayOfWeekInMonth_negative") + @ParameterizedTest + @MethodSource("data_dayOfWeekInMonth_negative") public void test_lastInMonth(int year, int month, DayOfWeek dow, LocalDate expected) { for (int day = 1; day <= Month.of(month).length(false); day++) { LocalDate date = date(year, month, day); LocalDate test = (LocalDate) TemporalAdjusters.lastInMonth(dow).adjustInto(date); - assertEquals(test, expected, "day-of-month=" + day); + assertEquals(expected, test, "day-of-month=" + day); } } @@ -453,9 +459,9 @@ public class TCKTemporalAdjusters { assertNotNull(TemporalAdjusters.next(MONDAY)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void factory_next_nullDayOfWeek() { - TemporalAdjusters.next(null); + Assertions.assertThrows(NullPointerException.class, () -> TemporalAdjusters.next(null)); } @Test @@ -475,7 +481,7 @@ public class TCKTemporalAdjusters { } else { assertSame(month, Month.DECEMBER); assertTrue(date.getDayOfMonth() > 24); - assertEquals(test.getYear(), 2008); + assertEquals(2008, test.getYear()); assertSame(test.getMonth(), Month.JANUARY); assertTrue(test.getDayOfMonth() < 8); } @@ -492,9 +498,9 @@ public class TCKTemporalAdjusters { assertNotNull(TemporalAdjusters.nextOrSame(MONDAY)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void factory_nextOrCurrent_nullDayOfWeek() { - TemporalAdjusters.nextOrSame(null); + Assertions.assertThrows(NullPointerException.class, () -> TemporalAdjusters.nextOrSame(null)); } @Test @@ -511,12 +517,12 @@ public class TCKTemporalAdjusters { if (test.getYear() == 2007) { int dayDiff = test.getDayOfYear() - date.getDayOfYear(); assertTrue(dayDiff < 8); - assertEquals(date.equals(test), date.getDayOfWeek() == dow); + assertEquals(date.getDayOfWeek() == dow, date.equals(test)); } else { assertFalse(date.getDayOfWeek() == dow); assertSame(month, Month.DECEMBER); assertTrue(date.getDayOfMonth() > 24); - assertEquals(test.getYear(), 2008); + assertEquals(2008, test.getYear()); assertSame(test.getMonth(), Month.JANUARY); assertTrue(test.getDayOfMonth() < 8); } @@ -533,9 +539,9 @@ public class TCKTemporalAdjusters { assertNotNull(TemporalAdjusters.previous(MONDAY)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void factory_previous_nullDayOfWeek() { - TemporalAdjusters.previous(null); + Assertions.assertThrows(NullPointerException.class, () -> TemporalAdjusters.previous(null)); } @Test @@ -555,7 +561,7 @@ public class TCKTemporalAdjusters { } else { assertSame(month, Month.JANUARY); assertTrue(date.getDayOfMonth() < 8); - assertEquals(test.getYear(), 2006); + assertEquals(2006, test.getYear()); assertSame(test.getMonth(), Month.DECEMBER); assertTrue(test.getDayOfMonth() > 24); } @@ -572,9 +578,9 @@ public class TCKTemporalAdjusters { assertNotNull(TemporalAdjusters.previousOrSame(MONDAY)); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void factory_previousOrCurrent_nullDayOfWeek() { - TemporalAdjusters.previousOrSame(null); + Assertions.assertThrows(NullPointerException.class, () -> TemporalAdjusters.previousOrSame(null)); } @Test @@ -591,12 +597,12 @@ public class TCKTemporalAdjusters { if (test.getYear() == 2007) { int dayDiff = test.getDayOfYear() - date.getDayOfYear(); assertTrue(dayDiff <= 0 && dayDiff > -7); - assertEquals(date.equals(test), date.getDayOfWeek() == dow); + assertEquals(date.getDayOfWeek() == dow, date.equals(test)); } else { assertFalse(date.getDayOfWeek() == dow); assertSame(month, Month.JANUARY); assertTrue(date.getDayOfMonth() < 7); - assertEquals(test.getYear(), 2006); + assertEquals(2006, test.getYear()); assertSame(test.getMonth(), Month.DECEMBER); assertTrue(test.getDayOfMonth() > 25); } diff --git a/test/jdk/java/time/tck/java/time/temporal/TCKWeekFields.java b/test/jdk/java/time/tck/java/time/temporal/TCKWeekFields.java index f379766897c..b7c83f8de80 100644 --- a/test/jdk/java/time/tck/java/time/temporal/TCKWeekFields.java +++ b/test/jdk/java/time/tck/java/time/temporal/TCKWeekFields.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -62,11 +62,12 @@ import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.DAY_OF_YEAR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.time.DateTimeException; @@ -79,85 +80,92 @@ import java.time.temporal.TemporalField; import java.time.temporal.ValueRange; import java.time.temporal.WeekFields; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import tck.java.time.AbstractTCKTest; /** * Test WeekFields. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKWeekFields extends AbstractTCKTest { - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_of_DayOfWeek_int_singleton(DayOfWeek firstDayOfWeek, int minDays) { WeekFields week = WeekFields.of(firstDayOfWeek, minDays); - assertEquals(week.getFirstDayOfWeek(), firstDayOfWeek, "Incorrect firstDayOfWeek"); - assertEquals(week.getMinimalDaysInFirstWeek(), minDays, "Incorrect MinimalDaysInFirstWeek"); + assertEquals(firstDayOfWeek, week.getFirstDayOfWeek(), "Incorrect firstDayOfWeek"); + assertEquals(minDays, week.getMinimalDaysInFirstWeek(), "Incorrect MinimalDaysInFirstWeek"); assertSame(WeekFields.of(firstDayOfWeek, minDays), week); } //----------------------------------------------------------------------- - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_basics(DayOfWeek firstDayOfWeek, int minDays) { WeekFields week = WeekFields.of(firstDayOfWeek, minDays); - assertEquals(week.dayOfWeek().isDateBased(), true); - assertEquals(week.dayOfWeek().isTimeBased(), false); + assertEquals(true, week.dayOfWeek().isDateBased()); + assertEquals(false, week.dayOfWeek().isTimeBased()); - assertEquals(week.weekOfMonth().isDateBased(), true); - assertEquals(week.weekOfMonth().isTimeBased(), false); + assertEquals(true, week.weekOfMonth().isDateBased()); + assertEquals(false, week.weekOfMonth().isTimeBased()); - assertEquals(week.weekOfYear().isDateBased(), true); - assertEquals(week.weekOfYear().isTimeBased(), false); + assertEquals(true, week.weekOfYear().isDateBased()); + assertEquals(false, week.weekOfYear().isTimeBased()); - assertEquals(week.weekOfWeekBasedYear().isDateBased(), true); - assertEquals(week.weekOfWeekBasedYear().isTimeBased(), false); + assertEquals(true, week.weekOfWeekBasedYear().isDateBased()); + assertEquals(false, week.weekOfWeekBasedYear().isTimeBased()); - assertEquals(week.weekBasedYear().isDateBased(), true); - assertEquals(week.weekBasedYear().isTimeBased(), false); + assertEquals(true, week.weekBasedYear().isDateBased()); + assertEquals(false, week.weekBasedYear().isTimeBased()); } //----------------------------------------------------------------------- @Test public void test_dayOfWeekField_simpleGet() { LocalDate date = LocalDate.of(2000, 1, 10); // Known to be ISO Monday - assertEquals(date.get(WeekFields.ISO.dayOfWeek()), 1); - assertEquals(date.get(WeekFields.of(DayOfWeek.MONDAY, 1).dayOfWeek()), 1); - assertEquals(date.get(WeekFields.of(DayOfWeek.MONDAY, 7).dayOfWeek()), 1); - assertEquals(date.get(WeekFields.SUNDAY_START.dayOfWeek()), 2); - assertEquals(date.get(WeekFields.of(DayOfWeek.SUNDAY, 1).dayOfWeek()), 2); - assertEquals(date.get(WeekFields.of(DayOfWeek.SUNDAY, 7).dayOfWeek()), 2); - assertEquals(date.get(WeekFields.of(DayOfWeek.SATURDAY, 1).dayOfWeek()), 3); - assertEquals(date.get(WeekFields.of(DayOfWeek.FRIDAY, 1).dayOfWeek()), 4); - assertEquals(date.get(WeekFields.of(DayOfWeek.TUESDAY, 1).dayOfWeek()), 7); + assertEquals(1, date.get(WeekFields.ISO.dayOfWeek())); + assertEquals(1, date.get(WeekFields.of(DayOfWeek.MONDAY, 1).dayOfWeek())); + assertEquals(1, date.get(WeekFields.of(DayOfWeek.MONDAY, 7).dayOfWeek())); + assertEquals(2, date.get(WeekFields.SUNDAY_START.dayOfWeek())); + assertEquals(2, date.get(WeekFields.of(DayOfWeek.SUNDAY, 1).dayOfWeek())); + assertEquals(2, date.get(WeekFields.of(DayOfWeek.SUNDAY, 7).dayOfWeek())); + assertEquals(3, date.get(WeekFields.of(DayOfWeek.SATURDAY, 1).dayOfWeek())); + assertEquals(4, date.get(WeekFields.of(DayOfWeek.FRIDAY, 1).dayOfWeek())); + assertEquals(7, date.get(WeekFields.of(DayOfWeek.TUESDAY, 1).dayOfWeek())); } @Test public void test_dayOfWeekField_simpleSet() { LocalDate date = LocalDate.of(2000, 1, 10); // Known to be ISO Monday - assertEquals(date.with(WeekFields.ISO.dayOfWeek(), 2), LocalDate.of(2000, 1, 11)); - assertEquals(date.with(WeekFields.ISO.dayOfWeek(), 7), LocalDate.of(2000, 1, 16)); + assertEquals(LocalDate.of(2000, 1, 11), date.with(WeekFields.ISO.dayOfWeek(), 2)); + assertEquals(LocalDate.of(2000, 1, 16), date.with(WeekFields.ISO.dayOfWeek(), 7)); - assertEquals(date.with(WeekFields.SUNDAY_START.dayOfWeek(), 3), LocalDate.of(2000, 1, 11)); - assertEquals(date.with(WeekFields.SUNDAY_START.dayOfWeek(), 7), LocalDate.of(2000, 1, 15)); + assertEquals(LocalDate.of(2000, 1, 11), date.with(WeekFields.SUNDAY_START.dayOfWeek(), 3)); + assertEquals(LocalDate.of(2000, 1, 15), date.with(WeekFields.SUNDAY_START.dayOfWeek(), 7)); - assertEquals(date.with(WeekFields.of(DayOfWeek.SATURDAY, 1).dayOfWeek(), 4), LocalDate.of(2000, 1, 11)); - assertEquals(date.with(WeekFields.of(DayOfWeek.TUESDAY, 1).dayOfWeek(), 1), LocalDate.of(2000, 1, 4)); + assertEquals(LocalDate.of(2000, 1, 11), date.with(WeekFields.of(DayOfWeek.SATURDAY, 1).dayOfWeek(), 4)); + assertEquals(LocalDate.of(2000, 1, 4), date.with(WeekFields.of(DayOfWeek.TUESDAY, 1).dayOfWeek(), 1)); } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_dayOfWeekField(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2000, 1, 10); // Known to be ISO Monday WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField f = week.dayOfWeek(); for (int i = 1; i <= 7; i++) { - assertEquals(day.get(f), (7 + day.getDayOfWeek().getValue() - firstDayOfWeek.getValue()) % 7 + 1); + assertEquals((7 + day.getDayOfWeek().getValue() - firstDayOfWeek.getValue()) % 7 + 1, day.get(f)); day = day.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_weekOfMonthField(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2012, 12, 31); // Known to be ISO Monday WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -183,14 +191,15 @@ public class TCKWeekFields extends AbstractTCKTest { offset += (actualWOM - 1) * 7; LocalDate result = day1.plusDays(offset); - assertEquals(result, day, "Incorrect dayOfWeek or weekOfMonth: " + assertEquals(day, result, "Incorrect dayOfWeek or weekOfMonth: " + String.format("%s, ISO Dow: %s, offset: %s, actualDOW: %s, actualWOM: %s, expected: %s, result: %s%n", week, day.getDayOfWeek(), offset, actualDOW, actualWOM, day, result)); day = day.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_weekOfYearField(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2012, 12, 31); // Known to be ISO Monday WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -214,7 +223,7 @@ public class TCKWeekFields extends AbstractTCKTest { offset += (actualWOY - 1) * 7; LocalDate result = day1.plusDays(offset); - assertEquals(result, day, "Incorrect dayOfWeek or weekOfYear " + assertEquals(day, result, "Incorrect dayOfWeek or weekOfYear " + String.format("%s, ISO Dow: %s, offset: %s, actualDOW: %s, actualWOM: %s, expected: %s, result: %s%n", week, day.getDayOfWeek(), offset, actualDOW, actualWOY, day, result)); day = day.plusDays(1); @@ -228,7 +237,8 @@ public class TCKWeekFields extends AbstractTCKTest { * @param firstDayOfWeek the first day of the week * @param minDays the minimum number of days in the week */ - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_weekOfWeekBasedYearField(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2012, 12, 31); // Known to be ISO Monday WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays); @@ -256,14 +266,15 @@ public class TCKWeekFields extends AbstractTCKTest { weekStart += (actualWOWBY - 1) * 7; LocalDate result = day1.plusDays(weekStart); - assertEquals(result, day, "Incorrect dayOfWeek or weekOfYear " + assertEquals(day, result, "Incorrect dayOfWeek or weekOfYear " + String.format("%s, ISO Dow: %s, weekStart: %s, actualDOW: %s, actualWOWBY: %s, YearOfWBY: %d, expected day: %s, result: %s%n", weekDef, day.getDayOfWeek(), weekStart, actualDOW, actualWOWBY, actualYOWBY, day, result)); day = day.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_fieldRanges(DayOfWeek firstDayOfWeek, int minDays) { WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays); TemporalField womField = weekDef.weekOfMonth(); @@ -277,10 +288,10 @@ public class TCKWeekFields extends AbstractTCKTest { LocalDate first = day.with(DAY_OF_MONTH, 1); int firstWOM = first.get(womField); ValueRange rangeWOM = day.range(womField); - assertEquals(rangeWOM.getMinimum(), firstWOM, + assertEquals(firstWOM, rangeWOM.getMinimum(), "Range min should be same as WeekOfMonth for first day of month: " + first + ", " + weekDef); - assertEquals(rangeWOM.getMaximum(), lastWOM, + assertEquals(lastWOM, rangeWOM.getMaximum(), "Range max should be same as WeekOfMonth for last day of month: " + last + ", " + weekDef); @@ -289,10 +300,10 @@ public class TCKWeekFields extends AbstractTCKTest { first = day.with(DAY_OF_YEAR, 1); int firstWOY = first.get(woyField); ValueRange rangeWOY = day.range(woyField); - assertEquals(rangeWOY.getMinimum(), firstWOY, + assertEquals(firstWOY, rangeWOY.getMinimum(), "Range min should be same as WeekOfYear for first day of Year: " + day + ", " + weekDef); - assertEquals(rangeWOY.getMaximum(), lastWOY, + assertEquals(lastWOY, rangeWOY.getMaximum(), "Range max should be same as WeekOfYear for last day of Year: " + day + ", " + weekDef); @@ -303,7 +314,8 @@ public class TCKWeekFields extends AbstractTCKTest { //----------------------------------------------------------------------- // withDayOfWeek() //----------------------------------------------------------------------- - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_withDayOfWeek(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2012, 12, 15); // Safely in the middle of a month WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -315,13 +327,14 @@ public class TCKWeekFields extends AbstractTCKTest { int woy = day.get(woyField); for (int dow = 1; dow <= 7; dow++) { LocalDate result = day.with(dowField, dow); - assertEquals(result.get(dowField), dow, String.format("Incorrect new Day of week: %s", result)); - assertEquals(result.get(womField), wom, "Week of Month should not change"); - assertEquals(result.get(woyField), woy, "Week of Year should not change"); + assertEquals(dow, result.get(dowField), String.format("Incorrect new Day of week: %s", result)); + assertEquals(wom, result.get(womField), "Week of Month should not change"); + assertEquals(woy, result.get(woyField), "Week of Year should not change"); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_rangeWeekOfWeekBasedYear(DayOfWeek firstDayOfWeek, int minDays) { WeekFields weekFields = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = weekFields.dayOfWeek(); @@ -336,10 +349,11 @@ public class TCKWeekFields extends AbstractTCKTest { int expectedWeeks = (int)ChronoUnit.DAYS.between(day1, day2) / 7; ValueRange range = day1.range(wowByField); - assertEquals(range.getMaximum(), expectedWeeks, "Range incorrect"); + assertEquals(expectedWeeks, range.getMaximum(), "Range incorrect"); } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_withWeekOfWeekBasedYear(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2012, 12, 31); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -350,30 +364,31 @@ public class TCKWeekFields extends AbstractTCKTest { int dowExpected = (day.get(dowField) - 1) % 7 + 1; LocalDate dowDate = day.with(dowField, dowExpected); int dowResult = dowDate.get(dowField); - assertEquals(dowResult, dowExpected, "Localized DayOfWeek not correct; " + day + " -->" + dowDate); + assertEquals(dowExpected, dowResult, "Localized DayOfWeek not correct; " + day + " -->" + dowDate); int weekExpected = day.get(wowbyField) + 1; ValueRange range = day.range(wowbyField); weekExpected = ((weekExpected - 1) % (int)range.getMaximum()) + 1; LocalDate weekDate = day.with(wowbyField, weekExpected); int weekResult = weekDate.get(wowbyField); - assertEquals(weekResult, weekExpected, "Localized WeekOfWeekBasedYear not correct; " + day + " -->" + weekDate); + assertEquals(weekExpected, weekResult, "Localized WeekOfWeekBasedYear not correct; " + day + " -->" + weekDate); int yearExpected = day.get(yowbyField) + 1; LocalDate yearDate = day.with(yowbyField, yearExpected); int yearResult = yearDate.get(yowbyField); - assertEquals(yearResult, yearExpected, "Localized WeekBasedYear not correct; " + day + " --> " + yearDate); + assertEquals(yearExpected, yearResult, "Localized WeekBasedYear not correct; " + day + " --> " + yearDate); range = yearDate.range(wowbyField); weekExpected = Math.min(day.get(wowbyField), (int)range.getMaximum()); int weekActual = yearDate.get(wowbyField); - assertEquals(weekActual, weekExpected, "Localized WeekOfWeekBasedYear week should not change; " + day + " --> " + yearDate + ", actual: " + weekActual + ", weekExpected: " + weekExpected); + assertEquals(weekExpected, weekActual, "Localized WeekOfWeekBasedYear week should not change; " + day + " --> " + yearDate + ", actual: " + weekActual + ", weekExpected: " + weekExpected); } //----------------------------------------------------------------------- - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWom(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -388,13 +403,14 @@ public class TCKWeekFields extends AbstractTCKTest { String str = date.getYear() + ":" + date.getMonthValue() + ":" + date.get(womField) + ":" + date.get(DAY_OF_WEEK); LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date, " ::" + str + "::" + i); + assertEquals(date, parsed, " ::" + str + "::" + i); date = date.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWom_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -411,14 +427,15 @@ public class TCKWeekFields extends AbstractTCKTest { for (int j = wom - 10; j < wom + 10; j++) { String str = date.getYear() + ":" + date.getMonthValue() + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date.plusWeeks(j - wom), " ::" + str + ": :" + i + "::" + j); + assertEquals(date.plusWeeks(j - wom), parsed, " ::" + str + ": :" + i + "::" + j); } date = date.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWom_strict(DayOfWeek firstDayOfWeek, int minDays) { WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField womField = week.weekOfMonth(); @@ -430,17 +447,18 @@ public class TCKWeekFields extends AbstractTCKTest { String str = "2012:1:0:1"; try { LocalDate date = LocalDate.parse(str, f); - assertEquals(date.getYear(), 2012); - assertEquals(date.getMonthValue(), 1); - assertEquals(date.get(womField), 0); - assertEquals(date.get(DAY_OF_WEEK), 1); + assertEquals(2012, date.getYear()); + assertEquals(1, date.getMonthValue()); + assertEquals(0, date.get(womField)); + assertEquals(1, date.get(DAY_OF_WEEK)); } catch (DateTimeException ex) { // expected } } //----------------------------------------------------------------------- - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWomDow(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -456,13 +474,14 @@ public class TCKWeekFields extends AbstractTCKTest { String str = date.getYear() + ":" + date.getMonthValue() + ":" + date.get(womField) + ":" + date.get(dowField); LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date, " :: " + str + " " + i); + assertEquals(date, parsed, " :: " + str + " " + i); date = date.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWomDow_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -480,7 +499,7 @@ public class TCKWeekFields extends AbstractTCKTest { for (int j = wom - 10; j < wom + 10; j++) { String str = date.getYear() + ":" + date.getMonthValue() + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date.plusWeeks(j - wom), " ::" + str + ": :" + i + "::" + j); + assertEquals(date.plusWeeks(j - wom), parsed, " ::" + str + ": :" + i + "::" + j); } date = date.plusDays(1); @@ -488,7 +507,8 @@ public class TCKWeekFields extends AbstractTCKTest { } //----------------------------------------------------------------------- - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWoy(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -502,13 +522,14 @@ public class TCKWeekFields extends AbstractTCKTest { String str = date.getYear() + ":" + date.get(woyField) + ":" + date.get(DAY_OF_WEEK); LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date, " :: " + str + " " + i); + assertEquals(date, parsed, " :: " + str + " " + i); date = date.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWoy_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -524,14 +545,15 @@ public class TCKWeekFields extends AbstractTCKTest { for (int j = woy - 60; j < woy + 60; j++) { String str = date.getYear() + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date.plusWeeks(j - woy), " ::" + str + ": :" + i + "::" + j); + assertEquals(date.plusWeeks(j - woy), parsed, " ::" + str + ": :" + i + "::" + j); } date = date.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWoy_strict(DayOfWeek firstDayOfWeek, int minDays) { WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField woyField = week.weekOfYear(); @@ -542,16 +564,17 @@ public class TCKWeekFields extends AbstractTCKTest { String str = "2012:0:1"; try { LocalDate date = LocalDate.parse(str, f); - assertEquals(date.getYear(), 2012); - assertEquals(date.get(woyField), 0); - assertEquals(date.get(DAY_OF_WEEK), 1); + assertEquals(2012, date.getYear()); + assertEquals(0, date.get(woyField)); + assertEquals(1, date.get(DAY_OF_WEEK)); } catch (DateTimeException ex) { // expected } } //----------------------------------------------------------------------- - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWoyDow(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -567,13 +590,14 @@ public class TCKWeekFields extends AbstractTCKTest { String str = date.getYear() + ":" + date.getMonthValue() + ":" + date.get(woyField) + ":" + date.get(dowField); LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date, " :: " + str + " " + i); + assertEquals(date, parsed, " :: " + str + " " + i); date = date.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWoyDow_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -590,7 +614,7 @@ public class TCKWeekFields extends AbstractTCKTest { for (int j = woy - 60; j < woy + 60; j++) { String str = date.getYear() + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date.plusWeeks(j - woy), " ::" + str + ": :" + i + "::" + j); + assertEquals(date.plusWeeks(j - woy), parsed, " ::" + str + ": :" + i + "::" + j); } date = date.plusDays(1); @@ -598,7 +622,8 @@ public class TCKWeekFields extends AbstractTCKTest { } //----------------------------------------------------------------------- - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWoWBY(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 31); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -613,13 +638,14 @@ public class TCKWeekFields extends AbstractTCKTest { String str = date.get(yowbyField) + ":" + date.get(wowbyField) + ":" + date.get(DAY_OF_WEEK); LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date, " :: " + str + " " + i); + assertEquals(date, parsed, " :: " + str + " " + i); date = date.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWoWBY_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 31); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -636,14 +662,15 @@ public class TCKWeekFields extends AbstractTCKTest { for (int j = wowby - 60; j < wowby + 60; j++) { String str = date.get(yowbyField) + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date.plusWeeks(j - wowby), " ::" + str + ": :" + i + "::" + j); + assertEquals(date.plusWeeks(j - wowby), parsed, " ::" + str + ": :" + i + "::" + j); } date = date.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWoWBY_strict(DayOfWeek firstDayOfWeek, int minDays) { WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField wowbyField = week.weekOfWeekBasedYear(); @@ -655,16 +682,17 @@ public class TCKWeekFields extends AbstractTCKTest { String str = "2012:0:1"; try { LocalDate date = LocalDate.parse(str, f); - assertEquals(date.get(yowbyField), 2012); - assertEquals(date.get(wowbyField), 0); - assertEquals(date.get(DAY_OF_WEEK), 1); + assertEquals(2012, date.get(yowbyField)); + assertEquals(0, date.get(wowbyField)); + assertEquals(1, date.get(DAY_OF_WEEK)); } catch (DateTimeException ex) { // expected } } //----------------------------------------------------------------------- - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWoWBYDow(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 31); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -680,13 +708,14 @@ public class TCKWeekFields extends AbstractTCKTest { String str = date.get(yowbyField) + ":" + date.get(wowbyField) + ":" + date.get(dowField); LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date, " :: " + str + " " + i); + assertEquals(date, parsed, " :: " + str + " " + i); date = date.plusDays(1); } } - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_parse_resolve_localizedWoWBYDow_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 31); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); @@ -704,7 +733,7 @@ public class TCKWeekFields extends AbstractTCKTest { for (int j = wowby - 60; j < wowby + 60; j++) { String str = date.get(yowbyField) + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); - assertEquals(parsed, date.plusWeeks(j - wowby), " ::" + str + ": :" + i + "::" + j); + assertEquals(date.plusWeeks(j - wowby), parsed, " ::" + str + ": :" + i + "::" + j); } date = date.plusDays(1); @@ -713,7 +742,6 @@ public class TCKWeekFields extends AbstractTCKTest { //----------------------------------------------------------------------- - @DataProvider(name="weekFields") Object[][] data_weekFields() { Object[][] objects = new Object[49][]; int i = 0; @@ -726,7 +754,6 @@ public class TCKWeekFields extends AbstractTCKTest { } //----------------------------------------------------------------------- - @DataProvider(name="WeekBasedYearData") Object[][] provider_WeekBasedYearData() { return new Object[][] { {WeekFields.of(DayOfWeek.SUNDAY, 1), 2008, 52, 7, LocalDate.of(2008, 12, 27)}, @@ -741,20 +768,20 @@ public class TCKWeekFields extends AbstractTCKTest { }; } - @Test(dataProvider="WeekBasedYearData") + @ParameterizedTest + @MethodSource("provider_WeekBasedYearData") public void test_weekBasedYears(WeekFields weekDef, int weekBasedYear, int weekOfWeekBasedYear, int dayOfWeek, LocalDate date) { TemporalField dowField = weekDef.dayOfWeek(); TemporalField wowbyField = weekDef.weekOfWeekBasedYear(); TemporalField yowbyField = weekDef.weekBasedYear(); - assertEquals(date.get(dowField), dayOfWeek, "DayOfWeek mismatch"); - assertEquals(date.get(wowbyField), weekOfWeekBasedYear, "Week of WeekBasedYear mismatch"); - assertEquals(date.get(yowbyField), weekBasedYear, "Year of WeekBasedYear mismatch"); + assertEquals(dayOfWeek, date.get(dowField), "DayOfWeek mismatch"); + assertEquals(weekOfWeekBasedYear, date.get(wowbyField), "Week of WeekBasedYear mismatch"); + assertEquals(weekBasedYear, date.get(yowbyField), "Year of WeekBasedYear mismatch"); } //----------------------------------------------------------------------- - @DataProvider(name="IsoWeekData") Object[][] data_week() { return new Object[][] { {LocalDate.of(1969, 12, 29), DayOfWeek.MONDAY, 1, 1970}, @@ -776,16 +803,17 @@ public class TCKWeekFields extends AbstractTCKTest { // WEEK_OF_WEEK_BASED_YEAR // Validate with the same data used by IsoFields. //----------------------------------------------------------------------- - @Test(dataProvider="IsoWeekData") + @ParameterizedTest + @MethodSource("data_week") public void test_WOWBY(LocalDate date, DayOfWeek dow, int week, int wby) { WeekFields weekDef = WeekFields.ISO; TemporalField dowField = weekDef.dayOfWeek(); TemporalField wowbyField = weekDef.weekOfWeekBasedYear(); TemporalField yowbyField = weekDef.weekBasedYear(); - assertEquals(date.get(dowField), dow.getValue()); - assertEquals(date.get(wowbyField), week); - assertEquals(date.get(yowbyField), wby); + assertEquals(dow.getValue(), date.get(dowField)); + assertEquals(week, date.get(wowbyField)); + assertEquals(wby, date.get(yowbyField)); } //----------------------------------------------------------------------- @@ -798,11 +826,11 @@ public class TCKWeekFields extends AbstractTCKTest { assertTrue(weekDef_iso.equals(WeekFields.of(DayOfWeek.MONDAY, 4))); assertTrue(weekDef_sundayStart.equals(WeekFields.of(DayOfWeek.SUNDAY, 1))); - assertEquals(weekDef_iso.hashCode(), WeekFields.of(DayOfWeek.MONDAY, 4).hashCode()); - assertEquals(weekDef_sundayStart.hashCode(), WeekFields.of(DayOfWeek.SUNDAY, 1).hashCode()); + assertEquals(WeekFields.of(DayOfWeek.MONDAY, 4).hashCode(), weekDef_iso.hashCode()); + assertEquals(WeekFields.of(DayOfWeek.SUNDAY, 1).hashCode(), weekDef_sundayStart.hashCode()); assertFalse(weekDef_iso.equals(weekDef_sundayStart)); - assertNotEquals(weekDef_iso.hashCode(), weekDef_sundayStart.hashCode()); + assertNotEquals(weekDef_sundayStart.hashCode(), weekDef_iso.hashCode()); } } diff --git a/test/jdk/java/time/tck/java/time/temporal/serial/TCKChronoFieldSerialization.java b/test/jdk/java/time/tck/java/time/temporal/serial/TCKChronoFieldSerialization.java index bb8c5c566a5..b82a278cb34 100644 --- a/test/jdk/java/time/tck/java/time/temporal/serial/TCKChronoFieldSerialization.java +++ b/test/jdk/java/time/tck/java/time/temporal/serial/TCKChronoFieldSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -86,21 +86,21 @@ import static java.time.temporal.ChronoField.ERA; import java.io.IOException; import java.time.temporal.ChronoField; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import tck.java.time.AbstractTCKTest; /** * Test serialization of ChronoField. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoFieldSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // List of Fields //----------------------------------------------------------------------- - @DataProvider(name="fieldBased") Object[][] data_fieldBased() { return new Object[][] { {DAY_OF_WEEK}, @@ -135,7 +135,8 @@ public class TCKChronoFieldSerialization extends AbstractTCKTest { }; } - @Test(dataProvider = "fieldBased") + @ParameterizedTest + @MethodSource("data_fieldBased") public void test_fieldSerializable(ChronoField field) throws IOException, ClassNotFoundException { assertSerializableSame(field); } diff --git a/test/jdk/java/time/tck/java/time/temporal/serial/TCKChronoUnitSerialization.java b/test/jdk/java/time/tck/java/time/temporal/serial/TCKChronoUnitSerialization.java index e97e183d252..9714220b7be 100644 --- a/test/jdk/java/time/tck/java/time/temporal/serial/TCKChronoUnitSerialization.java +++ b/test/jdk/java/time/tck/java/time/temporal/serial/TCKChronoUnitSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -74,21 +74,21 @@ import static java.time.temporal.ChronoUnit.YEARS; import java.io.IOException; import java.time.temporal.ChronoUnit; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import tck.java.time.AbstractTCKTest; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKChronoUnitSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // ChronoUnits //----------------------------------------------------------------------- - @DataProvider(name="chronoUnit") Object[][] data_chronoUnit() { return new Object[][] { {FOREVER}, @@ -112,7 +112,8 @@ public class TCKChronoUnitSerialization extends AbstractTCKTest { }; } - @Test(dataProvider = "chronoUnit") + @ParameterizedTest + @MethodSource("data_chronoUnit") public void test_unitType(ChronoUnit unit) throws IOException, ClassNotFoundException { assertSerializableSame(unit); } diff --git a/test/jdk/java/time/tck/java/time/temporal/serial/TCKJulianFieldsSerialization.java b/test/jdk/java/time/tck/java/time/temporal/serial/TCKJulianFieldsSerialization.java index 53047f8441a..a861290ac0e 100644 --- a/test/jdk/java/time/tck/java/time/temporal/serial/TCKJulianFieldsSerialization.java +++ b/test/jdk/java/time/tck/java/time/temporal/serial/TCKJulianFieldsSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -63,19 +63,19 @@ import java.io.IOException; import java.time.temporal.JulianFields; import java.time.temporal.TemporalField; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import tck.java.time.AbstractTCKTest; /** * Test serialization of JulianFields */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKJulianFieldsSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- - @DataProvider(name="julian_fields") Object[][] julian_samples() { return new Object[][] { {JulianFields.JULIAN_DAY}, @@ -86,7 +86,8 @@ public class TCKJulianFieldsSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- - @Test(dataProvider="julian_fields") + @ParameterizedTest + @MethodSource("julian_samples") public void test_serializable(TemporalField field) throws IOException, ClassNotFoundException { assertSerializable(field); } diff --git a/test/jdk/java/time/tck/java/time/temporal/serial/TCKValueRangeSerialization.java b/test/jdk/java/time/tck/java/time/temporal/serial/TCKValueRangeSerialization.java index d99efd03535..a3612e7f6a6 100644 --- a/test/jdk/java/time/tck/java/time/temporal/serial/TCKValueRangeSerialization.java +++ b/test/jdk/java/time/tck/java/time/temporal/serial/TCKValueRangeSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,7 @@ */ package tck.java.time.temporal.serial; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -71,19 +70,20 @@ import java.io.ObjectOutputStream; import java.time.temporal.ValueRange; import java.util.Arrays; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import tck.java.time.AbstractTCKTest; /** * Test serialization of ValueRange. */ -@Test public class TCKValueRangeSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- // Serialization //----------------------------------------------------------------------- + @Test public void test_serialization() throws Exception { ValueRange range = ValueRange.of(1, 2, 3, 4); assertSerializable(range); @@ -94,6 +94,7 @@ public class TCKValueRangeSerialization extends AbstractTCKTest { * Verify Serialized bytes of a ValueRange. * @throws IOException if thrown during serialization is an unexpected test tailure */ + @Test public void test_valueRangeSerialized() throws IOException { byte[] expected = { (byte)172, (byte)237, 0, 5, 115, 114, 0, 29, 106, 97, /* \u00ac \u00ed \u0000 \u0005 s r \u0000 \u001d j a */ @@ -118,7 +119,7 @@ public class TCKValueRangeSerialization extends AbstractTCKTest { oos.writeObject(range); byte[] actual = baos.toByteArray(); - assertEquals(actual, expected, "Serialized bytes incorrect"); + Assertions.assertArrayEquals(expected, actual, "Serialized bytes incorrect"); } } diff --git a/test/jdk/java/time/tck/java/time/temporal/serial/TCKWeekFieldsSerialization.java b/test/jdk/java/time/tck/java/time/temporal/serial/TCKWeekFieldsSerialization.java index 3523f05c88c..34171276cd1 100644 --- a/test/jdk/java/time/tck/java/time/temporal/serial/TCKWeekFieldsSerialization.java +++ b/test/jdk/java/time/tck/java/time/temporal/serial/TCKWeekFieldsSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,13 +54,11 @@ */ package tck.java.time.temporal.serial; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.io.IOException; @@ -70,21 +68,26 @@ import java.time.DayOfWeek; import java.time.temporal.WeekFields; import java.util.Arrays; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + /** * Test serialization of WeekFields. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKWeekFieldsSerialization extends AbstractTCKTest { //----------------------------------------------------------------------- - @Test(dataProvider="weekFields") + @ParameterizedTest + @MethodSource("data_weekFields") public void test_serializable_singleton(DayOfWeek firstDayOfWeek, int minDays) throws IOException, ClassNotFoundException { WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays); assertSerializableSame(weekDef); // spec state singleton } //----------------------------------------------------------------------- - @DataProvider(name="weekFields") Object[][] data_weekFields() { Object[][] objects = new Object[49][]; int i = 0; @@ -110,7 +113,7 @@ public class TCKWeekFieldsSerialization extends AbstractTCKTest { System.arraycopy(good1, 0, val, 105, good1.length); try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(val))) { Object o = in.readObject(); - assertEquals(o, WeekFields.of(DayOfWeek.MONDAY, 5), "Should be MONDAY, min = 5"); + assertEquals(WeekFields.of(DayOfWeek.MONDAY, 5), o, "Should be MONDAY, min = 5"); } catch (Exception ioe) { fail("Unexpected exception " + ioe); } diff --git a/test/jdk/java/time/tck/java/time/zone/TCKFixedZoneRules.java b/test/jdk/java/time/tck/java/time/zone/TCKFixedZoneRules.java index 08df5433349..83d8af37306 100644 --- a/test/jdk/java/time/tck/java/time/zone/TCKFixedZoneRules.java +++ b/test/jdk/java/time/tck/java/time/zone/TCKFixedZoneRules.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,7 +59,7 @@ */ package tck.java.time.zone; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -76,13 +76,16 @@ import java.time.zone.ZoneOffsetTransitionRule; import java.time.zone.ZoneOffsetTransitionRule.TimeDefinition; import java.time.zone.ZoneRules; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test ZoneRules for fixed offset time-zones. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKFixedZoneRules { private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); @@ -95,7 +98,6 @@ public class TCKFixedZoneRules { return offset.getRules(); } - @DataProvider(name="rules") Object[][] data_rules() { return new Object[][] { {make(OFFSET_PONE), OFFSET_PONE}, @@ -108,95 +110,111 @@ public class TCKFixedZoneRules { // Basics //----------------------------------------------------------------------- - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_getOffset_Instant(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.getOffset(INSTANT), expectedOffset); - assertEquals(test.getOffset((Instant) null), expectedOffset); + assertEquals(expectedOffset, test.getOffset(INSTANT)); + assertEquals(expectedOffset, test.getOffset((Instant) null)); } - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_getOffset_LocalDateTime(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.getOffset(LDT), expectedOffset); - assertEquals(test.getOffset((LocalDateTime) null), expectedOffset); + assertEquals(expectedOffset, test.getOffset(LDT)); + assertEquals(expectedOffset, test.getOffset((LocalDateTime) null)); } - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_getValidOffsets_LDT(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.getValidOffsets(LDT).size(), 1); - assertEquals(test.getValidOffsets(LDT).get(0), expectedOffset); - assertEquals(test.getValidOffsets(null).size(), 1); - assertEquals(test.getValidOffsets(null).get(0), expectedOffset); + assertEquals(1, test.getValidOffsets(LDT).size()); + assertEquals(expectedOffset, test.getValidOffsets(LDT).get(0)); + assertEquals(1, test.getValidOffsets(null).size()); + assertEquals(expectedOffset, test.getValidOffsets(null).get(0)); } - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_getTransition_LDT(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.getTransition(LDT), null); - assertEquals(test.getTransition(null), null); + assertEquals(null, test.getTransition(LDT)); + assertEquals(null, test.getTransition(null)); } - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_isValidOffset_LDT_ZO(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.isValidOffset(LDT, expectedOffset), true); - assertEquals(test.isValidOffset(LDT, ZoneOffset.UTC), false); - assertEquals(test.isValidOffset(LDT, null), false); + assertEquals(true, test.isValidOffset(LDT, expectedOffset)); + assertEquals(false, test.isValidOffset(LDT, ZoneOffset.UTC)); + assertEquals(false, test.isValidOffset(LDT, null)); - assertEquals(test.isValidOffset(null, expectedOffset), true); - assertEquals(test.isValidOffset(null, ZoneOffset.UTC), false); - assertEquals(test.isValidOffset(null, null), false); + assertEquals(true, test.isValidOffset(null, expectedOffset)); + assertEquals(false, test.isValidOffset(null, ZoneOffset.UTC)); + assertEquals(false, test.isValidOffset(null, null)); } - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_getStandardOffset_Instant(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.getStandardOffset(INSTANT), expectedOffset); - assertEquals(test.getStandardOffset(null), expectedOffset); + assertEquals(expectedOffset, test.getStandardOffset(INSTANT)); + assertEquals(expectedOffset, test.getStandardOffset(null)); } - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_getDaylightSavings_Instant(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.getDaylightSavings(INSTANT), Duration.ZERO); - assertEquals(test.getDaylightSavings(null), Duration.ZERO); + assertEquals(Duration.ZERO, test.getDaylightSavings(INSTANT)); + assertEquals(Duration.ZERO, test.getDaylightSavings(null)); } - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_isDaylightSavings_Instant(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.isDaylightSavings(INSTANT), false); - assertEquals(test.isDaylightSavings(null), false); + assertEquals(false, test.isDaylightSavings(INSTANT)); + assertEquals(false, test.isDaylightSavings(null)); } //------------------------------------------------------------------------- - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_nextTransition_Instant(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.nextTransition(INSTANT), null); - assertEquals(test.nextTransition(null), null); + assertEquals(null, test.nextTransition(INSTANT)); + assertEquals(null, test.nextTransition(null)); } - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_previousTransition_Instant(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.previousTransition(INSTANT), null); - assertEquals(test.previousTransition(null), null); + assertEquals(null, test.previousTransition(INSTANT)); + assertEquals(null, test.previousTransition(null)); } //------------------------------------------------------------------------- - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_getTransitions(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.getTransitions().size(), 0); + assertEquals(0, test.getTransitions().size()); } - @Test(expectedExceptions=UnsupportedOperationException.class) + @Test public void test_getTransitions_immutable() { - ZoneRules test = make(OFFSET_PTWO); - test.getTransitions().add(ZoneOffsetTransition.of(LDT, OFFSET_PONE, OFFSET_PTWO)); + Assertions.assertThrows(UnsupportedOperationException.class, () -> { + ZoneRules test = make(OFFSET_PTWO); + test.getTransitions().add(ZoneOffsetTransition.of(LDT, OFFSET_PONE, OFFSET_PTWO)); + }); } - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_getTransitionRules(ZoneRules test, ZoneOffset expectedOffset) { - assertEquals(test.getTransitionRules().size(), 0); + assertEquals(0, test.getTransitionRules().size()); } - @Test(expectedExceptions=UnsupportedOperationException.class) + @Test public void test_getTransitionRules_immutable() { - ZoneRules test = make(OFFSET_PTWO); - test.getTransitionRules().add(ZoneOffsetTransitionRule.of(Month.JULY, 2, null, LocalTime.of(12, 30), false, TimeDefinition.STANDARD, OFFSET_PONE, OFFSET_PTWO, OFFSET_PONE)); + Assertions.assertThrows(UnsupportedOperationException.class, () -> { + ZoneRules test = make(OFFSET_PTWO); + test.getTransitionRules().add(ZoneOffsetTransitionRule.of(Month.JULY, 2, null, LocalTime.of(12, 30), false, TimeDefinition.STANDARD, OFFSET_PONE, OFFSET_PTWO, OFFSET_PONE)); + }); } //----------------------------------------------------------------------- @@ -207,16 +225,16 @@ public class TCKFixedZoneRules { ZoneRules a = make(OFFSET_PONE); ZoneRules b = make(OFFSET_PTWO); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); - assertEquals(a.equals("Rubbish"), false); - assertEquals(a.equals(null), false); + assertEquals(false, a.equals("Rubbish")); + assertEquals(false, a.equals(null)); - assertEquals(a.hashCode() == a.hashCode(), true); - assertEquals(b.hashCode() == b.hashCode(), true); + assertEquals(true, a.hashCode() == a.hashCode()); + assertEquals(true, b.hashCode() == b.hashCode()); } } diff --git a/test/jdk/java/time/tck/java/time/zone/TCKZoneOffsetTransition.java b/test/jdk/java/time/tck/java/time/zone/TCKZoneOffsetTransition.java index 9cd42624bfa..241da3d0519 100644 --- a/test/jdk/java/time/tck/java/time/zone/TCKZoneOffsetTransition.java +++ b/test/jdk/java/time/tck/java/time/zone/TCKZoneOffsetTransition.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -60,7 +60,8 @@ package tck.java.time.zone; import static java.time.temporal.ChronoUnit.HOURS; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Duration; import java.time.LocalDateTime; @@ -68,13 +69,14 @@ import java.time.Year; import java.time.ZoneOffset; import java.time.zone.ZoneOffsetTransition; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import tck.java.time.AbstractTCKTest; /** * Test ZoneOffsetTransition. */ -@Test public class TCKZoneOffsetTransition extends AbstractTCKTest { private static final ZoneOffset OFFSET_0100 = ZoneOffset.ofHours(1); @@ -86,29 +88,29 @@ public class TCKZoneOffsetTransition extends AbstractTCKTest { //----------------------------------------------------------------------- // factory //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_nullTransition() { - ZoneOffsetTransition.of(null, OFFSET_0100, OFFSET_0200); + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffsetTransition.of(null, OFFSET_0100, OFFSET_0200)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_nullOffsetBefore() { - ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30), null, OFFSET_0200); + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30), null, OFFSET_0200)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_nullOffsetAfter() { - ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30), OFFSET_0200, null); + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30), OFFSET_0200, null)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_factory_sameOffset() { - ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30), OFFSET_0200, OFFSET_0200); + Assertions.assertThrows(IllegalArgumentException.class, () -> ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30), OFFSET_0200, OFFSET_0200)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_factory_noNanos() { - ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30, 0, 500), OFFSET_0200, OFFSET_0300); + Assertions.assertThrows(IllegalArgumentException.class, () -> ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30, 0, 500), OFFSET_0200, OFFSET_0300)); } //----------------------------------------------------------------------- @@ -119,14 +121,14 @@ public class TCKZoneOffsetTransition extends AbstractTCKTest { LocalDateTime before = LocalDateTime.of(2010, 3, 31, 1, 0); LocalDateTime after = LocalDateTime.of(2010, 3, 31, 2, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(before, OFFSET_0200, OFFSET_0300); - assertEquals(test.isGap(), true); - assertEquals(test.isOverlap(), false); - assertEquals(test.getDateTimeBefore(), before); - assertEquals(test.getDateTimeAfter(), after); - assertEquals(test.getInstant(), before.toInstant(OFFSET_0200)); - assertEquals(test.getOffsetBefore(), OFFSET_0200); - assertEquals(test.getOffsetAfter(), OFFSET_0300); - assertEquals(test.getDuration(), Duration.of(1, HOURS)); + assertEquals(true, test.isGap()); + assertEquals(false, test.isOverlap()); + assertEquals(before, test.getDateTimeBefore()); + assertEquals(after, test.getDateTimeAfter()); + assertEquals(before.toInstant(OFFSET_0200), test.getInstant()); + assertEquals(OFFSET_0200, test.getOffsetBefore()); + assertEquals(OFFSET_0300, test.getOffsetAfter()); + assertEquals(Duration.of(1, HOURS), test.getDuration()); } @Test @@ -134,14 +136,14 @@ public class TCKZoneOffsetTransition extends AbstractTCKTest { LocalDateTime before = LocalDateTime.of(2010, 10, 31, 1, 0); LocalDateTime after = LocalDateTime.of(2010, 10, 31, 0, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(before, OFFSET_0300, OFFSET_0200); - assertEquals(test.isGap(), false); - assertEquals(test.isOverlap(), true); - assertEquals(test.getDateTimeBefore(), before); - assertEquals(test.getDateTimeAfter(), after); - assertEquals(test.getInstant(), before.toInstant(OFFSET_0300)); - assertEquals(test.getOffsetBefore(), OFFSET_0300); - assertEquals(test.getOffsetAfter(), OFFSET_0200); - assertEquals(test.getDuration(), Duration.of(-1, HOURS)); + assertEquals(false, test.isGap()); + assertEquals(true, test.isOverlap()); + assertEquals(before, test.getDateTimeBefore()); + assertEquals(after, test.getDateTimeAfter()); + assertEquals(before.toInstant(OFFSET_0300), test.getInstant()); + assertEquals(OFFSET_0300, test.getOffsetBefore()); + assertEquals(OFFSET_0200, test.getOffsetAfter()); + assertEquals(Duration.of(-1, HOURS), test.getDuration()); } @@ -152,22 +154,22 @@ public class TCKZoneOffsetTransition extends AbstractTCKTest { public void test_isValidOffset_gap() { LocalDateTime ldt = LocalDateTime.of(2010, 3, 31, 1, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, OFFSET_0200, OFFSET_0300); - assertEquals(test.isValidOffset(OFFSET_0100), false); - assertEquals(test.isValidOffset(OFFSET_0200), false); - assertEquals(test.isValidOffset(OFFSET_0230), false); - assertEquals(test.isValidOffset(OFFSET_0300), false); - assertEquals(test.isValidOffset(OFFSET_0400), false); + assertEquals(false, test.isValidOffset(OFFSET_0100)); + assertEquals(false, test.isValidOffset(OFFSET_0200)); + assertEquals(false, test.isValidOffset(OFFSET_0230)); + assertEquals(false, test.isValidOffset(OFFSET_0300)); + assertEquals(false, test.isValidOffset(OFFSET_0400)); } @Test public void test_isValidOffset_overlap() { LocalDateTime ldt = LocalDateTime.of(2010, 10, 31, 1, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, OFFSET_0300, OFFSET_0200); - assertEquals(test.isValidOffset(OFFSET_0100), false); - assertEquals(test.isValidOffset(OFFSET_0200), true); - assertEquals(test.isValidOffset(OFFSET_0230), false); - assertEquals(test.isValidOffset(OFFSET_0300), true); - assertEquals(test.isValidOffset(OFFSET_0400), false); + assertEquals(false, test.isValidOffset(OFFSET_0100)); + assertEquals(true, test.isValidOffset(OFFSET_0200)); + assertEquals(false, test.isValidOffset(OFFSET_0230)); + assertEquals(true, test.isValidOffset(OFFSET_0300)); + assertEquals(false, test.isValidOffset(OFFSET_0400)); } //----------------------------------------------------------------------- @@ -182,17 +184,17 @@ public class TCKZoneOffsetTransition extends AbstractTCKTest { ZoneOffsetTransition c = ZoneOffsetTransition.of( LocalDateTime.ofEpochSecond(23875287L + 1, 0, OFFSET_0100), OFFSET_0100,OFFSET_0400); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(a.compareTo(b) < 0, true); - assertEquals(a.compareTo(c) < 0, true); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, a.compareTo(b) < 0); + assertEquals(true, a.compareTo(c) < 0); - assertEquals(b.compareTo(a) > 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(b.compareTo(c) < 0, true); + assertEquals(true, b.compareTo(a) > 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, b.compareTo(c) < 0); - assertEquals(c.compareTo(a) > 0, true); - assertEquals(c.compareTo(b) > 0, true); - assertEquals(c.compareTo(c) == 0, true); + assertEquals(true, c.compareTo(a) > 0); + assertEquals(true, c.compareTo(b) > 0); + assertEquals(true, c.compareTo(c) == 0); } @Test @@ -204,17 +206,17 @@ public class TCKZoneOffsetTransition extends AbstractTCKTest { ZoneOffsetTransition c = ZoneOffsetTransition.of( LocalDateTime.ofEpochSecond(23875287L, 0, OFFSET_0100), OFFSET_0100, OFFSET_0400); - assertEquals(a.compareTo(a) == 0, true); - assertEquals(a.compareTo(b) == 0, true); - assertEquals(a.compareTo(c) == 0, true); + assertEquals(true, a.compareTo(a) == 0); + assertEquals(true, a.compareTo(b) == 0); + assertEquals(true, a.compareTo(c) == 0); - assertEquals(b.compareTo(a) == 0, true); - assertEquals(b.compareTo(b) == 0, true); - assertEquals(b.compareTo(c) == 0, true); + assertEquals(true, b.compareTo(a) == 0); + assertEquals(true, b.compareTo(b) == 0); + assertEquals(true, b.compareTo(c) == 0); - assertEquals(c.compareTo(a) == 0, true); - assertEquals(c.compareTo(b) == 0, true); - assertEquals(c.compareTo(c) == 0, true); + assertEquals(true, c.compareTo(a) == 0); + assertEquals(true, c.compareTo(b) == 0); + assertEquals(true, c.compareTo(c) == 0); } //----------------------------------------------------------------------- @@ -228,18 +230,18 @@ public class TCKZoneOffsetTransition extends AbstractTCKTest { LocalDateTime ldtB = LocalDateTime.of(2010, 10, 31, 1, 0); ZoneOffsetTransition b = ZoneOffsetTransition.of(ldtB, OFFSET_0300, OFFSET_0200); - assertEquals(a1.equals(a1), true); - assertEquals(a1.equals(a2), true); - assertEquals(a1.equals(b), false); - assertEquals(a2.equals(a1), true); - assertEquals(a2.equals(a2), true); - assertEquals(a2.equals(b), false); - assertEquals(b.equals(a1), false); - assertEquals(b.equals(a2), false); - assertEquals(b.equals(b), true); + assertEquals(true, a1.equals(a1)); + assertEquals(true, a1.equals(a2)); + assertEquals(false, a1.equals(b)); + assertEquals(true, a2.equals(a1)); + assertEquals(true, a2.equals(a2)); + assertEquals(false, a2.equals(b)); + assertEquals(false, b.equals(a1)); + assertEquals(false, b.equals(a2)); + assertEquals(true, b.equals(b)); - assertEquals(a1.equals(""), false); - assertEquals(a1.equals(null), false); + assertEquals(false, a1.equals("")); + assertEquals(false, a1.equals(null)); } //----------------------------------------------------------------------- @@ -254,7 +256,7 @@ public class TCKZoneOffsetTransition extends AbstractTCKTest { ZoneOffsetTransition b = ZoneOffsetTransition.of(ldtB, OFFSET_0300, OFFSET_0200); assertEquals(a1.hashCode(), a1.hashCode()); - assertEquals(a1.hashCode(), a2.hashCode()); + assertEquals(a2.hashCode(), a1.hashCode()); assertEquals(b.hashCode(), b.hashCode()); } @@ -265,14 +267,14 @@ public class TCKZoneOffsetTransition extends AbstractTCKTest { public void test_toString_gap() { LocalDateTime ldt = LocalDateTime.of(2010, 3, 31, 1, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, OFFSET_0200, OFFSET_0300); - assertEquals(test.toString(), "Transition[Gap at 2010-03-31T01:00+02:00 to +03:00]"); + assertEquals("Transition[Gap at 2010-03-31T01:00+02:00 to +03:00]", test.toString()); } @Test public void test_toString_overlap() { LocalDateTime ldt = LocalDateTime.of(2010, 10, 31, 1, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, OFFSET_0300, OFFSET_0200); - assertEquals(test.toString(), "Transition[Overlap at 2010-10-31T01:00+03:00 to +02:00]"); + assertEquals("Transition[Overlap at 2010-10-31T01:00+03:00 to +02:00]", test.toString()); } } diff --git a/test/jdk/java/time/tck/java/time/zone/TCKZoneOffsetTransitionRule.java b/test/jdk/java/time/tck/java/time/zone/TCKZoneOffsetTransitionRule.java index 3c0c14c1ca6..e12251c6874 100644 --- a/test/jdk/java/time/tck/java/time/zone/TCKZoneOffsetTransitionRule.java +++ b/test/jdk/java/time/tck/java/time/zone/TCKZoneOffsetTransitionRule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,7 +59,7 @@ */ package tck.java.time.zone; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DayOfWeek; import java.time.LocalDateTime; @@ -70,13 +70,14 @@ import java.time.zone.ZoneOffsetTransition; import java.time.zone.ZoneOffsetTransitionRule; import java.time.zone.ZoneOffsetTransitionRule.TimeDefinition; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import tck.java.time.AbstractTCKTest; /** * Test ZoneOffsetTransitionRule. */ -@Test public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { private static final LocalTime TIME_0100 = LocalTime.of(1, 0); @@ -86,81 +87,81 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { //----------------------------------------------------------------------- // factory //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_nullMonth() { - ZoneOffsetTransitionRule.of( + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffsetTransitionRule.of( null, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, - OFFSET_0200, OFFSET_0200, OFFSET_0300); + OFFSET_0200, OFFSET_0200, OFFSET_0300)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_nullTime() { - ZoneOffsetTransitionRule.of( + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, null, false, TimeDefinition.WALL, - OFFSET_0200, OFFSET_0200, OFFSET_0300); + OFFSET_0200, OFFSET_0200, OFFSET_0300)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_nullTimeDefinition() { - ZoneOffsetTransitionRule.of( + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, null, - OFFSET_0200, OFFSET_0200, OFFSET_0300); + OFFSET_0200, OFFSET_0200, OFFSET_0300)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_nullStandardOffset() { - ZoneOffsetTransitionRule.of( + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, - null, OFFSET_0200, OFFSET_0300); + null, OFFSET_0200, OFFSET_0300)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_nullOffsetBefore() { - ZoneOffsetTransitionRule.of( + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, - OFFSET_0200, null, OFFSET_0300); + OFFSET_0200, null, OFFSET_0300)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_factory_nullOffsetAfter() { - ZoneOffsetTransitionRule.of( + Assertions.assertThrows(NullPointerException.class, () -> ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, - OFFSET_0200, OFFSET_0200, null); + OFFSET_0200, OFFSET_0200, null)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_factory_invalidDayOfMonthIndicator_tooSmall() { - ZoneOffsetTransitionRule.of( + Assertions.assertThrows(IllegalArgumentException.class, () -> ZoneOffsetTransitionRule.of( Month.MARCH, -29, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, - OFFSET_0200, OFFSET_0200, OFFSET_0300); + OFFSET_0200, OFFSET_0200, OFFSET_0300)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_factory_invalidDayOfMonthIndicator_zero() { - ZoneOffsetTransitionRule.of( + Assertions.assertThrows(IllegalArgumentException.class, () -> ZoneOffsetTransitionRule.of( Month.MARCH, 0, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, - OFFSET_0200, OFFSET_0200, OFFSET_0300); + OFFSET_0200, OFFSET_0200, OFFSET_0300)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_factory_invalidDayOfMonthIndicator_tooLarge() { - ZoneOffsetTransitionRule.of( + Assertions.assertThrows(IllegalArgumentException.class, () -> ZoneOffsetTransitionRule.of( Month.MARCH, 32, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, - OFFSET_0200, OFFSET_0200, OFFSET_0300); + OFFSET_0200, OFFSET_0200, OFFSET_0300)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_factory_invalidMidnightFlag() { - ZoneOffsetTransitionRule.of( + Assertions.assertThrows(IllegalArgumentException.class, () -> ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, true, TimeDefinition.WALL, - OFFSET_0200, OFFSET_0200, OFFSET_0300); + OFFSET_0200, OFFSET_0200, OFFSET_0300)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_factory_nonZeroTimeNanos() { - ZoneOffsetTransitionRule.of( - Month.MARCH, 20, DayOfWeek.SUNDAY, LocalTime.of(1, 2, 3, 400_000_000), - false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); + Assertions.assertThrows(IllegalArgumentException.class, () -> ZoneOffsetTransitionRule.of( + Month.MARCH, 20, DayOfWeek.SUNDAY, LocalTime.of(1, 2, 3, 400_000_000), + false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300)); } //----------------------------------------------------------------------- @@ -171,15 +172,15 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(test.getMonth(), Month.MARCH); - assertEquals(test.getDayOfMonthIndicator(), 20); - assertEquals(test.getDayOfWeek(), DayOfWeek.SUNDAY); - assertEquals(test.getLocalTime(), TIME_0100); - assertEquals(test.isMidnightEndOfDay(), false); - assertEquals(test.getTimeDefinition(), TimeDefinition.WALL); - assertEquals(test.getStandardOffset(), OFFSET_0200); - assertEquals(test.getOffsetBefore(), OFFSET_0200); - assertEquals(test.getOffsetAfter(), OFFSET_0300); + assertEquals(Month.MARCH, test.getMonth()); + assertEquals(20, test.getDayOfMonthIndicator()); + assertEquals(DayOfWeek.SUNDAY, test.getDayOfWeek()); + assertEquals(TIME_0100, test.getLocalTime()); + assertEquals(false, test.isMidnightEndOfDay()); + assertEquals(TimeDefinition.WALL, test.getTimeDefinition()); + assertEquals(OFFSET_0200, test.getStandardOffset()); + assertEquals(OFFSET_0200, test.getOffsetBefore()); + assertEquals(OFFSET_0300, test.getOffsetAfter()); } @Test @@ -187,15 +188,15 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of( Month.MARCH, -1, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(test.getMonth(), Month.MARCH); - assertEquals(test.getDayOfMonthIndicator(), -1); - assertEquals(test.getDayOfWeek(), DayOfWeek.SUNDAY); - assertEquals(test.getLocalTime(), TIME_0100); - assertEquals(test.isMidnightEndOfDay(), false); - assertEquals(test.getTimeDefinition(), TimeDefinition.WALL); - assertEquals(test.getStandardOffset(), OFFSET_0200); - assertEquals(test.getOffsetBefore(), OFFSET_0200); - assertEquals(test.getOffsetAfter(), OFFSET_0300); + assertEquals(Month.MARCH, test.getMonth()); + assertEquals(-1, test.getDayOfMonthIndicator()); + assertEquals(DayOfWeek.SUNDAY, test.getDayOfWeek()); + assertEquals(TIME_0100, test.getLocalTime()); + assertEquals(false, test.isMidnightEndOfDay()); + assertEquals(TimeDefinition.WALL, test.getTimeDefinition()); + assertEquals(OFFSET_0200, test.getStandardOffset()); + assertEquals(OFFSET_0200, test.getOffsetBefore()); + assertEquals(OFFSET_0300, test.getOffsetAfter()); } @Test @@ -203,15 +204,15 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of( Month.MARCH, 20, null, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(test.getMonth(), Month.MARCH); - assertEquals(test.getDayOfMonthIndicator(), 20); - assertEquals(test.getDayOfWeek(), null); - assertEquals(test.getLocalTime(), TIME_0100); - assertEquals(test.isMidnightEndOfDay(), false); - assertEquals(test.getTimeDefinition(), TimeDefinition.WALL); - assertEquals(test.getStandardOffset(), OFFSET_0200); - assertEquals(test.getOffsetBefore(), OFFSET_0200); - assertEquals(test.getOffsetAfter(), OFFSET_0300); + assertEquals(Month.MARCH, test.getMonth()); + assertEquals(20, test.getDayOfMonthIndicator()); + assertEquals(null, test.getDayOfWeek()); + assertEquals(TIME_0100, test.getLocalTime()); + assertEquals(false, test.isMidnightEndOfDay()); + assertEquals(TimeDefinition.WALL, test.getTimeDefinition()); + assertEquals(OFFSET_0200, test.getStandardOffset()); + assertEquals(OFFSET_0200, test.getOffsetBefore()); + assertEquals(OFFSET_0300, test.getOffsetAfter()); } @@ -225,7 +226,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { OFFSET_0200, OFFSET_0200, OFFSET_0300); ZoneOffsetTransition trans = ZoneOffsetTransition.of( LocalDateTime.of(2000, Month.MARCH, 26, 1, 0), OFFSET_0200, OFFSET_0300); - assertEquals(test.createTransition(2000), trans); + assertEquals(trans, test.createTransition(2000)); } @Test @@ -235,7 +236,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { OFFSET_0200, OFFSET_0300, OFFSET_0200); ZoneOffsetTransition trans = ZoneOffsetTransition.of( LocalDateTime.of(2000, Month.MARCH, 27, 0, 0), OFFSET_0300, OFFSET_0200); - assertEquals(test.createTransition(2000), trans); + assertEquals(trans, test.createTransition(2000)); } @Test @@ -245,7 +246,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { OFFSET_0200, OFFSET_0200, OFFSET_0300); ZoneOffsetTransition trans = ZoneOffsetTransition.of( LocalDateTime.of(2000, Month.MARCH, 26, 1, 0), OFFSET_0200, OFFSET_0300); - assertEquals(test.createTransition(2000), trans); + assertEquals(trans, test.createTransition(2000)); } @Test @@ -255,7 +256,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { OFFSET_0200, OFFSET_0200, OFFSET_0300); ZoneOffsetTransition trans = ZoneOffsetTransition.of( LocalDateTime.of(2000, Month.MARCH, 19, 1, 0), OFFSET_0200, OFFSET_0300); - assertEquals(test.createTransition(2000), trans); + assertEquals(trans, test.createTransition(2000)); } @Test @@ -265,7 +266,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { OFFSET_0200, OFFSET_0200, OFFSET_0300); ZoneOffsetTransition trans = ZoneOffsetTransition.of( LocalDateTime.of(2000, Month.MARCH, 26, 1, 0), OFFSET_0200, OFFSET_0300); - assertEquals(test.createTransition(2000), trans); + assertEquals(trans, test.createTransition(2000)); } @Test @@ -275,7 +276,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { OFFSET_0200, OFFSET_0200, OFFSET_0300); ZoneOffsetTransition trans = ZoneOffsetTransition.of( LocalDateTime.of(2000, Month.MARCH, 20, 1, 0), OFFSET_0200, OFFSET_0300); - assertEquals(test.createTransition(2000), trans); + assertEquals(trans, test.createTransition(2000)); } //----------------------------------------------------------------------- @@ -289,10 +290,10 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.APRIL, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); } @Test @@ -303,10 +304,10 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 21, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); } @Test @@ -317,10 +318,10 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SATURDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); } @Test @@ -331,10 +332,10 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 20, null, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); } @Test @@ -345,10 +346,10 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, LocalTime.MIDNIGHT, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); } @Test @@ -359,10 +360,10 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, LocalTime.MIDNIGHT, true, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); } @Test @@ -373,10 +374,10 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.STANDARD, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); } @Test @@ -387,10 +388,10 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0300, OFFSET_0200, OFFSET_0300); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); } @Test @@ -401,10 +402,10 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0300, OFFSET_0300); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); } @Test @@ -415,10 +416,10 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0200); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), false); - assertEquals(b.equals(a), false); - assertEquals(b.equals(b), true); + assertEquals(true, a.equals(a)); + assertEquals(false, a.equals(b)); + assertEquals(false, b.equals(a)); + assertEquals(true, b.equals(b)); } @Test @@ -426,7 +427,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule a = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.equals("TZDB"), false); + assertEquals(false, a.equals("TZDB")); } @Test @@ -434,7 +435,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule a = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.equals(null), false); + assertEquals(false, a.equals(null)); } //----------------------------------------------------------------------- @@ -448,7 +449,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); } @Test @@ -459,7 +460,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.OCTOBER, 20, null, LocalTime.MIDNIGHT, true, TimeDefinition.WALL, OFFSET_0200, OFFSET_0300, OFFSET_0200); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); } @Test @@ -470,7 +471,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, -1, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); } @Test @@ -481,7 +482,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule b = ZoneOffsetTransitionRule.of( Month.MARCH, 20, null, TIME_0100, false, TimeDefinition.STANDARD, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(a.hashCode(), b.hashCode()); + assertEquals(b.hashCode(), a.hashCode()); } //----------------------------------------------------------------------- @@ -492,7 +493,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of( Month.MARCH, 20, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(test.toString(), "TransitionRule[Gap +02:00 to +03:00, SUNDAY on or after MARCH 20 at 01:00 WALL, standard offset +02:00]"); + assertEquals("TransitionRule[Gap +02:00 to +03:00, SUNDAY on or after MARCH 20 at 01:00 WALL, standard offset +02:00]", test.toString()); } @Test @@ -500,7 +501,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of( Month.OCTOBER, 20, DayOfWeek.SUNDAY, LocalTime.MIDNIGHT, true, TimeDefinition.WALL, OFFSET_0200, OFFSET_0300, OFFSET_0200); - assertEquals(test.toString(), "TransitionRule[Overlap +03:00 to +02:00, SUNDAY on or after OCTOBER 20 at 24:00 WALL, standard offset +02:00]"); + assertEquals("TransitionRule[Overlap +03:00 to +02:00, SUNDAY on or after OCTOBER 20 at 24:00 WALL, standard offset +02:00]", test.toString()); } @Test @@ -508,7 +509,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of( Month.MARCH, -1, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(test.toString(), "TransitionRule[Gap +02:00 to +03:00, SUNDAY on or before last day of MARCH at 01:00 WALL, standard offset +02:00]"); + assertEquals("TransitionRule[Gap +02:00 to +03:00, SUNDAY on or before last day of MARCH at 01:00 WALL, standard offset +02:00]", test.toString()); } @Test @@ -516,7 +517,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of( Month.MARCH, -2, DayOfWeek.SUNDAY, TIME_0100, false, TimeDefinition.WALL, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(test.toString(), "TransitionRule[Gap +02:00 to +03:00, SUNDAY on or before last day minus 1 of MARCH at 01:00 WALL, standard offset +02:00]"); + assertEquals("TransitionRule[Gap +02:00 to +03:00, SUNDAY on or before last day minus 1 of MARCH at 01:00 WALL, standard offset +02:00]", test.toString()); } @Test @@ -524,7 +525,7 @@ public class TCKZoneOffsetTransitionRule extends AbstractTCKTest { ZoneOffsetTransitionRule test = ZoneOffsetTransitionRule.of( Month.MARCH, 20, null, TIME_0100, false, TimeDefinition.STANDARD, OFFSET_0200, OFFSET_0200, OFFSET_0300); - assertEquals(test.toString(), "TransitionRule[Gap +02:00 to +03:00, MARCH 20 at 01:00 STANDARD, standard offset +02:00]"); + assertEquals("TransitionRule[Gap +02:00 to +03:00, MARCH 20 at 01:00 STANDARD, standard offset +02:00]", test.toString()); } } diff --git a/test/jdk/java/time/tck/java/time/zone/TCKZoneRules.java b/test/jdk/java/time/tck/java/time/zone/TCKZoneRules.java index d44216b69b5..265555a1792 100644 --- a/test/jdk/java/time/tck/java/time/zone/TCKZoneRules.java +++ b/test/jdk/java/time/tck/java/time/zone/TCKZoneRules.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,10 +59,10 @@ */ package tck.java.time.zone; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -88,12 +88,12 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Test ZoneRules. */ -@Test public class TCKZoneRules { private static final ZoneOffset OFFSET_ZERO = ZoneOffset.ofHours(0); @@ -115,7 +115,7 @@ public class TCKZoneRules { @Test public void test_London() { ZoneRules test = europeLondon(); - assertEquals(test.isFixedOffset(), false); + assertEquals(false, test.isFixedOffset()); } @Test @@ -124,60 +124,60 @@ public class TCKZoneRules { ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC); Instant instant = old.toInstant(); ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, -1, -15); - assertEquals(test.getOffset(instant), offset); + assertEquals(offset, test.getOffset(instant)); checkOffset(test, old.toLocalDateTime(), offset, 1); - assertEquals(test.getStandardOffset(instant), offset); - assertEquals(test.getDaylightSavings(instant), Duration.ZERO); - assertEquals(test.isDaylightSavings(instant), false); + assertEquals(offset, test.getStandardOffset(instant)); + assertEquals(Duration.ZERO, test.getDaylightSavings(instant)); + assertEquals(false, test.isDaylightSavings(instant)); } @Test public void test_London_getOffset() { ZoneRules test = europeLondon(); - assertEquals(test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), OFFSET_ZERO); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC))); } @Test public void test_London_getOffset_toDST() { ZoneRules test = europeLondon(); - assertEquals(test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), OFFSET_PONE); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC))); // cutover at 01:00Z - assertEquals(test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PONE); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC))); } @Test public void test_London_getOffset_fromDST() { ZoneRules test = europeLondon(); - assertEquals(test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), OFFSET_ZERO); - assertEquals(test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), OFFSET_ZERO); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC))); // cutover at 01:00Z - assertEquals(test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_ZERO); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC))); + assertEquals(OFFSET_ZERO, test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC))); } @Test @@ -234,17 +234,17 @@ public class TCKZoneRules { ZoneRules test = europeLondon(); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_ZERO, GAP); - assertEquals(trans.isGap(), true); - assertEquals(trans.isOverlap(), false); - assertEquals(trans.getOffsetBefore(), OFFSET_ZERO); - assertEquals(trans.getOffsetAfter(), OFFSET_PONE); - assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC)); - assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 3, 30, 1, 0)); - assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 3, 30, 2, 0)); - assertEquals(trans.isValidOffset(OFFSET_ZERO), false); - assertEquals(trans.isValidOffset(OFFSET_PONE), false); - assertEquals(trans.isValidOffset(OFFSET_PTWO), false); - assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T01:00Z to +01:00]"); + assertEquals(true, trans.isGap()); + assertEquals(false, trans.isOverlap()); + assertEquals(OFFSET_ZERO, trans.getOffsetBefore()); + assertEquals(OFFSET_PONE, trans.getOffsetAfter()); + assertEquals(createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC), trans.getInstant()); + assertEquals(LocalDateTime.of(2008, 3, 30, 1, 0), trans.getDateTimeBefore()); + assertEquals(LocalDateTime.of(2008, 3, 30, 2, 0), trans.getDateTimeAfter()); + assertEquals(false, trans.isValidOffset(OFFSET_ZERO)); + assertEquals(false, trans.isValidOffset(OFFSET_PONE)); + assertEquals(false, trans.isValidOffset(OFFSET_PTWO)); + assertEquals("Transition[Gap at 2008-03-30T01:00Z to +01:00]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_ZERO)); @@ -252,7 +252,7 @@ public class TCKZoneRules { final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); - assertEquals(trans.hashCode(), otherTrans.hashCode()); + assertEquals(otherTrans.hashCode(), trans.hashCode()); } @Test @@ -260,18 +260,18 @@ public class TCKZoneRules { ZoneRules test = europeLondon(); final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, OVERLAP); - assertEquals(trans.isGap(), false); - assertEquals(trans.isOverlap(), true); - assertEquals(trans.getOffsetBefore(), OFFSET_PONE); - assertEquals(trans.getOffsetAfter(), OFFSET_ZERO); - assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC)); - assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 10, 26, 2, 0)); - assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 10, 26, 1, 0)); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false); - assertEquals(trans.isValidOffset(OFFSET_ZERO), true); - assertEquals(trans.isValidOffset(OFFSET_PONE), true); - assertEquals(trans.isValidOffset(OFFSET_PTWO), false); - assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T02:00+01:00 to Z]"); + assertEquals(false, trans.isGap()); + assertEquals(true, trans.isOverlap()); + assertEquals(OFFSET_PONE, trans.getOffsetBefore()); + assertEquals(OFFSET_ZERO, trans.getOffsetAfter()); + assertEquals(createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC), trans.getInstant()); + assertEquals(LocalDateTime.of(2008, 10, 26, 2, 0), trans.getDateTimeBefore()); + assertEquals(LocalDateTime.of(2008, 10, 26, 1, 0), trans.getDateTimeAfter()); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-1))); + assertEquals(true, trans.isValidOffset(OFFSET_ZERO)); + assertEquals(true, trans.isValidOffset(OFFSET_PONE)); + assertEquals(false, trans.isValidOffset(OFFSET_PTWO)); + assertEquals("Transition[Overlap at 2008-10-26T02:00+01:00 to Z]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_PONE)); @@ -279,7 +279,7 @@ public class TCKZoneRules { final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); - assertEquals(trans.hashCode(), otherTrans.hashCode()); + assertEquals(otherTrans.hashCode(), trans.hashCode()); } @Test @@ -289,11 +289,11 @@ public class TCKZoneRules { while (zdt.getYear() < 2010) { Instant instant = zdt.toInstant(); if (zdt.getYear() < 1848) { - assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, -1, -15)); + assertEquals(ZoneOffset.ofHoursMinutesSeconds(0, -1, -15), test.getStandardOffset(instant)); } else if (zdt.getYear() >= 1969 && zdt.getYear() < 1972) { - assertEquals(test.getStandardOffset(instant), OFFSET_PONE); + assertEquals(OFFSET_PONE, test.getStandardOffset(instant)); } else { - assertEquals(test.getStandardOffset(instant), OFFSET_ZERO); + assertEquals(OFFSET_ZERO, test.getStandardOffset(instant)); } zdt = zdt.plusMonths(6); } @@ -305,19 +305,19 @@ public class TCKZoneRules { List trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); - assertEquals(first.getDateTimeBefore(), LocalDateTime.of(1847, 12, 1, 0, 0)); - assertEquals(first.getOffsetBefore(), ZoneOffset.ofHoursMinutesSeconds(0, -1, -15)); - assertEquals(first.getOffsetAfter(), OFFSET_ZERO); + assertEquals(LocalDateTime.of(1847, 12, 1, 0, 0), first.getDateTimeBefore()); + assertEquals(ZoneOffset.ofHoursMinutesSeconds(0, -1, -15), first.getOffsetBefore()); + assertEquals(OFFSET_ZERO, first.getOffsetAfter()); ZoneOffsetTransition spring1916 = trans.get(1); - assertEquals(spring1916.getDateTimeBefore(), LocalDateTime.of(1916, 5, 21, 2, 0)); - assertEquals(spring1916.getOffsetBefore(), OFFSET_ZERO); - assertEquals(spring1916.getOffsetAfter(), OFFSET_PONE); + assertEquals(LocalDateTime.of(1916, 5, 21, 2, 0), spring1916.getDateTimeBefore()); + assertEquals(OFFSET_ZERO, spring1916.getOffsetBefore()); + assertEquals(OFFSET_PONE, spring1916.getOffsetAfter()); ZoneOffsetTransition autumn1916 = trans.get(2); - assertEquals(autumn1916.getDateTimeBefore(), LocalDateTime.of(1916, 10, 1, 3, 0)); - assertEquals(autumn1916.getOffsetBefore(), OFFSET_PONE); - assertEquals(autumn1916.getOffsetAfter(), OFFSET_ZERO); + assertEquals(LocalDateTime.of(1916, 10, 1, 3, 0), autumn1916.getDateTimeBefore()); + assertEquals(OFFSET_PONE, autumn1916.getOffsetBefore()); + assertEquals(OFFSET_ZERO, autumn1916.getOffsetAfter()); ZoneOffsetTransition zot = null; Iterator it = trans.iterator(); @@ -327,81 +327,81 @@ public class TCKZoneRules { break; } } - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1990, 3, 25, 1, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); + assertEquals(LocalDateTime.of(1990, 3, 25, 1, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_ZERO, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1990, 10, 28, 2, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_PONE); + assertEquals(LocalDateTime.of(1990, 10, 28, 2, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_PONE, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1991, 3, 31, 1, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); + assertEquals(LocalDateTime.of(1991, 3, 31, 1, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_ZERO, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1991, 10, 27, 2, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_PONE); + assertEquals(LocalDateTime.of(1991, 10, 27, 2, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_PONE, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1992, 3, 29, 1, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); + assertEquals(LocalDateTime.of(1992, 3, 29, 1, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_ZERO, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1992, 10, 25, 2, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_PONE); + assertEquals(LocalDateTime.of(1992, 10, 25, 2, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_PONE, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1993, 3, 28, 1, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); + assertEquals(LocalDateTime.of(1993, 3, 28, 1, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_ZERO, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1993, 10, 24, 2, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_PONE); + assertEquals(LocalDateTime.of(1993, 10, 24, 2, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_PONE, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1994, 3, 27, 1, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); + assertEquals(LocalDateTime.of(1994, 3, 27, 1, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_ZERO, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1994, 10, 23, 2, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_PONE); + assertEquals(LocalDateTime.of(1994, 10, 23, 2, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_PONE, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1995, 3, 26, 1, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); + assertEquals(LocalDateTime.of(1995, 3, 26, 1, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_ZERO, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1995, 10, 22, 2, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_PONE); + assertEquals(LocalDateTime.of(1995, 10, 22, 2, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_PONE, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1996, 3, 31, 1, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); + assertEquals(LocalDateTime.of(1996, 3, 31, 1, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_ZERO, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1996, 10, 27, 2, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_PONE); + assertEquals(LocalDateTime.of(1996, 10, 27, 2, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_PONE, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1997, 3, 30, 1, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); + assertEquals(LocalDateTime.of(1997, 3, 30, 1, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_ZERO, zot.getOffsetBefore()); zot = it.next(); - assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1997, 10, 26, 2, 0)); - assertEquals(zot.getOffsetBefore(), OFFSET_PONE); - assertEquals(it.hasNext(), false); + assertEquals(LocalDateTime.of(1997, 10, 26, 2, 0), zot.getDateTimeBefore()); + assertEquals(OFFSET_PONE, zot.getOffsetBefore()); + assertEquals(false, it.hasNext()); } @Test public void test_London_getTransitionRules() { ZoneRules test = europeLondon(); List rules = test.getTransitionRules(); - assertEquals(rules.size(), 2); + assertEquals(2, rules.size()); ZoneOffsetTransitionRule in = rules.get(0); - assertEquals(in.getMonth(), Month.MARCH); - assertEquals(in.getDayOfMonthIndicator(), 25); // optimized from -1 - assertEquals(in.getDayOfWeek(), DayOfWeek.SUNDAY); - assertEquals(in.getLocalTime(), LocalTime.of(1, 0)); - assertEquals(in.getTimeDefinition(), TimeDefinition.UTC); - assertEquals(in.getStandardOffset(), OFFSET_ZERO); - assertEquals(in.getOffsetBefore(), OFFSET_ZERO); - assertEquals(in.getOffsetAfter(), OFFSET_PONE); + assertEquals(Month.MARCH, in.getMonth()); + assertEquals(25, in.getDayOfMonthIndicator()); // optimized from -1 + assertEquals(DayOfWeek.SUNDAY, in.getDayOfWeek()); + assertEquals(LocalTime.of(1, 0), in.getLocalTime()); + assertEquals(TimeDefinition.UTC, in.getTimeDefinition()); + assertEquals(OFFSET_ZERO, in.getStandardOffset()); + assertEquals(OFFSET_ZERO, in.getOffsetBefore()); + assertEquals(OFFSET_PONE, in.getOffsetAfter()); ZoneOffsetTransitionRule out = rules.get(1); - assertEquals(out.getMonth(), Month.OCTOBER); - assertEquals(out.getDayOfMonthIndicator(), 25); // optimized from -1 - assertEquals(out.getDayOfWeek(), DayOfWeek.SUNDAY); - assertEquals(out.getLocalTime(), LocalTime.of(1, 0)); - assertEquals(out.getTimeDefinition(), TimeDefinition.UTC); - assertEquals(out.getStandardOffset(), OFFSET_ZERO); - assertEquals(out.getOffsetBefore(), OFFSET_PONE); - assertEquals(out.getOffsetAfter(), OFFSET_ZERO); + assertEquals(Month.OCTOBER, out.getMonth()); + assertEquals(25, out.getDayOfMonthIndicator()); // optimized from -1 + assertEquals(DayOfWeek.SUNDAY, out.getDayOfWeek()); + assertEquals(LocalTime.of(1, 0), out.getLocalTime()); + assertEquals(TimeDefinition.UTC, out.getTimeDefinition()); + assertEquals(OFFSET_ZERO, out.getStandardOffset()); + assertEquals(OFFSET_PONE, out.getOffsetBefore()); + assertEquals(OFFSET_ZERO, out.getOffsetAfter()); } //----------------------------------------------------------------------- @@ -411,14 +411,14 @@ public class TCKZoneRules { List trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); - assertEquals(test.nextTransition(first.getInstant().minusNanos(1)), first); + assertEquals(first, test.nextTransition(first.getInstant().minusNanos(1))); for (int i = 0; i < trans.size() - 1; i++) { ZoneOffsetTransition cur = trans.get(i); ZoneOffsetTransition next = trans.get(i + 1); - assertEquals(test.nextTransition(cur.getInstant()), next); - assertEquals(test.nextTransition(next.getInstant().minusNanos(1)), next); + assertEquals(next, test.nextTransition(cur.getInstant())); + assertEquals(next, test.nextTransition(next.getInstant().minusNanos(1))); } } @@ -429,18 +429,18 @@ public class TCKZoneRules { List trans = test.getTransitions(); ZoneOffsetTransition last = trans.get(trans.size() - 1); - assertEquals(test.nextTransition(last.getInstant()), rules.get(0).createTransition(1998)); + assertEquals(rules.get(0).createTransition(1998), test.nextTransition(last.getInstant())); for (int year = 1998; year < 2010; year++) { ZoneOffsetTransition a = rules.get(0).createTransition(year); ZoneOffsetTransition b = rules.get(1).createTransition(year); ZoneOffsetTransition c = rules.get(0).createTransition(year + 1); - assertEquals(test.nextTransition(a.getInstant()), b); - assertEquals(test.nextTransition(b.getInstant().minusNanos(1)), b); + assertEquals(b, test.nextTransition(a.getInstant())); + assertEquals(b, test.nextTransition(b.getInstant().minusNanos(1))); - assertEquals(test.nextTransition(b.getInstant()), c); - assertEquals(test.nextTransition(c.getInstant().minusNanos(1)), c); + assertEquals(c, test.nextTransition(b.getInstant())); + assertEquals(c, test.nextTransition(c.getInstant().minusNanos(1))); } } @@ -449,7 +449,7 @@ public class TCKZoneRules { ZoneRules test = europeLondon(); List rules = test.getTransitionRules(); ZoneOffsetTransition zot = rules.get(1).createTransition(Year.MAX_VALUE); - assertEquals(test.nextTransition(zot.getInstant()), null); + assertEquals(null, test.nextTransition(zot.getInstant())); } //----------------------------------------------------------------------- @@ -459,16 +459,16 @@ public class TCKZoneRules { List trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); - assertEquals(test.previousTransition(first.getInstant()), null); - assertEquals(test.previousTransition(first.getInstant().minusNanos(1)), null); + assertEquals(null, test.previousTransition(first.getInstant())); + assertEquals(null, test.previousTransition(first.getInstant().minusNanos(1))); for (int i = 0; i < trans.size() - 1; i++) { ZoneOffsetTransition prev = trans.get(i); ZoneOffsetTransition cur = trans.get(i + 1); - assertEquals(test.previousTransition(cur.getInstant()), prev); - assertEquals(test.previousTransition(prev.getInstant().plusSeconds(1)), prev); - assertEquals(test.previousTransition(prev.getInstant().plusNanos(1)), prev); + assertEquals(prev, test.previousTransition(cur.getInstant())); + assertEquals(prev, test.previousTransition(prev.getInstant().plusSeconds(1))); + assertEquals(prev, test.previousTransition(prev.getInstant().plusNanos(1))); } } @@ -479,13 +479,13 @@ public class TCKZoneRules { List trans = test.getTransitions(); ZoneOffsetTransition last = trans.get(trans.size() - 1); - assertEquals(test.previousTransition(last.getInstant().plusSeconds(1)), last); - assertEquals(test.previousTransition(last.getInstant().plusNanos(1)), last); + assertEquals(last, test.previousTransition(last.getInstant().plusSeconds(1))); + assertEquals(last, test.previousTransition(last.getInstant().plusNanos(1))); // Jan 1st of year between transitions and rules ZonedDateTime odt = ZonedDateTime.ofInstant(last.getInstant(), last.getOffsetAfter()); odt = odt.withDayOfYear(1).plusYears(1).with(LocalTime.MIDNIGHT); - assertEquals(test.previousTransition(odt.toInstant()), last); + assertEquals(last, test.previousTransition(odt.toInstant())); // later years for (int year = 1998; year < 2010; year++) { @@ -493,13 +493,13 @@ public class TCKZoneRules { ZoneOffsetTransition b = rules.get(1).createTransition(year); ZoneOffsetTransition c = rules.get(0).createTransition(year + 1); - assertEquals(test.previousTransition(c.getInstant()), b); - assertEquals(test.previousTransition(b.getInstant().plusSeconds(1)), b); - assertEquals(test.previousTransition(b.getInstant().plusNanos(1)), b); + assertEquals(b, test.previousTransition(c.getInstant())); + assertEquals(b, test.previousTransition(b.getInstant().plusSeconds(1))); + assertEquals(b, test.previousTransition(b.getInstant().plusNanos(1))); - assertEquals(test.previousTransition(b.getInstant()), a); - assertEquals(test.previousTransition(a.getInstant().plusSeconds(1)), a); - assertEquals(test.previousTransition(a.getInstant().plusNanos(1)), a); + assertEquals(a, test.previousTransition(b.getInstant())); + assertEquals(a, test.previousTransition(a.getInstant().plusSeconds(1))); + assertEquals(a, test.previousTransition(a.getInstant().plusNanos(1))); } } @@ -513,7 +513,7 @@ public class TCKZoneRules { @Test public void test_Paris() { ZoneRules test = europeParis(); - assertEquals(test.isFixedOffset(), false); + assertEquals(false, test.isFixedOffset()); } @Test @@ -522,60 +522,60 @@ public class TCKZoneRules { ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC); Instant instant = old.toInstant(); ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, 9, 21); - assertEquals(test.getOffset(instant), offset); + assertEquals(offset, test.getOffset(instant)); checkOffset(test, old.toLocalDateTime(), offset, 1); - assertEquals(test.getStandardOffset(instant), offset); - assertEquals(test.getDaylightSavings(instant), Duration.ZERO); - assertEquals(test.isDaylightSavings(instant), false); + assertEquals(offset, test.getStandardOffset(instant)); + assertEquals(Duration.ZERO, test.getDaylightSavings(instant)); + assertEquals(false, test.isDaylightSavings(instant)); } @Test public void test_Paris_getOffset() { ZoneRules test = europeParis(); - assertEquals(test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), OFFSET_PONE); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC))); } @Test public void test_Paris_getOffset_toDST() { ZoneRules test = europeParis(); - assertEquals(test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), OFFSET_PTWO); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC))); // cutover at 01:00Z - assertEquals(test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PTWO); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC))); } @Test public void test_Paris_getOffset_fromDST() { ZoneRules test = europeParis(); - assertEquals(test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), OFFSET_PONE); - assertEquals(test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), OFFSET_PONE); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC))); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC))); // cutover at 01:00Z - assertEquals(test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PTWO); - assertEquals(test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PONE); + assertEquals(OFFSET_PTWO, test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC))); + assertEquals(OFFSET_PONE, test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC))); } @Test @@ -632,15 +632,15 @@ public class TCKZoneRules { ZoneRules test = europeParis(); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, GAP); - assertEquals(trans.isGap(), true); - assertEquals(trans.isOverlap(), false); - assertEquals(trans.getOffsetBefore(), OFFSET_PONE); - assertEquals(trans.getOffsetAfter(), OFFSET_PTWO); - assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC)); - assertEquals(trans.isValidOffset(OFFSET_ZERO), false); - assertEquals(trans.isValidOffset(OFFSET_PONE), false); - assertEquals(trans.isValidOffset(OFFSET_PTWO), false); - assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T02:00+01:00 to +02:00]"); + assertEquals(true, trans.isGap()); + assertEquals(false, trans.isOverlap()); + assertEquals(OFFSET_PONE, trans.getOffsetBefore()); + assertEquals(OFFSET_PTWO, trans.getOffsetAfter()); + assertEquals(createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC), trans.getInstant()); + assertEquals(false, trans.isValidOffset(OFFSET_ZERO)); + assertEquals(false, trans.isValidOffset(OFFSET_PONE)); + assertEquals(false, trans.isValidOffset(OFFSET_PTWO)); + assertEquals("Transition[Gap at 2008-03-30T02:00+01:00 to +02:00]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_PONE)); @@ -648,7 +648,7 @@ public class TCKZoneRules { final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); - assertEquals(trans.hashCode(), otherTrans.hashCode()); + assertEquals(otherTrans.hashCode(), trans.hashCode()); } @Test @@ -656,16 +656,16 @@ public class TCKZoneRules { ZoneRules test = europeParis(); final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PTWO, OVERLAP); - assertEquals(trans.isGap(), false); - assertEquals(trans.isOverlap(), true); - assertEquals(trans.getOffsetBefore(), OFFSET_PTWO); - assertEquals(trans.getOffsetAfter(), OFFSET_PONE); - assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC)); - assertEquals(trans.isValidOffset(OFFSET_ZERO), false); - assertEquals(trans.isValidOffset(OFFSET_PONE), true); - assertEquals(trans.isValidOffset(OFFSET_PTWO), true); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(3)), false); - assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T03:00+02:00 to +01:00]"); + assertEquals(false, trans.isGap()); + assertEquals(true, trans.isOverlap()); + assertEquals(OFFSET_PTWO, trans.getOffsetBefore()); + assertEquals(OFFSET_PONE, trans.getOffsetAfter()); + assertEquals(createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC), trans.getInstant()); + assertEquals(false, trans.isValidOffset(OFFSET_ZERO)); + assertEquals(true, trans.isValidOffset(OFFSET_PONE)); + assertEquals(true, trans.isValidOffset(OFFSET_PTWO)); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(3))); + assertEquals("Transition[Overlap at 2008-10-26T03:00+02:00 to +01:00]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_PTWO)); @@ -673,7 +673,7 @@ public class TCKZoneRules { final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); - assertEquals(trans.hashCode(), otherTrans.hashCode()); + assertEquals(otherTrans.hashCode(), trans.hashCode()); } @Test @@ -683,15 +683,15 @@ public class TCKZoneRules { while (zdt.getYear() < 2010) { Instant instant = zdt.toInstant(); if (zdt.toLocalDate().isBefore(LocalDate.of(1911, 3, 11))) { - assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, 9, 21)); + assertEquals(ZoneOffset.ofHoursMinutesSeconds(0, 9, 21), test.getStandardOffset(instant)); } else if (zdt.toLocalDate().isBefore(LocalDate.of(1940, 6, 14))) { - assertEquals(test.getStandardOffset(instant), OFFSET_ZERO); + assertEquals(OFFSET_ZERO, test.getStandardOffset(instant)); } else if (zdt.toLocalDate().isBefore(LocalDate.of(1944, 8, 25))) { - assertEquals(test.getStandardOffset(instant), OFFSET_PONE); + assertEquals(OFFSET_PONE, test.getStandardOffset(instant)); } else if (zdt.toLocalDate().isBefore(LocalDate.of(1945, 9, 16))) { - assertEquals(test.getStandardOffset(instant), OFFSET_ZERO); + assertEquals(OFFSET_ZERO, test.getStandardOffset(instant)); } else { - assertEquals(test.getStandardOffset(instant), OFFSET_PONE); + assertEquals(OFFSET_PONE, test.getStandardOffset(instant)); } zdt = zdt.plusMonths(6); } @@ -707,7 +707,7 @@ public class TCKZoneRules { @Test public void test_NewYork() { ZoneRules test = americaNewYork(); - assertEquals(test.isFixedOffset(), false); + assertEquals(false, test.isFixedOffset()); } @Test @@ -716,73 +716,73 @@ public class TCKZoneRules { ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC); Instant instant = old.toInstant(); ZoneOffset offset = ZoneOffset.of("-04:56:02"); - assertEquals(test.getOffset(instant), offset); + assertEquals(offset, test.getOffset(instant)); checkOffset(test, old.toLocalDateTime(), offset, 1); - assertEquals(test.getStandardOffset(instant), offset); - assertEquals(test.getDaylightSavings(instant), Duration.ZERO); - assertEquals(test.isDaylightSavings(instant), false); + assertEquals(offset, test.getStandardOffset(instant)); + assertEquals(Duration.ZERO, test.getDaylightSavings(instant)); + assertEquals(false, test.isDaylightSavings(instant)); } @Test public void test_NewYork_getOffset() { ZoneRules test = americaNewYork(); ZoneOffset offset = ZoneOffset.ofHours(-5); - assertEquals(test.getOffset(createInstant(2008, 1, 1, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 2, 1, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 3, 1, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 4, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 5, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 6, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 7, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 8, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 9, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 10, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 11, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 12, 1, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 1, 28, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 2, 28, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 3, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 4, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 5, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 6, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 7, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 8, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 9, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 10, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 11, 28, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 12, 28, offset)), ZoneOffset.ofHours(-5)); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 1, 1, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 2, 1, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 3, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 4, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 5, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 6, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 7, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 8, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 9, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 10, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 11, 1, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 12, 1, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 1, 28, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 2, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 3, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 4, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 5, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 6, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 7, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 8, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 9, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 10, 28, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 11, 28, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 12, 28, offset))); } @Test public void test_NewYork_getOffset_toDST() { ZoneRules test = americaNewYork(); ZoneOffset offset = ZoneOffset.ofHours(-5); - assertEquals(test.getOffset(createInstant(2008, 3, 8, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 3, 9, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 3, 10, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 3, 11, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 3, 12, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 3, 13, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 3, 14, offset)), ZoneOffset.ofHours(-4)); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 3, 8, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 3, 9, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 3, 10, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 3, 11, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 3, 12, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 3, 13, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 3, 14, offset))); // cutover at 02:00 local - assertEquals(test.getOffset(createInstant(2008, 3, 9, 1, 59, 59, 999999999, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 3, 9, 2, 0, 0, 0, offset)), ZoneOffset.ofHours(-4)); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 3, 9, 1, 59, 59, 999999999, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 3, 9, 2, 0, 0, 0, offset))); } @Test public void test_NewYork_getOffset_fromDST() { ZoneRules test = americaNewYork(); ZoneOffset offset = ZoneOffset.ofHours(-4); - assertEquals(test.getOffset(createInstant(2008, 11, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 11, 2, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 11, 3, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 11, 4, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 11, 5, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 11, 6, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getOffset(createInstant(2008, 11, 7, offset)), ZoneOffset.ofHours(-5)); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 11, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 11, 2, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 11, 3, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 11, 4, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 11, 5, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 11, 6, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 11, 7, offset))); // cutover at 02:00 local - assertEquals(test.getOffset(createInstant(2008, 11, 2, 1, 59, 59, 999999999, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getOffset(createInstant(2008, 11, 2, 2, 0, 0, 0, offset)), ZoneOffset.ofHours(-5)); + assertEquals(ZoneOffset.ofHours(-4), test.getOffset(createInstant(2008, 11, 2, 1, 59, 59, 999999999, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getOffset(createInstant(2008, 11, 2, 2, 0, 0, 0, offset))); } @Test @@ -849,15 +849,15 @@ public class TCKZoneRules { ZoneRules test = americaNewYork(); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 9, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, ZoneOffset.ofHours(-5), GAP); - assertEquals(trans.isGap(), true); - assertEquals(trans.isOverlap(), false); - assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-5)); - assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-4)); - assertEquals(trans.getInstant(), createInstant(2008, 3, 9, 2, 0, ZoneOffset.ofHours(-5))); - assertEquals(trans.isValidOffset(OFFSET_PTWO), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), false); - assertEquals(trans.toString(), "Transition[Gap at 2008-03-09T02:00-05:00 to -04:00]"); + assertEquals(true, trans.isGap()); + assertEquals(false, trans.isOverlap()); + assertEquals(ZoneOffset.ofHours(-5), trans.getOffsetBefore()); + assertEquals(ZoneOffset.ofHours(-4), trans.getOffsetAfter()); + assertEquals(createInstant(2008, 3, 9, 2, 0, ZoneOffset.ofHours(-5)), trans.getInstant()); + assertEquals(false, trans.isValidOffset(OFFSET_PTWO)); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-5))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-4))); + assertEquals("Transition[Gap at 2008-03-09T02:00-05:00 to -04:00]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(-5))); @@ -865,7 +865,7 @@ public class TCKZoneRules { final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); - assertEquals(trans.hashCode(), otherTrans.hashCode()); + assertEquals(otherTrans.hashCode(), trans.hashCode()); } @Test @@ -873,16 +873,16 @@ public class TCKZoneRules { ZoneRules test = americaNewYork(); final LocalDateTime dateTime = LocalDateTime.of(2008, 11, 2, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, ZoneOffset.ofHours(-4), OVERLAP); - assertEquals(trans.isGap(), false); - assertEquals(trans.isOverlap(), true); - assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-4)); - assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-5)); - assertEquals(trans.getInstant(), createInstant(2008, 11, 2, 2, 0, ZoneOffset.ofHours(-4))); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), true); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), true); - assertEquals(trans.isValidOffset(OFFSET_PTWO), false); - assertEquals(trans.toString(), "Transition[Overlap at 2008-11-02T02:00-04:00 to -05:00]"); + assertEquals(false, trans.isGap()); + assertEquals(true, trans.isOverlap()); + assertEquals(ZoneOffset.ofHours(-4), trans.getOffsetBefore()); + assertEquals(ZoneOffset.ofHours(-5), trans.getOffsetAfter()); + assertEquals(createInstant(2008, 11, 2, 2, 0, ZoneOffset.ofHours(-4)), trans.getInstant()); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-1))); + assertEquals(true, trans.isValidOffset(ZoneOffset.ofHours(-5))); + assertEquals(true, trans.isValidOffset(ZoneOffset.ofHours(-4))); + assertEquals(false, trans.isValidOffset(OFFSET_PTWO)); + assertEquals("Transition[Overlap at 2008-11-02T02:00-04:00 to -05:00]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(-4))); @@ -890,7 +890,7 @@ public class TCKZoneRules { final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); - assertEquals(trans.hashCode(), otherTrans.hashCode()); + assertEquals(otherTrans.hashCode(), trans.hashCode()); } @Test @@ -900,9 +900,9 @@ public class TCKZoneRules { while (dateTime.getYear() < 2010) { Instant instant = dateTime.toInstant(); if (dateTime.toLocalDate().isBefore(LocalDate.of(1883, 11, 18))) { - assertEquals(test.getStandardOffset(instant), ZoneOffset.of("-04:56:02")); + assertEquals(ZoneOffset.of("-04:56:02"), test.getStandardOffset(instant)); } else { - assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHours(-5)); + assertEquals(ZoneOffset.ofHours(-5), test.getStandardOffset(instant)); } dateTime = dateTime.plusMonths(6); } @@ -921,14 +921,14 @@ public class TCKZoneRules { List trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); - assertEquals(test.nextTransition(first.getInstant().minusNanos(1)), first); + assertEquals(first, test.nextTransition(first.getInstant().minusNanos(1))); for (int i = 0; i < trans.size() - 1; i++) { ZoneOffsetTransition cur = trans.get(i); ZoneOffsetTransition next = trans.get(i + 1); - assertEquals(test.nextTransition(cur.getInstant()), next); - assertEquals(test.nextTransition(next.getInstant().minusNanos(1)), next); + assertEquals(next, test.nextTransition(cur.getInstant())); + assertEquals(next, test.nextTransition(next.getInstant().minusNanos(1))); } } @@ -938,7 +938,7 @@ public class TCKZoneRules { List trans = test.getTransitions(); ZoneOffsetTransition last = trans.get(trans.size() - 1); - assertEquals(test.nextTransition(last.getInstant()), null); + assertEquals(null, test.nextTransition(last.getInstant())); } //----------------------------------------------------------------------- @@ -954,14 +954,14 @@ public class TCKZoneRules { List trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); - assertEquals(test.nextTransition(first.getInstant().minusNanos(1)), first); + assertEquals(first, test.nextTransition(first.getInstant().minusNanos(1))); for (int i = 0; i < trans.size() - 1; i++) { ZoneOffsetTransition cur = trans.get(i); ZoneOffsetTransition next = trans.get(i + 1); - assertEquals(test.nextTransition(cur.getInstant()), next); - assertEquals(test.nextTransition(next.getInstant().minusNanos(1)), next); + assertEquals(next, test.nextTransition(cur.getInstant())); + assertEquals(next, test.nextTransition(next.getInstant().minusNanos(1))); } } @@ -971,17 +971,17 @@ public class TCKZoneRules { ZoneRules test = pacificApia(); Instant instantBefore = LocalDate.of(2011, 12, 27).atStartOfDay(ZoneOffset.UTC).toInstant(); ZoneOffsetTransition trans = test.nextTransition(instantBefore); - assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2011, 12, 30, 0, 0)); - assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2011, 12, 31, 0, 0)); - assertEquals(trans.isGap(), true); - assertEquals(trans.isOverlap(), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-10)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(+14)), false); - assertEquals(trans.getDuration(), Duration.ofHours(24)); - assertEquals(trans.getInstant(), LocalDateTime.of(2011, 12, 31, 0, 0).toInstant(ZoneOffset.ofHours(+14))); + assertEquals(LocalDateTime.of(2011, 12, 30, 0, 0), trans.getDateTimeBefore()); + assertEquals(LocalDateTime.of(2011, 12, 31, 0, 0), trans.getDateTimeAfter()); + assertEquals(true, trans.isGap()); + assertEquals(false, trans.isOverlap()); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-10))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(+14))); + assertEquals(Duration.ofHours(24), trans.getDuration()); + assertEquals(LocalDateTime.of(2011, 12, 31, 0, 0).toInstant(ZoneOffset.ofHours(+14)), trans.getInstant()); ZonedDateTime zdt = ZonedDateTime.of(2011, 12, 29, 23, 0, 0, 0, ZoneId.of("Pacific/Apia")); - assertEquals(zdt.plusHours(2).toLocalDateTime(), LocalDateTime.of(2011, 12, 31, 1, 0)); + assertEquals(LocalDateTime.of(2011, 12, 31, 1, 0), zdt.plusHours(2).toLocalDateTime()); } @Test @@ -990,30 +990,34 @@ public class TCKZoneRules { ZoneRules test = pacificApia(); Instant instantBefore = LocalDate.of(1892, 7, 2).atStartOfDay(ZoneOffset.UTC).toInstant(); ZoneOffsetTransition trans = test.nextTransition(instantBefore); - assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(1892, 7, 5, 0, 0)); - assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(1892, 7, 4, 0, 0)); - assertEquals(trans.isGap(), false); - assertEquals(trans.isOverlap(), true); - assertEquals(trans.isValidOffset(ZoneOffset.ofHoursMinutesSeconds(+12, 33, 4)), true); - assertEquals(trans.isValidOffset(ZoneOffset.ofHoursMinutesSeconds(-11, -26, -56)), true); - assertEquals(trans.getDuration(), Duration.ofHours(-24)); - assertEquals(trans.getInstant(), LocalDateTime.of(1892, 7, 4, 0, 0).toInstant(ZoneOffset.ofHoursMinutesSeconds(-11, -26, -56))); + assertEquals(LocalDateTime.of(1892, 7, 5, 0, 0), trans.getDateTimeBefore()); + assertEquals(LocalDateTime.of(1892, 7, 4, 0, 0), trans.getDateTimeAfter()); + assertEquals(false, trans.isGap()); + assertEquals(true, trans.isOverlap()); + assertEquals(true, trans.isValidOffset(ZoneOffset.ofHoursMinutesSeconds(+12, 33, 4))); + assertEquals(true, trans.isValidOffset(ZoneOffset.ofHoursMinutesSeconds(-11, -26, -56))); + assertEquals(Duration.ofHours(-24), trans.getDuration()); + assertEquals(LocalDateTime.of(1892, 7, 4, 0, 0).toInstant(ZoneOffset.ofHoursMinutesSeconds(-11, -26, -56)), trans.getInstant()); ZonedDateTime zdt = ZonedDateTime.of(1892, 7, 4, 23, 0, 0, 0, ZoneId.of("Pacific/Apia")); - assertEquals(zdt.plusHours(2).toLocalDateTime(), LocalDateTime.of(1892, 7, 4, 1, 0, 0)); + assertEquals(LocalDateTime.of(1892, 7, 4, 1, 0, 0), zdt.plusHours(2).toLocalDateTime()); } //------------------------------------------------------------------------- - @Test(expectedExceptions=UnsupportedOperationException.class) + @Test public void test_getTransitions_immutable() { - ZoneRules test = europeParis(); - test.getTransitions().clear(); + Assertions.assertThrows(UnsupportedOperationException.class, () -> { + ZoneRules test = europeParis(); + test.getTransitions().clear(); + }); } - @Test(expectedExceptions=UnsupportedOperationException.class) + @Test public void test_getTransitionRules_immutable() { - ZoneRules test = europeParis(); - test.getTransitionRules().clear(); + Assertions.assertThrows(UnsupportedOperationException.class, () -> { + ZoneRules test = europeParis(); + test.getTransitionRules().clear(); + }); } //----------------------------------------------------------------------- @@ -1073,23 +1077,23 @@ public class TCKZoneRules { OffsetDateTime before_time_of_stdOffsetTransition1 = OffsetDateTime.of(time_of_stdOffsetTransition1, stdOffset1).minusSeconds(1); OffsetDateTime after_time_of_stdOffsetTransition1 = OffsetDateTime.of(time_of_stdOffsetTransition1, stdOffset1).plusSeconds(1); - assertEquals(zoneRule.getStandardOffset(before_time_of_stdOffsetTransition1.toInstant()), stdOffset1); - assertEquals(zoneRule.getStandardOffset(after_time_of_stdOffsetTransition1.toInstant()), stdOffset2); + assertEquals(stdOffset1, zoneRule.getStandardOffset(before_time_of_stdOffsetTransition1.toInstant())); + assertEquals(stdOffset2, zoneRule.getStandardOffset(after_time_of_stdOffsetTransition1.toInstant())); OffsetDateTime before_time_of_wallOffsetTransition1 = OffsetDateTime.of(time_of_wallOffsetTransition1, wallOffset1).minusSeconds(1); OffsetDateTime after_time_of_wallOffsetTransition1 = OffsetDateTime.of(time_of_wallOffsetTransition1, wallOffset1).plusSeconds(1); - assertEquals(zoneRule.nextTransition(before_time_of_wallOffsetTransition1.toInstant()), wallOffsetTransition1); - assertEquals(zoneRule.nextTransition(after_time_of_wallOffsetTransition1.toInstant()), wallOffsetTransition2); + assertEquals(wallOffsetTransition1, zoneRule.nextTransition(before_time_of_wallOffsetTransition1.toInstant())); + assertEquals(wallOffsetTransition2, zoneRule.nextTransition(after_time_of_wallOffsetTransition1.toInstant())); OffsetDateTime before_time_of_wallOffsetTransition2 = OffsetDateTime.of(time_of_wallOffsetTransition2, wallOffset2).minusSeconds(1); OffsetDateTime after_time_of_wallOffsetTransition2 = OffsetDateTime.of(time_of_wallOffsetTransition2, wallOffset2).plusSeconds(1); - assertEquals(zoneRule.nextTransition(before_time_of_wallOffsetTransition2.toInstant()), wallOffsetTransition2); - assertEquals(zoneRule.nextTransition(after_time_of_wallOffsetTransition2.toInstant()), wallOffsetTransition3); + assertEquals(wallOffsetTransition2, zoneRule.nextTransition(before_time_of_wallOffsetTransition2.toInstant())); + assertEquals(wallOffsetTransition3, zoneRule.nextTransition(after_time_of_wallOffsetTransition2.toInstant())); OffsetDateTime before_time_of_wallOffsetTransition3 = OffsetDateTime.of(time_of_wallOffsetTransition3, wallOffset3).minusSeconds(1); OffsetDateTime after_time_of_wallOffsetTransition3 = OffsetDateTime.of(time_of_wallOffsetTransition3, wallOffset3).plusSeconds(1); - assertEquals(zoneRule.nextTransition(before_time_of_wallOffsetTransition3.toInstant()), wallOffsetTransition3); - assertEquals(zoneRule.nextTransition(after_time_of_wallOffsetTransition3.toInstant()), rule1.createTransition(2014)); + assertEquals(wallOffsetTransition3, zoneRule.nextTransition(before_time_of_wallOffsetTransition3.toInstant())); + assertEquals(rule1.createTransition(2014), zoneRule.nextTransition(after_time_of_wallOffsetTransition3.toInstant())); } //----------------------------------------------------------------------- @@ -1100,31 +1104,31 @@ public class TCKZoneRules { ZoneRules test1 = europeLondon(); ZoneRules test2 = europeParis(); ZoneRules test2b = europeParis(); - assertEquals(test1.equals(test2), false); - assertEquals(test2.equals(test1), false); + assertEquals(false, test1.equals(test2)); + assertEquals(false, test2.equals(test1)); - assertEquals(test1.equals(test1), true); - assertEquals(test2.equals(test2), true); - assertEquals(test2.equals(test2b), true); + assertEquals(true, test1.equals(test1)); + assertEquals(true, test2.equals(test2)); + assertEquals(true, test2.equals(test2b)); - assertEquals(test1.hashCode() == test1.hashCode(), true); - assertEquals(test2.hashCode() == test2.hashCode(), true); - assertEquals(test2.hashCode() == test2b.hashCode(), true); + assertEquals(true, test1.hashCode() == test1.hashCode()); + assertEquals(true, test2.hashCode() == test2.hashCode()); + assertEquals(true, test2.hashCode() == test2b.hashCode()); } @Test public void test_equals_null() { - assertEquals(europeLondon().equals(null), false); + assertEquals(false, europeLondon().equals(null)); } @Test public void test_equals_notZoneRules() { - assertEquals(europeLondon().equals("Europe/London"), false); + assertEquals(false, europeLondon().equals("Europe/London")); } @Test public void test_toString() { - assertEquals(europeLondon().toString().contains("ZoneRules"), true); + assertEquals(true, europeLondon().toString().contains("ZoneRules")); } //----------------------------------------------------------------------- @@ -1152,17 +1156,17 @@ public class TCKZoneRules { private ZoneOffsetTransition checkOffset(ZoneRules rules, LocalDateTime dateTime, ZoneOffset offset, int type) { List validOffsets = rules.getValidOffsets(dateTime); - assertEquals(validOffsets.size(), type); - assertEquals(rules.getOffset(dateTime), offset); + assertEquals(type, validOffsets.size()); + assertEquals(offset, rules.getOffset(dateTime)); if (type == 1) { - assertEquals(validOffsets.get(0), offset); + assertEquals(offset, validOffsets.get(0)); return null; } else { ZoneOffsetTransition zot = rules.getTransition(dateTime); assertNotNull(zot); - assertEquals(zot.isOverlap(), type == 2); - assertEquals(zot.isGap(), type == 0); - assertEquals(zot.isValidOffset(offset), type == 2); + assertEquals(type == 2, zot.isOverlap()); + assertEquals(type == 0, zot.isGap()); + assertEquals(type == 2, zot.isValidOffset(offset)); return zot; } } diff --git a/test/jdk/java/time/tck/java/time/zone/TCKZoneRulesProvider.java b/test/jdk/java/time/tck/java/time/zone/TCKZoneRulesProvider.java index f51bb396f50..32b1a688b54 100644 --- a/test/jdk/java/time/tck/java/time/zone/TCKZoneRulesProvider.java +++ b/test/jdk/java/time/tck/java/time/zone/TCKZoneRulesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,9 +59,9 @@ */ package tck.java.time.zone; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.ZoneId; import java.time.ZoneOffset; @@ -74,12 +74,12 @@ import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Test ZoneRulesProvider. */ -@Test public class TCKZoneRulesProvider { private static String TZDB_VERSION = "2012i"; @@ -90,12 +90,12 @@ public class TCKZoneRulesProvider { @Test public void test_getAvailableGroupIds() { Set zoneIds = ZoneRulesProvider.getAvailableZoneIds(); - assertEquals(zoneIds.contains("Europe/London"), true); + assertEquals(true, zoneIds.contains("Europe/London")); } - @Test(expectedExceptions=UnsupportedOperationException.class) + @Test public void test_getAvailableGroupIds_modifyZoneId() { - ZoneRulesProvider.getAvailableZoneIds().clear(); + Assertions.assertThrows(UnsupportedOperationException.class, () -> ZoneRulesProvider.getAvailableZoneIds().clear()); } //----------------------------------------------------------------------- @@ -106,17 +106,17 @@ public class TCKZoneRulesProvider { ZoneRules rules = ZoneRulesProvider.getRules("Europe/London", false); assertNotNull(rules); ZoneRules rules2 = ZoneRulesProvider.getRules("Europe/London", false); - assertEquals(rules2, rules); + assertEquals(rules, rules2); } - @Test(expectedExceptions=ZoneRulesException.class) + @Test public void test_getRules_StringBoolean_unknownId() { - ZoneRulesProvider.getRules("Europe/Lon", false); + Assertions.assertThrows(ZoneRulesException.class, () -> ZoneRulesProvider.getRules("Europe/Lon", false)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_getRules_StringBoolean_null() { - ZoneRulesProvider.getRules(null, false); + Assertions.assertThrows(NullPointerException.class, () -> ZoneRulesProvider.getRules(null, false)); } @Test @@ -124,13 +124,13 @@ public class TCKZoneRulesProvider { MockDynamicProvider dynamicProvider = new MockDynamicProvider(); ZoneRulesProvider.registerProvider(dynamicProvider); - assertEquals(dynamicProvider.count, 0); + assertEquals(0, dynamicProvider.count); ZoneRules rules1 = ZoneId.of("DynamicLocation").getRules(); - assertEquals(dynamicProvider.count, 2); - assertEquals(rules1, dynamicProvider.BASE); + assertEquals(2, dynamicProvider.count); + assertEquals(dynamicProvider.BASE, rules1); ZoneRules rules2 = ZoneId.of("DynamicLocation").getRules(); - assertEquals(dynamicProvider.count, 4); - assertEquals(rules2, dynamicProvider.ALTERNATE); + assertEquals(4, dynamicProvider.count); + assertEquals(dynamicProvider.ALTERNATE, rules2); } //----------------------------------------------------------------------- @@ -141,23 +141,23 @@ public class TCKZoneRulesProvider { NavigableMap versions = ZoneRulesProvider.getVersions("Europe/London"); assertTrue(versions.size() >= 1); ZoneRules rules = ZoneRulesProvider.getRules("Europe/London", false); - assertEquals(versions.lastEntry().getValue(), rules); + assertEquals(rules, versions.lastEntry().getValue()); NavigableMap copy = new TreeMap<>(versions); versions.clear(); - assertEquals(versions.size(), 0); + assertEquals(0, versions.size()); NavigableMap versions2 = ZoneRulesProvider.getVersions("Europe/London"); - assertEquals(versions2, copy); + assertEquals(copy, versions2); } - @Test(expectedExceptions=ZoneRulesException.class) + @Test public void test_getVersions_String_unknownId() { - ZoneRulesProvider.getVersions("Europe/Lon"); + Assertions.assertThrows(ZoneRulesException.class, () -> ZoneRulesProvider.getVersions("Europe/Lon")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_getVersions_String_null() { - ZoneRulesProvider.getVersions(null); + Assertions.assertThrows(NullPointerException.class, () -> ZoneRulesProvider.getVersions(null)); } //----------------------------------------------------------------------- @@ -165,7 +165,7 @@ public class TCKZoneRulesProvider { //----------------------------------------------------------------------- @Test public void test_refresh() { - assertEquals(ZoneRulesProvider.refresh(), false); + assertEquals(false, ZoneRulesProvider.refresh()); } //----------------------------------------------------------------------- @@ -174,12 +174,12 @@ public class TCKZoneRulesProvider { @Test public void test_registerProvider() { Set pre = ZoneRulesProvider.getAvailableZoneIds(); - assertEquals(pre.contains("FooLocation"), false); + assertEquals(false, pre.contains("FooLocation")); ZoneRulesProvider.registerProvider(new MockTempProvider()); - assertEquals(pre.contains("FooLocation"), false); + assertEquals(false, pre.contains("FooLocation")); Set post = ZoneRulesProvider.getAvailableZoneIds(); - assertEquals(post.contains("FooLocation"), true); - assertEquals(ZoneRulesProvider.getRules("FooLocation", false), ZoneOffset.of("+01:45").getRules()); + assertEquals(true, post.contains("FooLocation")); + assertEquals(ZoneOffset.of("+01:45").getRules(), ZoneRulesProvider.getRules("FooLocation", false)); } static class MockTempProvider extends ZoneRulesProvider { diff --git a/test/jdk/java/time/tck/java/time/zone/serial/TCKFixedZoneRulesSerialization.java b/test/jdk/java/time/tck/java/time/zone/serial/TCKFixedZoneRulesSerialization.java index 790e54fbb6d..719d5aab5f7 100644 --- a/test/jdk/java/time/tck/java/time/zone/serial/TCKFixedZoneRulesSerialization.java +++ b/test/jdk/java/time/tck/java/time/zone/serial/TCKFixedZoneRulesSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,6 @@ */ package tck.java.time.zone.serial; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -69,12 +67,15 @@ import java.io.ObjectOutputStream; import java.time.ZoneOffset; import java.time.zone.ZoneRules; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test serialization of ZoneRules for fixed offset time-zones. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TCKFixedZoneRulesSerialization { private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); @@ -85,7 +86,6 @@ public class TCKFixedZoneRulesSerialization { return offset.getRules(); } - @DataProvider(name="rules") Object[][] data_rules() { return new Object[][] { {make(OFFSET_PONE), OFFSET_PONE}, @@ -97,7 +97,8 @@ public class TCKFixedZoneRulesSerialization { //----------------------------------------------------------------------- // Basics //----------------------------------------------------------------------- - @Test(dataProvider="rules") + @ParameterizedTest + @MethodSource("data_rules") public void test_serialization(ZoneRules test, ZoneOffset expectedOffset) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); @@ -109,8 +110,8 @@ public class TCKFixedZoneRulesSerialization { ObjectInputStream in = new ObjectInputStream(bais); ZoneRules result = (ZoneRules) in.readObject(); - assertEquals(result, test); - assertEquals(result.getClass(), test.getClass()); + assertEquals(test, result); + assertEquals(test.getClass(), result.getClass()); } diff --git a/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneOffsetTransitionRuleSerialization.java b/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneOffsetTransitionRuleSerialization.java index 42796f66f8f..ded4772cd9f 100644 --- a/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneOffsetTransitionRuleSerialization.java +++ b/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneOffsetTransitionRuleSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -66,13 +66,13 @@ import java.time.ZoneOffset; import java.time.zone.ZoneOffsetTransitionRule; import java.time.zone.ZoneOffsetTransitionRule.TimeDefinition; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; + import tck.java.time.AbstractTCKTest; /** * Test ZoneOffsetTransitionRule serialization. */ -@Test public class TCKZoneOffsetTransitionRuleSerialization extends AbstractTCKTest { private static final LocalTime TIME_0100 = LocalTime.of(1, 0); diff --git a/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneOffsetTransitionSerialization.java b/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneOffsetTransitionSerialization.java index 01ffefe09df..b6ae7dae76b 100644 --- a/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneOffsetTransitionSerialization.java +++ b/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneOffsetTransitionSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -62,7 +62,6 @@ package tck.java.time.zone.serial; import static java.time.temporal.ChronoUnit.HOURS; import java.time.Duration; -import org.testng.annotations.Test; import tck.java.time.AbstractTCKTest; import java.time.LocalDateTime; @@ -70,10 +69,11 @@ import java.time.Year; import java.time.ZoneOffset; import java.time.zone.ZoneOffsetTransition; +import org.junit.jupiter.api.Test; + /** * Test serialization of ZoneOffsetTransition. */ -@Test public class TCKZoneOffsetTransitionSerialization extends AbstractTCKTest { private static final ZoneOffset OFFSET_0200 = ZoneOffset.ofHours(2); diff --git a/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneRulesSerialization.java b/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneRulesSerialization.java index 5262d68eea0..1ba549ba916 100644 --- a/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneRulesSerialization.java +++ b/test/jdk/java/time/tck/java/time/zone/serial/TCKZoneRulesSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,7 +59,6 @@ */ package tck.java.time.zone.serial; -import org.testng.annotations.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -68,16 +67,17 @@ import java.io.ObjectOutputStream; import java.time.ZoneId; import java.time.zone.ZoneRules; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; import tck.java.time.AbstractTCKTest; /** * Test serialization of ZoneRules. */ -@Test public class TCKZoneRulesSerialization extends AbstractTCKTest{ + @Test public void test_serialization_loaded() throws Exception { assertSerialization(europeLondon()); assertSerialization(europeParis()); @@ -95,7 +95,7 @@ public class TCKZoneRulesSerialization extends AbstractTCKTest{ ObjectInputStream in = new ObjectInputStream(bais); ZoneRules result = (ZoneRules) in.readObject(); - assertEquals(result, test); + assertEquals(test, result); } //----------------------------------------------------------------------- diff --git a/test/jdk/java/time/test/TEST.properties b/test/jdk/java/time/test/TEST.properties index 4cc5775e862..e2ecb3e5dc3 100644 --- a/test/jdk/java/time/test/TEST.properties +++ b/test/jdk/java/time/test/TEST.properties @@ -1,5 +1,5 @@ -# java.time tests use TestNG -TestNG.dirs = .. +# java.time tests use JUnit +JUnit.dirs = .. othervm.dirs = java/time lib.dirs = /test/lib /test/jdk/tools/lib lib.build = jdk.test.lib.RandomFactory diff --git a/test/jdk/java/time/test/java/time/AbstractTest.java b/test/jdk/java/time/test/java/time/AbstractTest.java index 6e4734b8e4c..2a117011533 100644 --- a/test/jdk/java/time/test/java/time/AbstractTest.java +++ b/test/jdk/java/time/test/java/time/AbstractTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,9 +59,7 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Constructor; import java.lang.reflect.Field; diff --git a/test/jdk/java/time/test/java/time/TestClock_Fixed.java b/test/jdk/java/time/test/java/time/TestClock_Fixed.java index cf07ceea07b..1c82a092c6a 100644 --- a/test/jdk/java/time/test/java/time/TestClock_Fixed.java +++ b/test/jdk/java/time/test/java/time/TestClock_Fixed.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,8 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import java.time.Clock; import java.time.Instant; @@ -68,18 +68,18 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test fixed clock. */ -@Test public class TestClock_Fixed { private static final ZoneId PARIS = ZoneId.of("Europe/Paris"); private static final Instant INSTANT = LocalDateTime.of(2008, 6, 30, 11, 30, 10, 500).atZone(ZoneOffset.ofHours(2)).toInstant(); //------------------------------------------------------------------------- + @Test public void test_withZone_same() { Clock test = Clock.fixed(INSTANT, PARIS); Clock changed = test.withZone(PARIS); @@ -87,9 +87,10 @@ public class TestClock_Fixed { } //----------------------------------------------------------------------- + @Test public void test_toString() { Clock test = Clock.fixed(INSTANT, PARIS); - assertEquals(test.toString(), "FixedClock[2008-06-30T09:30:10.000000500Z,Europe/Paris]"); + assertEquals("FixedClock[2008-06-30T09:30:10.000000500Z,Europe/Paris]", test.toString()); } } diff --git a/test/jdk/java/time/test/java/time/TestClock_Offset.java b/test/jdk/java/time/test/java/time/TestClock_Offset.java index ed62300e681..03fc2974955 100644 --- a/test/jdk/java/time/test/java/time/TestClock_Offset.java +++ b/test/jdk/java/time/test/java/time/TestClock_Offset.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,25 +59,25 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import java.time.Clock; import java.time.Duration; import java.time.ZoneId; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test offset clock. */ -@Test public class TestClock_Offset { private static final ZoneId PARIS = ZoneId.of("Europe/Paris"); private static final Duration OFFSET = Duration.ofSeconds(2); //------------------------------------------------------------------------- + @Test public void test_withZone_same() { Clock test = Clock.offset(Clock.system(PARIS), OFFSET); Clock changed = test.withZone(PARIS); @@ -85,9 +85,10 @@ public class TestClock_Offset { } //----------------------------------------------------------------------- + @Test public void test_toString() { Clock test = Clock.offset(Clock.systemUTC(), OFFSET); - assertEquals(test.toString(), "OffsetClock[SystemClock[Z],PT2S]"); + assertEquals("OffsetClock[SystemClock[Z],PT2S]", test.toString()); } } diff --git a/test/jdk/java/time/test/java/time/TestClock_System.java b/test/jdk/java/time/test/java/time/TestClock_System.java index 05d235e3b3c..4d685e78cc1 100644 --- a/test/jdk/java/time/test/java/time/TestClock_System.java +++ b/test/jdk/java/time/test/java/time/TestClock_System.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,8 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import java.lang.reflect.Field; import java.time.Clock; @@ -68,18 +68,21 @@ import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test system clock. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestClock_System { private static final ZoneId PARIS = ZoneId.of("Europe/Paris"); private static final Clock systemUTC = Clock.systemUTC(); + @Test public void test_withZone_same() { Clock test = Clock.system(PARIS); Clock changed = test.withZone(PARIS); @@ -87,13 +90,13 @@ public class TestClock_System { } //----------------------------------------------------------------------- + @Test public void test_toString() { Clock test = Clock.system(PARIS); - assertEquals(test.toString(), "SystemClock[Europe/Paris]"); + assertEquals("SystemClock[Europe/Paris]", test.toString()); } //----------------------------------------------------------------------- - @DataProvider(name="sampleSystemUTC") Object[][] provider_sampleSystemUTC() { return new Object[][] { {"Clock.systemUTC()#1", Clock.systemUTC()}, @@ -104,7 +107,8 @@ public class TestClock_System { } // Test for 8073394 - @Test(dataProvider="sampleSystemUTC") + @ParameterizedTest + @MethodSource("provider_sampleSystemUTC") public void test_systemUTC(String s, Clock clock) { if (clock != systemUTC) { throw new RuntimeException("Unexpected clock instance for " + s + ": " @@ -126,6 +130,7 @@ public class TestClock_System { + time.getNano(); } + @Test public void test_ClockResolution() { Clock highestUTC = Clock.systemUTC(); @@ -392,6 +397,7 @@ public class TestClock_System { } } + @Test public void test_OffsetRegular() throws IllegalAccessException { System.out.println("*** Testing regular cases ***"); SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000", @@ -402,6 +408,7 @@ public class TestClock_System { System.currentTimeMillis()/1000 + 1024); } + @Test public void test_OffsetLimits() throws IllegalAccessException { System.out.println("*** Testing limits ***"); SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 - MAX_OFFSET + 1", diff --git a/test/jdk/java/time/test/java/time/TestClock_Tick.java b/test/jdk/java/time/test/java/time/TestClock_Tick.java index 53e27541764..5e23ed74ca2 100644 --- a/test/jdk/java/time/test/java/time/TestClock_Tick.java +++ b/test/jdk/java/time/test/java/time/TestClock_Tick.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,8 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import java.time.Clock; import java.time.Duration; @@ -69,12 +69,11 @@ import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test tick clock. */ -@Test public class TestClock_Tick { private static final ZoneId MOSCOW = ZoneId.of("Europe/Moscow"); @@ -82,6 +81,7 @@ public class TestClock_Tick { private static final ZonedDateTime ZDT = LocalDateTime.of(2008, 6, 30, 11, 30, 10, 500).atZone(ZoneOffset.ofHours(2)); //------------------------------------------------------------------------- + @Test public void test_withZone_same() { Clock test = Clock.tick(Clock.system(PARIS), Duration.ofMillis(500)); Clock changed = test.withZone(PARIS); @@ -89,14 +89,16 @@ public class TestClock_Tick { } //----------------------------------------------------------------------- + @Test public void test_toString() { Clock test = Clock.tick(Clock.systemUTC(), Duration.ofMillis(500)); - assertEquals(test.toString(), "TickClock[SystemClock[Z],PT0.5S]"); + assertEquals("TickClock[SystemClock[Z],PT0.5S]", test.toString()); } //----------------------------------------------------------------------- // Ensure divide-by-zero will not be thrown // @bug 8310232 + @Test public void test_millis() { var test = Clock.tick(Clock.systemUTC(), Duration.ofNanos(1000)); test.millis(); diff --git a/test/jdk/java/time/test/java/time/TestDuration.java b/test/jdk/java/time/test/java/time/TestDuration.java index 2b2043377f3..37147687511 100644 --- a/test/jdk/java/time/test/java/time/TestDuration.java +++ b/test/jdk/java/time/test/java/time/TestDuration.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,18 +59,16 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import java.time.Duration; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test Duration. */ -@Test public class TestDuration extends AbstractTest { //----------------------------------------------------------------------- @@ -187,14 +185,14 @@ public class TestDuration extends AbstractTest { for (int j = 0; j < durations.length; j++) { Duration b = durations[j]; if (i < j) { - assertEquals(a.compareTo(b)< 0, true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.compareTo(b)< 0, a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { - assertEquals(a.compareTo(b) > 0, true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.compareTo(b) > 0, a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } diff --git a/test/jdk/java/time/test/java/time/TestInstant.java b/test/jdk/java/time/test/java/time/TestInstant.java index 8dbd951bde1..40f3138ac28 100644 --- a/test/jdk/java/time/test/java/time/TestInstant.java +++ b/test/jdk/java/time/test/java/time/TestInstant.java @@ -66,16 +66,18 @@ import java.time.ZoneOffset; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; -import org.testng.annotations.Test; -import org.testng.annotations.DataProvider; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test Instant. * @bug 8273369 8331202 8364752 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestInstant extends AbstractTest { @Test @@ -83,7 +85,6 @@ public class TestInstant extends AbstractTest { assertImmutable(Instant.class); } - @DataProvider(name="sampleEpochMillis") private Object[][] provider_sampleEpochMillis() { return new Object[][] { {"Long.MAX_VALUE", Long.MAX_VALUE}, @@ -96,11 +97,12 @@ public class TestInstant extends AbstractTest { }; } - @Test(dataProvider="sampleEpochMillis") + @ParameterizedTest + @MethodSource("provider_sampleEpochMillis") public void test_epochMillis(String name, long millis) { Instant t1 = Instant.ofEpochMilli(millis); long m = t1.toEpochMilli(); - assertEquals(millis, m, name); + assertEquals(m, millis, name); } /** @@ -113,7 +115,7 @@ public class TestInstant extends AbstractTest { var nanoMax = Instant.EPOCH.plusNanos(Long.MAX_VALUE); var totalMicros = Instant.EPOCH.until(nanoMax, ChronoUnit.MICROS); var plusOneMicro = Instant.EPOCH.until(nanoMax.plusNanos(1000), ChronoUnit.MICROS); - assertEquals(plusOneMicro - totalMicros, 1L); + assertEquals(1L, plusOneMicro - totalMicros); } /** @@ -122,11 +124,10 @@ public class TestInstant extends AbstractTest { */ @Test public void test_millisUntil() { - assertEquals(Instant.MIN.until(Instant.MIN.plusSeconds(1), ChronoUnit.MILLIS), 1000L); - assertEquals(Instant.MAX.plusSeconds(-1).until(Instant.MAX, ChronoUnit.MILLIS), 1000L); + assertEquals(1000L, Instant.MIN.until(Instant.MIN.plusSeconds(1), ChronoUnit.MILLIS)); + assertEquals(1000L, Instant.MAX.plusSeconds(-1).until(Instant.MAX, ChronoUnit.MILLIS)); } - @DataProvider private Object[][] provider_until_1arg() { Instant t1 = Instant.ofEpochSecond(0, 10); Instant t2 = Instant.ofEpochSecond(10, -20); @@ -138,24 +139,22 @@ public class TestInstant extends AbstractTest { }; } - @Test(dataProvider = "provider_until_1arg") + @ParameterizedTest + @MethodSource("provider_until_1arg") public void test_until_1arg(Instant start, Instant end) { Duration result = start.until(end); Duration expected = Duration.ofSeconds(end.getEpochSecond() - start.getEpochSecond(), end.getNano() - start.getNano()); - assertEquals(result, expected); + assertEquals(expected, result); expected = Duration.between(start, end); - assertEquals(result, expected); + assertEquals(expected, result); } @Test public void test_until_1arg_NPE() { - assertThrows(NullPointerException.class, () -> { - Instant.now().until(null); - }); + assertThrows(NullPointerException.class, () -> Instant.now().until(null)); } - @DataProvider private Object[][] valid_instants() { var I1 = OffsetDateTime.of(2017, 1, 1, 0, 0, 0, 0, ZoneOffset.of("+02")).toInstant(); var I2 = OffsetDateTime.of(2017, 1, 1, 0, 0, 0, 0, ZoneOffset.of("+02:02")).toInstant(); @@ -178,12 +177,12 @@ public class TestInstant extends AbstractTest { }; } - @Test(dataProvider = "valid_instants") + @ParameterizedTest + @MethodSource("valid_instants") public void test_parse_valid(String instant, Instant expected) { - assertEquals(Instant.parse(instant), expected); + assertEquals(expected, Instant.parse(instant)); } - @DataProvider private Object[][] invalid_instants() { return new Object[][] { {"2017-01-01T00:00:00.000"}, @@ -204,7 +203,8 @@ public class TestInstant extends AbstractTest { }; } - @Test(dataProvider = "invalid_instants") + @ParameterizedTest + @MethodSource("invalid_instants") public void test_parse_invalid(String instant) { assertThrows(DateTimeParseException.class, () -> Instant.parse(instant)); } diff --git a/test/jdk/java/time/test/java/time/TestInstantSource.java b/test/jdk/java/time/test/java/time/TestInstantSource.java index 31fe7874e62..e0f70047718 100644 --- a/test/jdk/java/time/test/java/time/TestInstantSource.java +++ b/test/jdk/java/time/test/java/time/TestInstantSource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2025, 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,10 @@ package test.java.time; import static java.time.temporal.ChronoUnit.SECONDS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Clock; import java.time.Duration; @@ -34,67 +35,70 @@ import java.time.InstantSource; import java.time.ZoneId; import java.time.ZoneOffset; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test instant source. */ -@Test public class TestInstantSource { private static final ZoneId PARIS = ZoneId.of("Europe/Paris"); + @Test public void test_system() { // main tests for Clock.currentInstant() are in TestClock_System var test = InstantSource.system(); assertSame(test.withZone(ZoneOffset.UTC), Clock.systemUTC()); - assertEquals(test.withZone(PARIS), Clock.system(PARIS)); + assertEquals(Clock.system(PARIS), test.withZone(PARIS)); var millis = System.currentTimeMillis(); var testMillis = test.millis(); var testInstantMillis = test.instant().toEpochMilli(); assertTrue(Math.abs(testMillis - millis) < 1000); assertTrue(Math.abs(testInstantMillis - millis) < 1000); assertSame(test, InstantSource.system()); - assertEquals(test.hashCode(), InstantSource.system().hashCode()); - assertEquals(test.toString(), "SystemInstantSource"); + assertEquals(InstantSource.system().hashCode(), test.hashCode()); + assertEquals("SystemInstantSource", test.toString()); } + @Test public void test_tick() { var millis = 257265861691L; var instant = Instant.ofEpochMilli(millis); var duration = Duration.ofSeconds(1); var test = InstantSource.tick(InstantSource.fixed(instant), duration); - assertEquals(test.withZone(ZoneOffset.UTC), Clock.tick(Clock.fixed(instant, ZoneOffset.UTC), duration)); - assertEquals(test.withZone(PARIS), Clock.tick(Clock.fixed(instant, PARIS), duration)); - assertEquals(test.millis(), (millis / 1000) * 1000); - assertEquals(test.instant(), instant.truncatedTo(SECONDS)); - assertEquals(test, InstantSource.tick(InstantSource.fixed(instant), duration)); - assertEquals(test.hashCode(), InstantSource.tick(InstantSource.fixed(instant), duration).hashCode()); + assertEquals(Clock.tick(Clock.fixed(instant, ZoneOffset.UTC), duration), test.withZone(ZoneOffset.UTC)); + assertEquals(Clock.tick(Clock.fixed(instant, PARIS), duration), test.withZone(PARIS)); + assertEquals((millis / 1000) * 1000, test.millis()); + assertEquals(instant.truncatedTo(SECONDS), test.instant()); + assertEquals(InstantSource.tick(InstantSource.fixed(instant), duration), test); + assertEquals(InstantSource.tick(InstantSource.fixed(instant), duration).hashCode(), test.hashCode()); } + @Test public void test_fixed() { var millis = 257265861691L; var instant = Instant.ofEpochMilli(millis); var test = InstantSource.fixed(instant); - assertEquals(test.withZone(ZoneOffset.UTC), Clock.fixed(instant, ZoneOffset.UTC)); - assertEquals(test.withZone(PARIS), Clock.fixed(instant, PARIS)); - assertEquals(test.millis(), millis); - assertEquals(test.instant(), instant); - assertEquals(test, InstantSource.fixed(instant)); - assertEquals(test.hashCode(), InstantSource.fixed(instant).hashCode()); + assertEquals(Clock.fixed(instant, ZoneOffset.UTC), test.withZone(ZoneOffset.UTC)); + assertEquals(Clock.fixed(instant, PARIS), test.withZone(PARIS)); + assertEquals(millis, test.millis()); + assertEquals(instant, test.instant()); + assertEquals(InstantSource.fixed(instant), test); + assertEquals(InstantSource.fixed(instant).hashCode(), test.hashCode()); } + @Test public void test_offset() { var millis = 257265861691L; var instant = Instant.ofEpochMilli(millis); var duration = Duration.ofSeconds(120); var test = InstantSource.offset(InstantSource.fixed(instant), duration); - assertEquals(test.withZone(ZoneOffset.UTC), Clock.offset(Clock.fixed(instant, ZoneOffset.UTC), duration)); - assertEquals(test.withZone(PARIS), Clock.offset(Clock.fixed(instant, PARIS), duration)); - assertEquals(test.millis(), millis + 120_000); - assertEquals(test.instant(), instant.plusSeconds(120)); - assertEquals(test, InstantSource.offset(InstantSource.fixed(instant), duration)); - assertEquals(test.hashCode(), InstantSource.offset(InstantSource.fixed(instant), duration).hashCode()); + assertEquals(Clock.offset(Clock.fixed(instant, ZoneOffset.UTC), duration), test.withZone(ZoneOffset.UTC)); + assertEquals(Clock.offset(Clock.fixed(instant, PARIS), duration), test.withZone(PARIS)); + assertEquals(millis + 120_000, test.millis()); + assertEquals(instant.plusSeconds(120), test.instant()); + assertEquals(InstantSource.offset(InstantSource.fixed(instant), duration), test); + assertEquals(InstantSource.offset(InstantSource.fixed(instant), duration).hashCode(), test.hashCode()); } static class MockInstantSource implements InstantSource { @@ -106,13 +110,14 @@ public class TestInstantSource { } } + @Test public void test_mock() { var test = new MockInstantSource(); - assertEquals(test.withZone(ZoneOffset.UTC).getZone(), ZoneOffset.UTC); - assertEquals(test.withZone(PARIS).getZone(), PARIS); - assertEquals(test.withZone(ZoneOffset.UTC).withZone(PARIS).getZone(), PARIS); - assertEquals(test.millis(), MockInstantSource.FIXED.toEpochMilli()); - assertEquals(test.instant(), MockInstantSource.FIXED); + assertEquals(ZoneOffset.UTC, test.withZone(ZoneOffset.UTC).getZone()); + assertEquals(PARIS, test.withZone(PARIS).getZone()); + assertEquals(PARIS, test.withZone(ZoneOffset.UTC).withZone(PARIS).getZone()); + assertEquals(MockInstantSource.FIXED.toEpochMilli(), test.millis()); + assertEquals(MockInstantSource.FIXED, test.instant()); assertEquals(test.withZone(ZoneOffset.UTC), test.withZone(ZoneOffset.UTC)); assertEquals(test.withZone(ZoneOffset.UTC).hashCode(), test.withZone(ZoneOffset.UTC).hashCode()); } diff --git a/test/jdk/java/time/test/java/time/TestLocalDate.java b/test/jdk/java/time/test/java/time/TestLocalDate.java index ef7a10ac687..b7f232665d0 100644 --- a/test/jdk/java/time/test/java/time/TestLocalDate.java +++ b/test/jdk/java/time/test/java/time/TestLocalDate.java @@ -60,10 +60,11 @@ package test.java.time; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ObjectStreamClass; import java.io.ObjectStreamField; @@ -74,19 +75,21 @@ import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.time.temporal.IsoFields; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test LocalDate. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestLocalDate extends AbstractTest { private LocalDate TEST_2007_07_15; - @BeforeMethod + @BeforeEach public void setUp() { TEST_2007_07_15 = LocalDate.of(2007, 7, 15); } @@ -180,7 +183,6 @@ public class TestLocalDate extends AbstractTest { //----------------------------------------------------------------------- // plusWeeks() //----------------------------------------------------------------------- - @DataProvider(name="samplePlusWeeksSymmetry") Object[][] provider_samplePlusWeeksSymmetry() { return new Object[][] { {LocalDate.of(-1, 1, 1)}, @@ -212,14 +214,15 @@ public class TestLocalDate extends AbstractTest { }; } - @Test(dataProvider="samplePlusWeeksSymmetry") + @ParameterizedTest + @MethodSource("provider_samplePlusWeeksSymmetry") public void test_plusWeeks_symmetry(LocalDate reference) { for (int weeks = 0; weeks < 365 * 8; weeks++) { LocalDate t = reference.plusWeeks(weeks).plusWeeks(-weeks); - assertEquals(t, reference); + assertEquals(reference, t); t = reference.plusWeeks(-weeks).plusWeeks(weeks); - assertEquals(t, reference); + assertEquals(reference, t); } } @@ -232,7 +235,6 @@ public class TestLocalDate extends AbstractTest { //----------------------------------------------------------------------- // plusDays() //----------------------------------------------------------------------- - @DataProvider(name="samplePlusDaysSymmetry") Object[][] provider_samplePlusDaysSymmetry() { return new Object[][] { {LocalDate.of(-1, 1, 1)}, @@ -264,14 +266,15 @@ public class TestLocalDate extends AbstractTest { }; } - @Test(dataProvider="samplePlusDaysSymmetry") + @ParameterizedTest + @MethodSource("provider_samplePlusDaysSymmetry") public void test_plusDays_symmetry(LocalDate reference) { for (int days = 0; days < 365 * 8; days++) { LocalDate t = reference.plusDays(days).plusDays(-days); - assertEquals(t, reference); + assertEquals(reference, t); t = reference.plusDays(-days).plusDays(days); - assertEquals(t, reference); + assertEquals(reference, t); } } @@ -308,7 +311,6 @@ public class TestLocalDate extends AbstractTest { //----------------------------------------------------------------------- // minusWeeks() //----------------------------------------------------------------------- - @DataProvider(name="sampleMinusWeeksSymmetry") Object[][] provider_sampleMinusWeeksSymmetry() { return new Object[][] { {LocalDate.of(-1, 1, 1)}, @@ -340,14 +342,15 @@ public class TestLocalDate extends AbstractTest { }; } - @Test(dataProvider="sampleMinusWeeksSymmetry") + @ParameterizedTest + @MethodSource("provider_sampleMinusWeeksSymmetry") public void test_minusWeeks_symmetry(LocalDate reference) { for (int weeks = 0; weeks < 365 * 8; weeks++) { LocalDate t = reference.minusWeeks(weeks).minusWeeks(-weeks); - assertEquals(t, reference); + assertEquals(reference, t); t = reference.minusWeeks(-weeks).minusWeeks(weeks); - assertEquals(t, reference); + assertEquals(reference, t); } } @@ -360,7 +363,6 @@ public class TestLocalDate extends AbstractTest { //----------------------------------------------------------------------- // minusDays() //----------------------------------------------------------------------- - @DataProvider(name="sampleMinusDaysSymmetry") Object[][] provider_sampleMinusDaysSymmetry() { return new Object[][] { {LocalDate.of(-1, 1, 1)}, @@ -392,14 +394,15 @@ public class TestLocalDate extends AbstractTest { }; } - @Test(dataProvider="sampleMinusDaysSymmetry") + @ParameterizedTest + @MethodSource("provider_sampleMinusDaysSymmetry") public void test_minusDays_symmetry(LocalDate reference) { for (int days = 0; days < 365 * 8; days++) { LocalDate t = reference.minusDays(days).minusDays(-days); - assertEquals(t, reference); + assertEquals(reference, t); t = reference.minusDays(-days).minusDays(days); - assertEquals(t, reference); + assertEquals(reference, t); } } @@ -415,12 +418,12 @@ public class TestLocalDate extends AbstractTest { LocalDate test = LocalDate.of(0, 1, 1); for (long i = date_0000_01_01; i < 700000; i++) { - assertEquals(LocalDate.ofEpochDay(test.toEpochDay()), test); + assertEquals(test, LocalDate.ofEpochDay(test.toEpochDay())); test = next(test); } test = LocalDate.of(0, 1, 1); for (long i = date_0000_01_01; i > -2000000; i--) { - assertEquals(LocalDate.ofEpochDay(test.toEpochDay()), test); + assertEquals(test, LocalDate.ofEpochDay(test.toEpochDay())); test = previous(test); } } @@ -434,11 +437,11 @@ public class TestLocalDate extends AbstractTest { int[] offsets = new int[] { 0, 1, 2, 3, 28, 29, 30, 31, 32, 363, 364, 365, 366, 367 }; for (int offset : offsets) { LocalDate minDate = LocalDate.ofEpochDay(minDay + offset); - assertEquals(minDate, LocalDate.MIN.plusDays(offset)); + assertEquals(LocalDate.MIN.plusDays(offset), minDate); assertTrue(ChronoField.YEAR.range().isValidValue(minDate.getYear())); LocalDate maxDate = LocalDate.ofEpochDay(maxDay - offset); - assertEquals(maxDate, LocalDate.MAX.minusDays(offset)); + assertEquals(LocalDate.MAX.minusDays(offset), maxDate); assertTrue(ChronoField.YEAR.range().isValidValue(maxDate.getYear())); try { @@ -463,25 +466,24 @@ public class TestLocalDate extends AbstractTest { LocalDate b = localDates[j]; if (i < j) { assertTrue(a.compareTo(b) < 0, a + " <=> " + b); - assertEquals(a.isBefore(b), true, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { assertTrue(a.compareTo(b) > 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(true, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } } - @DataProvider(name="quarterYearsToAdd") Object[][] provider_quarterYearsToAdd() { return new Object[][] { {Long.valueOf(-1000000000)}, @@ -496,7 +498,8 @@ public class TestLocalDate extends AbstractTest { }; } - @Test(dataProvider="quarterYearsToAdd") + @ParameterizedTest + @MethodSource("provider_quarterYearsToAdd") public void test_plus_QuarterYears(long quarterYears) { LocalDate t0 = TEST_2007_07_15 .plus(quarterYears, IsoFields.QUARTER_YEARS); @@ -504,10 +507,11 @@ public class TestLocalDate extends AbstractTest { .plus(quarterYears, ChronoUnit.MONTHS) .plus(quarterYears, ChronoUnit.MONTHS) .plus(quarterYears, ChronoUnit.MONTHS); - assertEquals(t0, t1); + assertEquals(t1, t0); } - @Test(dataProvider="quarterYearsToAdd") + @ParameterizedTest + @MethodSource("provider_quarterYearsToAdd") public void test_minus_QuarterYears(long quarterYears) { LocalDate t0 = TEST_2007_07_15 .minus(quarterYears, IsoFields.QUARTER_YEARS); @@ -515,7 +519,7 @@ public class TestLocalDate extends AbstractTest { .minus(quarterYears, ChronoUnit.MONTHS) .minus(quarterYears, ChronoUnit.MONTHS) .minus(quarterYears, ChronoUnit.MONTHS); - assertEquals(t0, t1); + assertEquals(t1, t0); } // Verify serialized fields types are backward compatible @@ -524,9 +528,9 @@ public class TestLocalDate extends AbstractTest { var osc = ObjectStreamClass.lookup(LocalDate.class); for (ObjectStreamField f : osc.getFields()) { switch (f.getName()) { - case "year" -> assertEquals(f.getType(), int.class, f.getName()); + case "year" -> assertEquals(int.class, f.getType(), f.getName()); case "month", - "day" -> assertEquals(f.getType(), short.class); + "day" -> assertEquals(short.class, f.getType()); default -> fail("unknown field in LocalDate: " + f.getName()); } } diff --git a/test/jdk/java/time/test/java/time/TestLocalDateTime.java b/test/jdk/java/time/test/java/time/TestLocalDateTime.java index 80469ed0621..fb53ec70ede 100644 --- a/test/jdk/java/time/test/java/time/TestLocalDateTime.java +++ b/test/jdk/java/time/test/java/time/TestLocalDateTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,9 +59,9 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.LocalDate; import java.time.LocalDateTime; @@ -69,13 +69,15 @@ import java.time.LocalTime; import java.time.Period; import java.time.temporal.ChronoUnit; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test LocalDateTime. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestLocalDateTime extends AbstractTest { private LocalDateTime TEST_2007_07_15_12_30_40_987654321 = LocalDateTime.of(2007, 7, 15, 12, 30, 40, 987654321); @@ -87,7 +89,6 @@ public class TestLocalDateTime extends AbstractTest { } //----------------------------------------------------------------------- - @DataProvider(name="sampleDates") Object[][] provider_sampleDates() { return new Object[][] { {2008, 7, 5}, @@ -99,7 +100,6 @@ public class TestLocalDateTime extends AbstractTest { }; } - @DataProvider(name="sampleTimes") Object[][] provider_sampleTimes() { return new Object[][] { {0, 0, 0, 0}, @@ -444,7 +444,7 @@ public class TestLocalDateTime extends AbstractTest { @Test public void test_minusSeconds_noChange_oneDay() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.minusSeconds(24 * 60 * 60); - assertEquals(t.toLocalDate(), TEST_2007_07_15_12_30_40_987654321.toLocalDate().minusDays(1)); + assertEquals(TEST_2007_07_15_12_30_40_987654321.toLocalDate().minusDays(1), t.toLocalDate()); assertSame(t.toLocalTime(), TEST_2007_07_15_12_30_40_987654321.toLocalTime()); } @@ -469,7 +469,7 @@ public class TestLocalDateTime extends AbstractTest { @Test public void test_minusNanos_noChange_oneDay() { LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.minusNanos(24 * 60 * 60 * 1000000000L); - assertEquals(t.toLocalDate(), TEST_2007_07_15_12_30_40_987654321.toLocalDate().minusDays(1)); + assertEquals(TEST_2007_07_15_12_30_40_987654321.toLocalDate().minusDays(1), t.toLocalDate()); assertSame(t.toLocalTime(), TEST_2007_07_15_12_30_40_987654321.toLocalTime()); } @@ -488,7 +488,8 @@ public class TestLocalDateTime extends AbstractTest { //----------------------------------------------------------------------- // toLocalDate() //----------------------------------------------------------------------- - @Test(dataProvider="sampleDates") + @ParameterizedTest + @MethodSource("provider_sampleDates") public void test_getDate(int year, int month, int day) { LocalDate d = LocalDate.of(year, month, day); LocalDateTime dt = LocalDateTime.of(d, LocalTime.MIDNIGHT); @@ -498,7 +499,8 @@ public class TestLocalDateTime extends AbstractTest { //----------------------------------------------------------------------- // toLocalTime() //----------------------------------------------------------------------- - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_getTime(int h, int m, int s, int ns) { LocalTime t = LocalTime.of(h, m, s, ns); LocalDateTime dt = LocalDateTime.of(LocalDate.of(2011, 7, 30), t); @@ -549,19 +551,19 @@ public class TestLocalDateTime extends AbstractTest { LocalDateTime b = localDateTimes[j]; if (i < j) { assertTrue(a.compareTo(b) < 0, a + " <=> " + b); - assertEquals(a.isBefore(b), true, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { assertTrue(a.compareTo(b) > 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(true, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } diff --git a/test/jdk/java/time/test/java/time/TestLocalTime.java b/test/jdk/java/time/test/java/time/TestLocalTime.java index 8e25a85f198..24a456683fd 100644 --- a/test/jdk/java/time/test/java/time/TestLocalTime.java +++ b/test/jdk/java/time/test/java/time/TestLocalTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,19 +59,18 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Clock; import java.time.LocalTime; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test LocalTime. */ -@Test public class TestLocalTime extends AbstractTest { static final long NANOS_PER_SECOND = 1_000_000_000L; static final long NANOS_PER_MINUTE = 60 * NANOS_PER_SECOND; @@ -85,10 +84,10 @@ public class TestLocalTime extends AbstractTest { //----------------------------------------------------------------------- private void check(LocalTime time, int h, int m, int s, int n) { - assertEquals(time.getHour(), h); - assertEquals(time.getMinute(), m); - assertEquals(time.getSecond(), s); - assertEquals(time.getNano(), n); + assertEquals(h, time.getHour()); + assertEquals(m, time.getMinute()); + assertEquals(s, time.getSecond()); + assertEquals(n, time.getNano()); } //----------------------------------------------------------------------- @@ -184,8 +183,8 @@ public class TestLocalTime extends AbstractTest { //----------------------------------------------------------------------- // now() //----------------------------------------------------------------------- - @Test @SuppressWarnings("unused") + @Test public void now() { // Warmup the TimeZone data so the following test does not include // one-time initialization diff --git a/test/jdk/java/time/test/java/time/TestMonthDay.java b/test/jdk/java/time/test/java/time/TestMonthDay.java index 311a40030c1..a5195387d2b 100644 --- a/test/jdk/java/time/test/java/time/TestMonthDay.java +++ b/test/jdk/java/time/test/java/time/TestMonthDay.java @@ -59,10 +59,10 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ObjectStreamClass; import java.io.ObjectStreamField; @@ -70,18 +70,17 @@ import java.time.LocalDate; import java.time.Month; import java.time.MonthDay; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test MonthDay. */ -@Test public class TestMonthDay extends AbstractTest { private MonthDay TEST_07_15; - @BeforeMethod + @BeforeEach public void setUp() { TEST_07_15 = MonthDay.of(7, 15); } @@ -94,8 +93,8 @@ public class TestMonthDay extends AbstractTest { //----------------------------------------------------------------------- void check(MonthDay test, int m, int d) { - assertEquals(test.getMonth().getValue(), m); - assertEquals(test.getDayOfMonth(), d); + assertEquals(m, test.getMonth().getValue()); + assertEquals(d, test.getDayOfMonth()); } @Test @@ -129,19 +128,19 @@ public class TestMonthDay extends AbstractTest { MonthDay b = localDates[j]; if (i < j) { assertTrue(a.compareTo(b) < 0, a + " <=> " + b); - assertEquals(a.isBefore(b), true, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(true, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else if (i > j) { assertTrue(a.compareTo(b) > 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), true, a + " <=> " + b); - assertEquals(a.equals(b), false, a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(true, a.isAfter(b), a + " <=> " + b); + assertEquals(false, a.equals(b), a + " <=> " + b); } else { - assertEquals(a.compareTo(b), 0, a + " <=> " + b); - assertEquals(a.isBefore(b), false, a + " <=> " + b); - assertEquals(a.isAfter(b), false, a + " <=> " + b); - assertEquals(a.equals(b), true, a + " <=> " + b); + assertEquals(0, a.compareTo(b), a + " <=> " + b); + assertEquals(false, a.isBefore(b), a + " <=> " + b); + assertEquals(false, a.isAfter(b), a + " <=> " + b); + assertEquals(true, a.equals(b), a + " <=> " + b); } } } @@ -155,7 +154,7 @@ public class TestMonthDay extends AbstractTest { for (ObjectStreamField f : osc.getFields()) { switch (f.getName()) { case "month", - "day" -> assertEquals(f.getType(), int.class, f.getName()); + "day" -> assertEquals(int.class, f.getType(), f.getName()); default -> fail("unknown field in MonthDay: " + f.getName()); } } diff --git a/test/jdk/java/time/test/java/time/TestOffsetDateTime.java b/test/jdk/java/time/test/java/time/TestOffsetDateTime.java index bd145fa9663..3caf4d13c88 100644 --- a/test/jdk/java/time/test/java/time/TestOffsetDateTime.java +++ b/test/jdk/java/time/test/java/time/TestOffsetDateTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,8 +59,8 @@ */ package test.java.time; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Duration; import java.time.LocalDate; @@ -69,23 +69,25 @@ import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test OffsetDateTime. * * @bug 8211990 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestOffsetDateTime extends AbstractTest { private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2); private OffsetDateTime TEST_2008_6_30_11_30_59_000000500; - @BeforeMethod + @BeforeEach public void setUp() { TEST_2008_6_30_11_30_59_000000500 = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59, 500), OFFSET_PONE); } @@ -98,7 +100,6 @@ public class TestOffsetDateTime extends AbstractTest { //----------------------------------------------------------------------- // basics //----------------------------------------------------------------------- - @DataProvider(name="sampleTimes") Object[][] provider_sampleTimes() { return new Object[][] { {2008, 6, 30, 11, 30, 20, 500, OFFSET_PONE}, @@ -108,7 +109,8 @@ public class TestOffsetDateTime extends AbstractTest { }; } - @Test(dataProvider="sampleTimes") + @ParameterizedTest + @MethodSource("provider_sampleTimes") public void test_get_same(int y, int o, int d, int h, int m, int s, int n, ZoneOffset offset) { LocalDate localDate = LocalDate.of(y, o, d); LocalTime localTime = LocalTime.of(h, m, s, n); @@ -329,6 +331,6 @@ public class TestOffsetDateTime extends AbstractTest { OffsetDateTime start = OffsetDateTime.MAX .withOffsetSameLocal(ZoneOffset.ofHours(-17)); OffsetDateTime end = OffsetDateTime.MAX; - assertEquals(Duration.between(start, end), Duration.ofHours(1)); + assertEquals(Duration.ofHours(1), Duration.between(start, end)); } } diff --git a/test/jdk/java/time/test/java/time/TestOffsetDateTime_instants.java b/test/jdk/java/time/test/java/time/TestOffsetDateTime_instants.java index 28b32ba2811..9131a7b02b6 100644 --- a/test/jdk/java/time/test/java/time/TestOffsetDateTime_instants.java +++ b/test/jdk/java/time/test/java/time/TestOffsetDateTime_instants.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,7 +59,7 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DateTimeException; import java.time.Instant; @@ -70,12 +70,12 @@ import java.time.OffsetDateTime; import java.time.Year; import java.time.ZoneOffset; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Test OffsetDateTime creation. */ -@Test public class TestOffsetDateTime_instants { private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); @@ -83,148 +83,167 @@ public class TestOffsetDateTime_instants { private static final ZoneOffset OFFSET_MIN = ZoneOffset.ofHours(-18); //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_nullInstant() { - OffsetDateTime.ofInstant((Instant) null, OFFSET_PONE); + Assertions.assertThrows(NullPointerException.class, () -> OffsetDateTime.ofInstant((Instant) null, OFFSET_PONE)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void factory_ofInstant_nullOffset() { - Instant instant = Instant.ofEpochSecond(0L); - OffsetDateTime.ofInstant(instant, (ZoneOffset) null); + Assertions.assertThrows(NullPointerException.class, () -> { + Instant instant = Instant.ofEpochSecond(0L); + OffsetDateTime.ofInstant(instant, (ZoneOffset) null); + }); } + @Test public void factory_ofInstant_allSecsInDay() { for (int i = 0; i < (24 * 60 * 60); i++) { Instant instant = Instant.ofEpochSecond(i); OffsetDateTime test = OffsetDateTime.ofInstant(instant, OFFSET_PONE); - assertEquals(test.getYear(), 1970); - assertEquals(test.getMonth(), Month.JANUARY); - assertEquals(test.getDayOfMonth(), 1 + (i >= 23 * 60 * 60 ? 1 : 0)); - assertEquals(test.getHour(), ((i / (60 * 60)) + 1) % 24); - assertEquals(test.getMinute(), (i / 60) % 60); - assertEquals(test.getSecond(), i % 60); + assertEquals(1970, test.getYear()); + assertEquals(Month.JANUARY, test.getMonth()); + assertEquals(1 + (i >= 23 * 60 * 60 ? 1 : 0), test.getDayOfMonth()); + assertEquals(((i / (60 * 60)) + 1) % 24, test.getHour()); + assertEquals((i / 60) % 60, test.getMinute()); + assertEquals(i % 60, test.getSecond()); } } + @Test public void factory_ofInstant_allDaysInCycle() { // sanity check using different algorithm OffsetDateTime expected = OffsetDateTime.of(LocalDate.of(1970, 1, 1), LocalTime.of(0, 0, 0, 0), ZoneOffset.UTC); for (long i = 0; i < 146097; i++) { Instant instant = Instant.ofEpochSecond(i * 24L * 60L * 60L); OffsetDateTime test = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); - assertEquals(test, expected); + assertEquals(expected, test); expected = expected.plusDays(1); } } + @Test public void factory_ofInstant_history() { doTest_factory_ofInstant_all(-2820, 2820); } //----------------------------------------------------------------------- + @Test public void factory_ofInstant_minYear() { doTest_factory_ofInstant_all(Year.MIN_VALUE, Year.MIN_VALUE + 420); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_tooLow() { - long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); - int year = Year.MIN_VALUE - 1; - long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; - Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L); - OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); + Assertions.assertThrows(DateTimeException.class, () -> { + long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); + int year = Year.MIN_VALUE - 1; + long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; + Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L); + OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); + }); } + @Test public void factory_ofInstant_maxYear() { doTest_factory_ofInstant_all(Year.MAX_VALUE - 420, Year.MAX_VALUE); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_tooBig() { - long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); - long year = Year.MAX_VALUE + 1L; - long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; - Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L); - OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); + Assertions.assertThrows(DateTimeException.class, () -> { + long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); + long year = Year.MAX_VALUE + 1L; + long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; + Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L); + OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); + }); } //----------------------------------------------------------------------- + @Test public void factory_ofInstant_minWithMinOffset() { long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); int year = Year.MIN_VALUE; long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L - OFFSET_MIN.getTotalSeconds()); OffsetDateTime test = OffsetDateTime.ofInstant(instant, OFFSET_MIN); - assertEquals(test.getYear(), Year.MIN_VALUE); - assertEquals(test.getMonth().getValue(), 1); - assertEquals(test.getDayOfMonth(), 1); - assertEquals(test.getOffset(), OFFSET_MIN); - assertEquals(test.getHour(), 0); - assertEquals(test.getMinute(), 0); - assertEquals(test.getSecond(), 0); - assertEquals(test.getNano(), 0); + assertEquals(Year.MIN_VALUE, test.getYear()); + assertEquals(1, test.getMonth().getValue()); + assertEquals(1, test.getDayOfMonth()); + assertEquals(OFFSET_MIN, test.getOffset()); + assertEquals(0, test.getHour()); + assertEquals(0, test.getMinute()); + assertEquals(0, test.getSecond()); + assertEquals(0, test.getNano()); } + @Test public void factory_ofInstant_minWithMaxOffset() { long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); int year = Year.MIN_VALUE; long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970; Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L - OFFSET_MAX.getTotalSeconds()); OffsetDateTime test = OffsetDateTime.ofInstant(instant, OFFSET_MAX); - assertEquals(test.getYear(), Year.MIN_VALUE); - assertEquals(test.getMonth().getValue(), 1); - assertEquals(test.getDayOfMonth(), 1); - assertEquals(test.getOffset(), OFFSET_MAX); - assertEquals(test.getHour(), 0); - assertEquals(test.getMinute(), 0); - assertEquals(test.getSecond(), 0); - assertEquals(test.getNano(), 0); + assertEquals(Year.MIN_VALUE, test.getYear()); + assertEquals(1, test.getMonth().getValue()); + assertEquals(1, test.getDayOfMonth()); + assertEquals(OFFSET_MAX, test.getOffset()); + assertEquals(0, test.getHour()); + assertEquals(0, test.getMinute()); + assertEquals(0, test.getSecond()); + assertEquals(0, test.getNano()); } + @Test public void factory_ofInstant_maxWithMinOffset() { long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); int year = Year.MAX_VALUE; long days = (year * 365L + (year / 4 - year / 100 + year / 400)) + 365 - days_0000_to_1970; Instant instant = Instant.ofEpochSecond((days + 1) * 24L * 60L * 60L - 1 - OFFSET_MIN.getTotalSeconds()); OffsetDateTime test = OffsetDateTime.ofInstant(instant, OFFSET_MIN); - assertEquals(test.getYear(), Year.MAX_VALUE); - assertEquals(test.getMonth().getValue(), 12); - assertEquals(test.getDayOfMonth(), 31); - assertEquals(test.getOffset(), OFFSET_MIN); - assertEquals(test.getHour(), 23); - assertEquals(test.getMinute(), 59); - assertEquals(test.getSecond(), 59); - assertEquals(test.getNano(), 0); + assertEquals(Year.MAX_VALUE, test.getYear()); + assertEquals(12, test.getMonth().getValue()); + assertEquals(31, test.getDayOfMonth()); + assertEquals(OFFSET_MIN, test.getOffset()); + assertEquals(23, test.getHour()); + assertEquals(59, test.getMinute()); + assertEquals(59, test.getSecond()); + assertEquals(0, test.getNano()); } + @Test public void factory_ofInstant_maxWithMaxOffset() { long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7); int year = Year.MAX_VALUE; long days = (year * 365L + (year / 4 - year / 100 + year / 400)) + 365 - days_0000_to_1970; Instant instant = Instant.ofEpochSecond((days + 1) * 24L * 60L * 60L - 1 - OFFSET_MAX.getTotalSeconds()); OffsetDateTime test = OffsetDateTime.ofInstant(instant, OFFSET_MAX); - assertEquals(test.getYear(), Year.MAX_VALUE); - assertEquals(test.getMonth().getValue(), 12); - assertEquals(test.getDayOfMonth(), 31); - assertEquals(test.getOffset(), OFFSET_MAX); - assertEquals(test.getHour(), 23); - assertEquals(test.getMinute(), 59); - assertEquals(test.getSecond(), 59); - assertEquals(test.getNano(), 0); + assertEquals(Year.MAX_VALUE, test.getYear()); + assertEquals(12, test.getMonth().getValue()); + assertEquals(31, test.getDayOfMonth()); + assertEquals(OFFSET_MAX, test.getOffset()); + assertEquals(23, test.getHour()); + assertEquals(59, test.getMinute()); + assertEquals(59, test.getSecond()); + assertEquals(0, test.getNano()); } //----------------------------------------------------------------------- - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_maxInstantWithMaxOffset() { - Instant instant = Instant.ofEpochSecond(Long.MAX_VALUE); - OffsetDateTime.ofInstant(instant, OFFSET_MAX); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant instant = Instant.ofEpochSecond(Long.MAX_VALUE); + OffsetDateTime.ofInstant(instant, OFFSET_MAX); + }); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void factory_ofInstant_maxInstantWithMinOffset() { - Instant instant = Instant.ofEpochSecond(Long.MAX_VALUE); - OffsetDateTime.ofInstant(instant, OFFSET_MIN); + Assertions.assertThrows(DateTimeException.class, () -> { + Instant instant = Instant.ofEpochSecond(Long.MAX_VALUE); + OffsetDateTime.ofInstant(instant, OFFSET_MIN); + }); } //----------------------------------------------------------------------- @@ -241,7 +260,7 @@ public class TestOffsetDateTime_instants { Instant instant = Instant.ofEpochSecond(i * 24L * 60L * 60L); try { OffsetDateTime test = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); - assertEquals(test, expected); + assertEquals(expected, test); if (expected.toLocalDate().equals(maxDate) == false) { expected = expected.plusDays(1); } @@ -282,65 +301,75 @@ public class TestOffsetDateTime_instants { // } //----------------------------------------------------------------------- + @Test public void test_toInstant_19700101() { OffsetDateTime dt = OffsetDateTime.of(LocalDate.of(1970, 1, 1), LocalTime.of(0, 0, 0, 0), ZoneOffset.UTC); Instant test = dt.toInstant(); - assertEquals(test.getEpochSecond(), 0); - assertEquals(test.getNano(), 0); + assertEquals(0, test.getEpochSecond()); + assertEquals(0, test.getNano()); } + @Test public void test_toInstant_19700101_oneNano() { OffsetDateTime dt = OffsetDateTime.of(LocalDate.of(1970, 1, 1), LocalTime.of(0, 0, 0, 1), ZoneOffset.UTC); Instant test = dt.toInstant(); - assertEquals(test.getEpochSecond(), 0); - assertEquals(test.getNano(), 1); + assertEquals(0, test.getEpochSecond()); + assertEquals(1, test.getNano()); } + @Test public void test_toInstant_19700101_minusOneNano() { OffsetDateTime dt = OffsetDateTime.of(LocalDate.of(1969, 12, 31), LocalTime.of(23, 59, 59, 999999999), ZoneOffset.UTC); Instant test = dt.toInstant(); - assertEquals(test.getEpochSecond(), -1); - assertEquals(test.getNano(), 999999999); + assertEquals(-1, test.getEpochSecond()); + assertEquals(999999999, test.getNano()); } + @Test public void test_toInstant_19700102() { OffsetDateTime dt = OffsetDateTime.of(LocalDate.of(1970, 1, 2), LocalTime.of(0, 0, 0, 0), ZoneOffset.UTC); Instant test = dt.toInstant(); - assertEquals(test.getEpochSecond(), 24L * 60L * 60L); - assertEquals(test.getNano(), 0); + assertEquals(24L * 60L * 60L, test.getEpochSecond()); + assertEquals(0, test.getNano()); } + @Test public void test_toInstant_19691231() { OffsetDateTime dt = OffsetDateTime.of(LocalDate.of(1969, 12, 31), LocalTime.of(0, 0, 0, 0), ZoneOffset.UTC); Instant test = dt.toInstant(); - assertEquals(test.getEpochSecond(), -24L * 60L * 60L); - assertEquals(test.getNano(), 0); + assertEquals(-24L * 60L * 60L, test.getEpochSecond()); + assertEquals(0, test.getNano()); } //----------------------------------------------------------------------- + @Test public void test_toEpochSecond_19700101() { OffsetDateTime dt = OffsetDateTime.of(LocalDate.of(1970, 1, 1), LocalTime.of(0, 0, 0, 0), ZoneOffset.UTC); - assertEquals(dt.toEpochSecond(), 0); + assertEquals(0, dt.toEpochSecond()); } + @Test public void test_toEpochSecond_19700101_oneNano() { OffsetDateTime dt = OffsetDateTime.of(LocalDate.of(1970, 1, 1), LocalTime.of( 0, 0, 0, 1), ZoneOffset.UTC); - assertEquals(dt.toEpochSecond(), 0); + assertEquals(0, dt.toEpochSecond()); } + @Test public void test_toEpochSecond_19700101_minusOneNano() { OffsetDateTime dt = OffsetDateTime.of(LocalDate.of(1969, 12, 31), LocalTime.of(23, 59, 59, 999999999), ZoneOffset.UTC); - assertEquals(dt.toEpochSecond(), -1); + assertEquals(-1, dt.toEpochSecond()); } + @Test public void test_toEpochSecond_19700102() { OffsetDateTime dt = OffsetDateTime.of(LocalDate.of(1970, 1, 2), LocalTime.of(0, 0, 0, 0), ZoneOffset.UTC); - assertEquals(dt.toEpochSecond(), 24L * 60L * 60L); + assertEquals(24L * 60L * 60L, dt.toEpochSecond()); } + @Test public void test_toEpochSecond_19691231() { OffsetDateTime dt = OffsetDateTime.of(LocalDate.of(1969, 12, 31), LocalTime.of(0, 0, 0, 0), ZoneOffset.UTC); - assertEquals(dt.toEpochSecond(), -24L * 60L * 60L); + assertEquals(-24L * 60L * 60L, dt.toEpochSecond()); } } diff --git a/test/jdk/java/time/test/java/time/TestOffsetTime.java b/test/jdk/java/time/test/java/time/TestOffsetTime.java index 41116a7c964..ce3a73aa987 100644 --- a/test/jdk/java/time/test/java/time/TestOffsetTime.java +++ b/test/jdk/java/time/test/java/time/TestOffsetTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -61,12 +61,11 @@ package test.java.time; import java.time.OffsetTime; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test OffsetTime. */ -@Test public class TestOffsetTime extends AbstractTest { @Test diff --git a/test/jdk/java/time/test/java/time/TestPeriod.java b/test/jdk/java/time/test/java/time/TestPeriod.java index 2c6d4030d84..a74fbf4c8d2 100644 --- a/test/jdk/java/time/test/java/time/TestPeriod.java +++ b/test/jdk/java/time/test/java/time/TestPeriod.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,17 +59,16 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import java.time.Period; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test. */ -@Test public class TestPeriod extends AbstractTest { @Test @@ -98,10 +97,10 @@ public class TestPeriod extends AbstractTest { Period test6 = Period.ofDays(6); Period test5M = Period.ofMonths(5); Period test5Y = Period.ofYears(5); - assertEquals(test5.hashCode() == test5.hashCode(), true); - assertEquals(test5.hashCode() == test6.hashCode(), false); - assertEquals(test5.hashCode() == test5M.hashCode(), false); - assertEquals(test5.hashCode() == test5Y.hashCode(), false); + assertEquals(true, test5.hashCode() == test5.hashCode()); + assertEquals(false, test5.hashCode() == test6.hashCode()); + assertEquals(false, test5.hashCode() == test5M.hashCode()); + assertEquals(false, test5.hashCode() == test5Y.hashCode()); } } diff --git a/test/jdk/java/time/test/java/time/TestYear.java b/test/jdk/java/time/test/java/time/TestYear.java index 71791ab5fa7..ddb82d91b26 100644 --- a/test/jdk/java/time/test/java/time/TestYear.java +++ b/test/jdk/java/time/test/java/time/TestYear.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -61,12 +61,11 @@ package test.java.time; import java.time.Year; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test Year. */ -@Test public class TestYear extends AbstractTest { @Test diff --git a/test/jdk/java/time/test/java/time/TestYearMonth.java b/test/jdk/java/time/test/java/time/TestYearMonth.java index 0552994b8c2..51202c902f9 100644 --- a/test/jdk/java/time/test/java/time/TestYearMonth.java +++ b/test/jdk/java/time/test/java/time/TestYearMonth.java @@ -64,15 +64,13 @@ import java.io.ObjectStreamField; import java.time.LocalDate; import java.time.YearMonth; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; /** * Test YearMonth. */ -@Test public class TestYearMonth extends AbstractTest { //----------------------------------------------------------------------- @@ -87,8 +85,8 @@ public class TestYearMonth extends AbstractTest { var osc = ObjectStreamClass.lookup(YearMonth.class); for (ObjectStreamField f : osc.getFields()) { switch (f.getName()) { - case "year" -> assertEquals(f.getType(), int.class, f.getName()); - case "month" -> assertEquals(f.getType(), int.class, f.getName()); + case "year" -> assertEquals(int.class, f.getType(), f.getName()); + case "month" -> assertEquals(int.class, f.getType(), f.getName()); default -> fail("unknown field in YearMonth: " + f.getName()); } } diff --git a/test/jdk/java/time/test/java/time/TestZoneId.java b/test/jdk/java/time/test/java/time/TestZoneId.java index df2bbbc519e..fa8727560af 100644 --- a/test/jdk/java/time/test/java/time/TestZoneId.java +++ b/test/jdk/java/time/test/java/time/TestZoneId.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,10 +59,10 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Field; import java.lang.reflect.Modifier; @@ -81,12 +81,12 @@ import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Test ZoneId. */ -@Test public class TestZoneId extends AbstractTest { private static final int OVERLAP = 2; @@ -95,6 +95,7 @@ public class TestZoneId extends AbstractTest { //----------------------------------------------------------------------- // Basics //----------------------------------------------------------------------- + @Test public void test_immutable() { // cannot use standard test as ZoneId is abstract Class cls = ZoneId.class; @@ -112,100 +113,111 @@ public class TestZoneId extends AbstractTest { //----------------------------------------------------------------------- // UTC //----------------------------------------------------------------------- + @Test public void test_constant_UTC() { ZoneId test = ZoneOffset.UTC; - assertEquals(test.getId(), "Z"); - assertEquals(test.getDisplayName(TextStyle.FULL, Locale.UK), "Z"); - assertEquals(test.getRules().isFixedOffset(), true); - assertEquals(test.getRules().getOffset(Instant.ofEpochSecond(0L)), ZoneOffset.UTC); + assertEquals("Z", test.getId()); + assertEquals("Z", test.getDisplayName(TextStyle.FULL, Locale.UK)); + assertEquals(true, test.getRules().isFixedOffset()); + assertEquals(ZoneOffset.UTC, test.getRules().getOffset(Instant.ofEpochSecond(0L))); checkOffset(test.getRules(), createLDT(2008, 6, 30), ZoneOffset.UTC, 1); } //----------------------------------------------------------------------- // system default //----------------------------------------------------------------------- + @Test public void test_systemDefault() { ZoneId test = ZoneId.systemDefault(); - assertEquals(test.getId(), TimeZone.getDefault().getID()); + assertEquals(TimeZone.getDefault().getID(), test.getId()); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_systemDefault_unableToConvert_badFormat() { - TimeZone current = TimeZone.getDefault(); - try { - TimeZone.setDefault(new SimpleTimeZone(127, "Something Weird")); - ZoneId.systemDefault(); - } finally { - TimeZone.setDefault(current); - } + Assertions.assertThrows(DateTimeException.class, () -> { + TimeZone current = TimeZone.getDefault(); + try { + TimeZone.setDefault(new SimpleTimeZone(127, "Something Weird")); + ZoneId.systemDefault(); + } finally { + TimeZone.setDefault(current); + } + }); } - @Test(expectedExceptions = ZoneRulesException.class) + @Test public void test_systemDefault_unableToConvert_unknownId() { - TimeZone current = TimeZone.getDefault(); - try { - TimeZone.setDefault(new SimpleTimeZone(127, "SomethingWeird")); - ZoneId.systemDefault(); - } finally { - TimeZone.setDefault(current); - } + Assertions.assertThrows(ZoneRulesException.class, () -> { + TimeZone current = TimeZone.getDefault(); + try { + TimeZone.setDefault(new SimpleTimeZone(127, "SomethingWeird")); + ZoneId.systemDefault(); + } finally { + TimeZone.setDefault(current); + } + }); } //----------------------------------------------------------------------- // Europe/London //----------------------------------------------------------------------- + @Test public void test_London() { ZoneId test = ZoneId.of("Europe/London"); - assertEquals(test.getId(), "Europe/London"); - assertEquals(test.getRules().isFixedOffset(), false); + assertEquals("Europe/London", test.getId()); + assertEquals(false, test.getRules().isFixedOffset()); } + @Test public void test_London_getOffset() { ZoneId test = ZoneId.of("Europe/London"); - assertEquals(test.getRules().getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC))); } + @Test public void test_London_getOffset_toDST() { ZoneId test = ZoneId.of("Europe/London"); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC))); // cutover at 01:00Z - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC))); } + @Test public void test_London_getOffset_fromDST() { ZoneId test = ZoneId.of("Europe/London"); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC))); // cutover at 01:00Z - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), ZoneOffset.ofHours(0)); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(0), test.getRules().getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC))); } + @Test public void test_London_getOffsetInfo() { ZoneId test = ZoneId.of("Europe/London"); checkOffset(test.getRules(), createLDT(2008, 1, 1), ZoneOffset.ofHours(0), 1); @@ -222,6 +234,7 @@ public class TestZoneId extends AbstractTest { checkOffset(test.getRules(), createLDT(2008, 12, 1), ZoneOffset.ofHours(0), 1); } + @Test public void test_London_getOffsetInfo_toDST() { ZoneId test = ZoneId.of("Europe/London"); checkOffset(test.getRules(), createLDT(2008, 3, 24), ZoneOffset.ofHours(0), 1); @@ -238,6 +251,7 @@ public class TestZoneId extends AbstractTest { checkOffset(test.getRules(), LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0), ZoneOffset.ofHours(1), 1); } + @Test public void test_London_getOffsetInfo_fromDST() { ZoneId test = ZoneId.of("Europe/London"); checkOffset(test.getRules(), createLDT(2008, 10, 24), ZoneOffset.ofHours(1), 1); @@ -254,22 +268,23 @@ public class TestZoneId extends AbstractTest { checkOffset(test.getRules(), LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0), ZoneOffset.ofHours(0), 1); } + @Test public void test_London_getOffsetInfo_gap() { ZoneId test = ZoneId.of("Europe/London"); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test.getRules(), dateTime, ZoneOffset.ofHours(0), GAP); - assertEquals(trans.isGap(), true); - assertEquals(trans.isOverlap(), false); - assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(0)); - assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(1)); - assertEquals(trans.getInstant(), dateTime.toInstant(ZoneOffset.UTC)); - assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 3, 30, 1, 0)); - assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 3, 30, 2, 0)); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(0)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(1)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(2)), false); - assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T01:00Z to +01:00]"); + assertEquals(true, trans.isGap()); + assertEquals(false, trans.isOverlap()); + assertEquals(ZoneOffset.ofHours(0), trans.getOffsetBefore()); + assertEquals(ZoneOffset.ofHours(1), trans.getOffsetAfter()); + assertEquals(dateTime.toInstant(ZoneOffset.UTC), trans.getInstant()); + assertEquals(LocalDateTime.of(2008, 3, 30, 1, 0), trans.getDateTimeBefore()); + assertEquals(LocalDateTime.of(2008, 3, 30, 2, 0), trans.getDateTimeAfter()); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-1))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(0))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(1))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(2))); + assertEquals("Transition[Gap at 2008-03-30T01:00Z to +01:00]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(0))); @@ -277,25 +292,26 @@ public class TestZoneId extends AbstractTest { final ZoneOffsetTransition otherTrans = test.getRules().getTransition(dateTime); assertTrue(trans.equals(otherTrans)); - assertEquals(trans.hashCode(), otherTrans.hashCode()); + assertEquals(otherTrans.hashCode(), trans.hashCode()); } + @Test public void test_London_getOffsetInfo_overlap() { ZoneId test = ZoneId.of("Europe/London"); final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test.getRules(), dateTime, ZoneOffset.ofHours(1), OVERLAP); - assertEquals(trans.isGap(), false); - assertEquals(trans.isOverlap(), true); - assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(1)); - assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(0)); - assertEquals(trans.getInstant(), dateTime.toInstant(ZoneOffset.UTC)); - assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 10, 26, 2, 0)); - assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 10, 26, 1, 0)); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(0)), true); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(1)), true); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(2)), false); - assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T02:00+01:00 to Z]"); + assertEquals(false, trans.isGap()); + assertEquals(true, trans.isOverlap()); + assertEquals(ZoneOffset.ofHours(1), trans.getOffsetBefore()); + assertEquals(ZoneOffset.ofHours(0), trans.getOffsetAfter()); + assertEquals(dateTime.toInstant(ZoneOffset.UTC), trans.getInstant()); + assertEquals(LocalDateTime.of(2008, 10, 26, 2, 0), trans.getDateTimeBefore()); + assertEquals(LocalDateTime.of(2008, 10, 26, 1, 0), trans.getDateTimeAfter()); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-1))); + assertEquals(true, trans.isValidOffset(ZoneOffset.ofHours(0))); + assertEquals(true, trans.isValidOffset(ZoneOffset.ofHours(1))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(2))); + assertEquals("Transition[Overlap at 2008-10-26T02:00+01:00 to Z]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(1))); @@ -303,64 +319,69 @@ public class TestZoneId extends AbstractTest { final ZoneOffsetTransition otherTrans = test.getRules().getTransition(dateTime); assertTrue(trans.equals(otherTrans)); - assertEquals(trans.hashCode(), otherTrans.hashCode()); + assertEquals(otherTrans.hashCode(), trans.hashCode()); } //----------------------------------------------------------------------- // Europe/Paris //----------------------------------------------------------------------- + @Test public void test_Paris() { ZoneId test = ZoneId.of("Europe/Paris"); - assertEquals(test.getId(), "Europe/Paris"); - assertEquals(test.getRules().isFixedOffset(), false); + assertEquals("Europe/Paris", test.getId()); + assertEquals(false, test.getRules().isFixedOffset()); } + @Test public void test_Paris_getOffset() { ZoneId test = ZoneId.of("Europe/Paris"); - assertEquals(test.getRules().getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC))); } + @Test public void test_Paris_getOffset_toDST() { ZoneId test = ZoneId.of("Europe/Paris"); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC))); // cutover at 01:00Z - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC))); } + @Test public void test_Paris_getOffset_fromDST() { ZoneId test = ZoneId.of("Europe/Paris"); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC))); // cutover at 01:00Z - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), ZoneOffset.ofHours(2)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), ZoneOffset.ofHours(1)); + assertEquals(ZoneOffset.ofHours(2), test.getRules().getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC))); + assertEquals(ZoneOffset.ofHours(1), test.getRules().getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC))); } + @Test public void test_Paris_getOffsetInfo() { ZoneId test = ZoneId.of("Europe/Paris"); checkOffset(test.getRules(), createLDT(2008, 1, 1), ZoneOffset.ofHours(1), 1); @@ -377,6 +398,7 @@ public class TestZoneId extends AbstractTest { checkOffset(test.getRules(), createLDT(2008, 12, 1), ZoneOffset.ofHours(1), 1); } + @Test public void test_Paris_getOffsetInfo_toDST() { ZoneId test = ZoneId.of("Europe/Paris"); checkOffset(test.getRules(), createLDT(2008, 3, 24), ZoneOffset.ofHours(1), 1); @@ -393,6 +415,7 @@ public class TestZoneId extends AbstractTest { checkOffset(test.getRules(), LocalDateTime.of(2008, 3, 30, 3, 0, 0, 0), ZoneOffset.ofHours(2), 1); } + @Test public void test_Paris_getOffsetInfo_fromDST() { ZoneId test = ZoneId.of("Europe/Paris"); checkOffset(test.getRules(), createLDT(2008, 10, 24), ZoneOffset.ofHours(2), 1); @@ -409,20 +432,21 @@ public class TestZoneId extends AbstractTest { checkOffset(test.getRules(), LocalDateTime.of(2008, 10, 26, 3, 0, 0, 0), ZoneOffset.ofHours(1), 1); } + @Test public void test_Paris_getOffsetInfo_gap() { ZoneId test = ZoneId.of("Europe/Paris"); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test.getRules(), dateTime, ZoneOffset.ofHours(1), GAP); - assertEquals(trans.isGap(), true); - assertEquals(trans.isOverlap(), false); - assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(1)); - assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(2)); - assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(0)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(1)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(2)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(3)), false); - assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T02:00+01:00 to +02:00]"); + assertEquals(true, trans.isGap()); + assertEquals(false, trans.isOverlap()); + assertEquals(ZoneOffset.ofHours(1), trans.getOffsetBefore()); + assertEquals(ZoneOffset.ofHours(2), trans.getOffsetAfter()); + assertEquals(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC), trans.getInstant()); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(0))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(1))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(2))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(3))); + assertEquals("Transition[Gap at 2008-03-30T02:00+01:00 to +02:00]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(1))); @@ -430,23 +454,24 @@ public class TestZoneId extends AbstractTest { final ZoneOffsetTransition otherDis = test.getRules().getTransition(dateTime); assertTrue(trans.equals(otherDis)); - assertEquals(trans.hashCode(), otherDis.hashCode()); + assertEquals(otherDis.hashCode(), trans.hashCode()); } + @Test public void test_Paris_getOffsetInfo_overlap() { ZoneId test = ZoneId.of("Europe/Paris"); final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test.getRules(), dateTime, ZoneOffset.ofHours(2), OVERLAP); - assertEquals(trans.isGap(), false); - assertEquals(trans.isOverlap(), true); - assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(2)); - assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(1)); - assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(0)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(1)), true); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(2)), true); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(3)), false); - assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T03:00+02:00 to +01:00]"); + assertEquals(false, trans.isGap()); + assertEquals(true, trans.isOverlap()); + assertEquals(ZoneOffset.ofHours(2), trans.getOffsetBefore()); + assertEquals(ZoneOffset.ofHours(1), trans.getOffsetAfter()); + assertEquals(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC), trans.getInstant()); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(0))); + assertEquals(true, trans.isValidOffset(ZoneOffset.ofHours(1))); + assertEquals(true, trans.isValidOffset(ZoneOffset.ofHours(2))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(3))); + assertEquals("Transition[Overlap at 2008-10-26T03:00+02:00 to +01:00]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(2))); @@ -454,77 +479,82 @@ public class TestZoneId extends AbstractTest { final ZoneOffsetTransition otherDis = test.getRules().getTransition(dateTime); assertTrue(trans.equals(otherDis)); - assertEquals(trans.hashCode(), otherDis.hashCode()); + assertEquals(otherDis.hashCode(), trans.hashCode()); } //----------------------------------------------------------------------- // America/New_York //----------------------------------------------------------------------- + @Test public void test_NewYork() { ZoneId test = ZoneId.of("America/New_York"); - assertEquals(test.getId(), "America/New_York"); - assertEquals(test.getRules().isFixedOffset(), false); + assertEquals("America/New_York", test.getId()); + assertEquals(false, test.getRules().isFixedOffset()); } + @Test public void test_NewYork_getOffset() { ZoneId test = ZoneId.of("America/New_York"); ZoneOffset offset = ZoneOffset.ofHours(-5); - assertEquals(test.getRules().getOffset(createInstant(2008, 1, 1, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 2, 1, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 1, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 4, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 5, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 6, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 7, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 8, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 9, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 12, 1, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 1, 28, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 2, 28, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 4, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 5, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 6, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 7, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 8, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 9, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 10, 28, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 28, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 12, 28, offset)), ZoneOffset.ofHours(-5)); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 1, 1, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 2, 1, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 3, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 4, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 5, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 6, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 7, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 8, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 9, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 10, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 11, 1, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 12, 1, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 1, 28, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 2, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 3, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 4, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 5, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 6, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 7, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 8, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 9, 28, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 10, 28, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 11, 28, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 12, 28, offset))); } + @Test public void test_NewYork_getOffset_toDST() { ZoneId test = ZoneId.of("America/New_York"); ZoneOffset offset = ZoneOffset.ofHours(-5); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 8, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 9, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 10, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 11, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 12, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 13, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 14, offset)), ZoneOffset.ofHours(-4)); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 3, 8, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 3, 9, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 3, 10, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 3, 11, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 3, 12, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 3, 13, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 3, 14, offset))); // cutover at 02:00 local - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 9, 1, 59, 59, 999999999, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 3, 9, 2, 0, 0, 0, offset)), ZoneOffset.ofHours(-4)); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 3, 9, 1, 59, 59, 999999999, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 3, 9, 2, 0, 0, 0, offset))); } + @Test public void test_NewYork_getOffset_fromDST() { ZoneId test = ZoneId.of("America/New_York"); ZoneOffset offset = ZoneOffset.ofHours(-4); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 1, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 2, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 3, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 4, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 5, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 6, offset)), ZoneOffset.ofHours(-5)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 7, offset)), ZoneOffset.ofHours(-5)); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 11, 1, offset))); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 11, 2, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 11, 3, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 11, 4, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 11, 5, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 11, 6, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 11, 7, offset))); // cutover at 02:00 local - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 2, 1, 59, 59, 999999999, offset)), ZoneOffset.ofHours(-4)); - assertEquals(test.getRules().getOffset(createInstant(2008, 11, 2, 2, 0, 0, 0, offset)), ZoneOffset.ofHours(-5)); + assertEquals(ZoneOffset.ofHours(-4), test.getRules().getOffset(createInstant(2008, 11, 2, 1, 59, 59, 999999999, offset))); + assertEquals(ZoneOffset.ofHours(-5), test.getRules().getOffset(createInstant(2008, 11, 2, 2, 0, 0, 0, offset))); } + @Test public void test_NewYork_getOffsetInfo() { ZoneId test = ZoneId.of("America/New_York"); checkOffset(test.getRules(), createLDT(2008, 1, 1), ZoneOffset.ofHours(-5), 1); @@ -553,6 +583,7 @@ public class TestZoneId extends AbstractTest { checkOffset(test.getRules(), createLDT(2008, 12, 28), ZoneOffset.ofHours(-5), 1); } + @Test public void test_NewYork_getOffsetInfo_toDST() { ZoneId test = ZoneId.of("America/New_York"); checkOffset(test.getRules(), createLDT(2008, 3, 8), ZoneOffset.ofHours(-5), 1); @@ -568,6 +599,7 @@ public class TestZoneId extends AbstractTest { checkOffset(test.getRules(), LocalDateTime.of(2008, 3, 9, 3, 0, 0, 0), ZoneOffset.ofHours(-4), 1); } + @Test public void test_NewYork_getOffsetInfo_fromDST() { ZoneId test = ZoneId.of("America/New_York"); checkOffset(test.getRules(), createLDT(2008, 11, 1), ZoneOffset.ofHours(-4), 1); @@ -583,18 +615,19 @@ public class TestZoneId extends AbstractTest { checkOffset(test.getRules(), LocalDateTime.of(2008, 11, 2, 2, 0, 0, 0), ZoneOffset.ofHours(-5), 1); } + @Test public void test_NewYork_getOffsetInfo_gap() { ZoneId test = ZoneId.of("America/New_York"); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 9, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test.getRules(), dateTime, ZoneOffset.ofHours(-5), GAP); - assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-5)); - assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-4)); - assertEquals(trans.getInstant(), createInstant(2008, 3, 9, 2, 0, 0, 0, ZoneOffset.ofHours(-5))); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-6)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-3)), false); - assertEquals(trans.toString(), "Transition[Gap at 2008-03-09T02:00-05:00 to -04:00]"); + assertEquals(ZoneOffset.ofHours(-5), trans.getOffsetBefore()); + assertEquals(ZoneOffset.ofHours(-4), trans.getOffsetAfter()); + assertEquals(createInstant(2008, 3, 9, 2, 0, 0, 0, ZoneOffset.ofHours(-5)), trans.getInstant()); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-6))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-5))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-4))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-3))); + assertEquals("Transition[Gap at 2008-03-09T02:00-05:00 to -04:00]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(-5))); @@ -603,21 +636,22 @@ public class TestZoneId extends AbstractTest { final ZoneOffsetTransition otherTrans = test.getRules().getTransition(dateTime); assertTrue(trans.equals(otherTrans)); - assertEquals(trans.hashCode(), otherTrans.hashCode()); + assertEquals(otherTrans.hashCode(), trans.hashCode()); } + @Test public void test_NewYork_getOffsetInfo_overlap() { ZoneId test = ZoneId.of("America/New_York"); final LocalDateTime dateTime = LocalDateTime.of(2008, 11, 2, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test.getRules(), dateTime, ZoneOffset.ofHours(-4), OVERLAP); - assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-4)); - assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-5)); - assertEquals(trans.getInstant(), createInstant(2008, 11, 2, 2, 0, 0, 0, ZoneOffset.ofHours(-4))); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), true); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), true); - assertEquals(trans.isValidOffset(ZoneOffset.ofHours(2)), false); - assertEquals(trans.toString(), "Transition[Overlap at 2008-11-02T02:00-04:00 to -05:00]"); + assertEquals(ZoneOffset.ofHours(-4), trans.getOffsetBefore()); + assertEquals(ZoneOffset.ofHours(-5), trans.getOffsetAfter()); + assertEquals(createInstant(2008, 11, 2, 2, 0, 0, 0, ZoneOffset.ofHours(-4)), trans.getInstant()); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(-1))); + assertEquals(true, trans.isValidOffset(ZoneOffset.ofHours(-5))); + assertEquals(true, trans.isValidOffset(ZoneOffset.ofHours(-4))); + assertEquals(false, trans.isValidOffset(ZoneOffset.ofHours(2))); + assertEquals("Transition[Overlap at 2008-11-02T02:00-04:00 to -05:00]", trans.toString()); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(-4))); @@ -626,22 +660,24 @@ public class TestZoneId extends AbstractTest { final ZoneOffsetTransition otherTrans = test.getRules().getTransition(dateTime); assertTrue(trans.equals(otherTrans)); - assertEquals(trans.hashCode(), otherTrans.hashCode()); + assertEquals(otherTrans.hashCode(), trans.hashCode()); } //----------------------------------------------------------------------- // getXxx() isXxx() //----------------------------------------------------------------------- + @Test public void test_get_Tzdb() { ZoneId test = ZoneId.of("Europe/London"); - assertEquals(test.getId(), "Europe/London"); - assertEquals(test.getRules().isFixedOffset(), false); + assertEquals("Europe/London", test.getId()); + assertEquals(false, test.getRules().isFixedOffset()); } + @Test public void test_get_TzdbFixed() { ZoneId test = ZoneId.of("+01:30"); - assertEquals(test.getId(), "+01:30"); - assertEquals(test.getRules().isFixedOffset(), true); + assertEquals("+01:30", test.getId()); + assertEquals(true, test.getRules().isFixedOffset()); } //----------------------------------------------------------------------- @@ -665,17 +701,17 @@ public class TestZoneId extends AbstractTest { private ZoneOffsetTransition checkOffset(ZoneRules rules, LocalDateTime dateTime, ZoneOffset offset, int type) { List validOffsets = rules.getValidOffsets(dateTime); - assertEquals(validOffsets.size(), type); - assertEquals(rules.getOffset(dateTime), offset); + assertEquals(type, validOffsets.size()); + assertEquals(offset, rules.getOffset(dateTime)); if (type == 1) { - assertEquals(validOffsets.get(0), offset); + assertEquals(offset, validOffsets.get(0)); return null; } else { ZoneOffsetTransition zot = rules.getTransition(dateTime); assertNotNull(zot); - assertEquals(zot.isOverlap(), type == 2); - assertEquals(zot.isGap(), type == 0); - assertEquals(zot.isValidOffset(offset), type == 2); + assertEquals(type == 2, zot.isOverlap()); + assertEquals(type == 0, zot.isGap()); + assertEquals(type == 2, zot.isValidOffset(offset)); return zot; } } diff --git a/test/jdk/java/time/test/java/time/TestZoneOffset.java b/test/jdk/java/time/test/java/time/TestZoneOffset.java index b85a629aefc..8a42fe2a0ab 100644 --- a/test/jdk/java/time/test/java/time/TestZoneOffset.java +++ b/test/jdk/java/time/test/java/time/TestZoneOffset.java @@ -60,17 +60,16 @@ */ package test.java.time; -import static org.testng.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; import java.util.Set; import java.time.ZoneOffset; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test ZoneOffset. */ -@Test public class TestZoneOffset extends AbstractTest { @Test diff --git a/test/jdk/java/time/test/java/time/TestZonedDateTime.java b/test/jdk/java/time/test/java/time/TestZonedDateTime.java index 15a95d1f3bc..436187cf3d0 100644 --- a/test/jdk/java/time/test/java/time/TestZonedDateTime.java +++ b/test/jdk/java/time/test/java/time/TestZonedDateTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,21 +59,20 @@ */ package test.java.time; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Duration; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.ZoneId; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test ZonedDateTime. * * @bug 8211990 */ -@Test public class TestZonedDateTime extends AbstractTest { @Test @@ -89,6 +88,6 @@ public class TestZonedDateTime extends AbstractTest { ZonedDateTime end = ZonedDateTime.of(LocalDateTime.MAX, sanJose); ZonedDateTime start = end.withZoneSameLocal(tokyo); - assertEquals(Duration.between(start, end), Duration.ofHours(17)); + assertEquals(Duration.ofHours(17), Duration.between(start, end)); } } diff --git a/test/jdk/java/time/test/java/time/chrono/TestChronoLocalDate.java b/test/jdk/java/time/test/java/time/chrono/TestChronoLocalDate.java index 79410941206..bb738feee05 100644 --- a/test/jdk/java/time/test/java/time/chrono/TestChronoLocalDate.java +++ b/test/jdk/java/time/test/java/time/chrono/TestChronoLocalDate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,8 +54,8 @@ */ package test.java.time.chrono; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.LocalDate; import java.time.LocalDateTime; @@ -69,16 +69,16 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test chrono local date. */ -@Test public class TestChronoLocalDate { // this class primarily tests whether the generics work OK //----------------------------------------------------------------------- + @Test public void test_date_comparator_checkGenerics_ISO() { List dates = new ArrayList<>(); ChronoLocalDate date = LocalDate.of(2013, 1, 1); @@ -99,10 +99,11 @@ public class TestChronoLocalDate { List copy = new ArrayList<>(dates); Collections.shuffle(copy); Collections.sort(copy, ChronoLocalDate.timeLineOrder()); - assertEquals(copy, dates); + assertEquals(dates, copy); assertTrue(ChronoLocalDate.timeLineOrder().compare(copy.get(0), copy.get(1)) < 0); } + @Test public void test_date_comparator_checkGenerics_LocalDate() { List dates = new ArrayList<>(); LocalDate date = LocalDate.of(2013, 1, 1); @@ -123,11 +124,12 @@ public class TestChronoLocalDate { List copy = new ArrayList<>(dates); Collections.shuffle(copy); Collections.sort(copy, ChronoLocalDate.timeLineOrder()); - assertEquals(copy, dates); + assertEquals(dates, copy); assertTrue(ChronoLocalDate.timeLineOrder().compare(copy.get(0), copy.get(1)) < 0); } //----------------------------------------------------------------------- + @Test public void test_date_checkGenerics_genericsMethod() { Chronology chrono = ThaiBuddhistChronology.INSTANCE; ChronoLocalDate date = chrono.dateNow(); @@ -138,6 +140,7 @@ public class TestChronoLocalDate { date = processClassWeird(ThaiBuddhistDate.class); } + @Test public void test_date_checkGenerics_genericsMethod_concreteType() { ThaiBuddhistChronology chrono = ThaiBuddhistChronology.INSTANCE; ThaiBuddhistDate date = chrono.dateNow(); @@ -149,6 +152,7 @@ public class TestChronoLocalDate { // date = processClassWeird(ThaiBuddhistDate.class); // does not compile (correct) } + @Test public void test_date_checkGenerics_genericsMethod_withType() { Chronology chrono = ThaiBuddhistChronology.INSTANCE; @SuppressWarnings("unchecked") @@ -180,6 +184,7 @@ public class TestChronoLocalDate { return null; } + @Test public void test_date_checkGenerics_chronoLocalDateTime1() { LocalDateTime now = LocalDateTime.now(); Chronology chrono = ThaiBuddhistChronology.INSTANCE; @@ -187,6 +192,7 @@ public class TestChronoLocalDate { ldt = processCLDT(ldt); } + @Test public void test_date_checkGenerics_chronoLocalDateTime2() { LocalDateTime now = LocalDateTime.now(); Chronology chrono = ThaiBuddhistChronology.INSTANCE; diff --git a/test/jdk/java/time/test/java/time/chrono/TestChronologyPerf.java b/test/jdk/java/time/test/java/time/chrono/TestChronologyPerf.java index 5026ebf1700..ab6bdd7ee1d 100644 --- a/test/jdk/java/time/test/java/time/chrono/TestChronologyPerf.java +++ b/test/jdk/java/time/test/java/time/chrono/TestChronologyPerf.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -29,7 +29,7 @@ import java.time.chrono.HijrahDate; import java.time.temporal.ChronoUnit; import java.util.Set; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test the speed of initializing all calendars. diff --git a/test/jdk/java/time/test/java/time/chrono/TestEraDisplayName.java b/test/jdk/java/time/test/java/time/chrono/TestEraDisplayName.java index 4e20ceb5495..99cd7499adb 100644 --- a/test/jdk/java/time/test/java/time/chrono/TestEraDisplayName.java +++ b/test/jdk/java/time/test/java/time/chrono/TestEraDisplayName.java @@ -30,10 +30,11 @@ import java.util.Arrays; import java.util.Locale; import java.util.stream.Stream; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests Era.getDisplayName() correctly returns the name based on each @@ -42,7 +43,7 @@ import static org.testng.Assert.assertFalse; * * @bug 8171049 8224105 8240626 8354548 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestEraDisplayName { private static final Locale THAI = Locale.forLanguageTag("th-TH"); private static final Locale EGYPT = Locale.forLanguageTag("ar-EG"); @@ -52,7 +53,6 @@ public class TestEraDisplayName { DateTimeFormatter.ofPattern("yyyy MM dd GGGG G GGGGG") .withChronology(JapaneseChronology.INSTANCE); - @DataProvider(name="eraDisplayName") Object[][] eraDisplayName() { return new Object[][] { // Era, text style, displyay locale, expected name @@ -141,7 +141,6 @@ public class TestEraDisplayName { }; } - @DataProvider Object[][] allLocales() { return Arrays.stream(Locale.getAvailableLocales()) .map(Stream::of) @@ -149,7 +148,6 @@ public class TestEraDisplayName { .toArray(Object[][]::new); } - @DataProvider Object[][] allEras() { return Stream.of(IsoEra.values(), JapaneseEra.values(), @@ -162,29 +160,28 @@ public class TestEraDisplayName { .toArray(Object[][]::new); } - @Test(dataProvider="eraDisplayName") + @ParameterizedTest + @MethodSource("eraDisplayName") public void test_eraDisplayName(Era era, TextStyle style, Locale locale, String expected) { - assertEquals(era.getDisplayName(style, locale), expected); + assertEquals(expected, era.getDisplayName(style, locale)); } - @Test(dataProvider="allLocales") + @ParameterizedTest + @MethodSource("allLocales") public void test_reiwaNames(Locale locale) throws DateTimeParseException { DateTimeFormatter f = JAPANESE_FORMATTER.withLocale(locale); - assertEquals(LocalDate.parse(REIWA_1ST.format(f), f), REIWA_1ST); + assertEquals(REIWA_1ST, LocalDate.parse(REIWA_1ST.format(f), f)); } // Make sure era display names aren't empty // @bug 8240626 - @Test(dataProvider="allEras") + @ParameterizedTest + @MethodSource("allEras") public void test_noEmptyEraNames(Era era) { Arrays.stream(Locale.getAvailableLocales()) - .forEach(l -> { - Arrays.stream(TextStyle.values()) - .forEach(s -> { - assertFalse(era.getDisplayName(s, l).isEmpty(), - "getDisplayName() returns empty display name for era: " + era - + ", style: " + s + ", locale: " + l); - }); - }); + .forEach(l -> Arrays.stream(TextStyle.values()) + .forEach(s -> assertFalse(era.getDisplayName(s, l).isEmpty(), + "getDisplayName() returns empty display name for era: " + era + + ", style: " + s + ", locale: " + l))); } } diff --git a/test/jdk/java/time/test/java/time/chrono/TestExampleCode.java b/test/jdk/java/time/test/java/time/chrono/TestExampleCode.java index 5258a0b8062..b4e3c41d5e3 100644 --- a/test/jdk/java/time/test/java/time/chrono/TestExampleCode.java +++ b/test/jdk/java/time/test/java/time/chrono/TestExampleCode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -55,7 +55,7 @@ package test.java.time.chrono; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDate; import java.time.LocalTime; @@ -72,13 +72,16 @@ import java.time.temporal.ChronoUnit; import java.util.Locale; import java.util.Set; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test case verify that the example code in the package-info.java compiles * and runs. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestExampleCode { @Test @@ -113,14 +116,14 @@ public class TestExampleCode { //----------------------------------------------------------------------- // Data provider for Hijrah Type names //----------------------------------------------------------------------- - @DataProvider(name = "HijrahTypeNames") Object[][] data_of_ummalqura() { return new Object[][]{ { "Hijrah-umalqura", "islamic-umalqura"}, }; } - @Test(dataProvider= "HijrahTypeNames") + @ParameterizedTest + @MethodSource("data_of_ummalqura") public void test_HijrahTypeViaLocale(String calendarId, String calendarType) { Locale.Builder builder = new Locale.Builder(); builder.setLanguage("en").setRegion("US"); @@ -130,7 +133,7 @@ public class TestExampleCode { System.out.printf(" Locale language tag: %s, Chronology ID: %s, type: %s%n", locale.toLanguageTag(), chrono, chrono.getCalendarType()); Chronology expected = Chronology.of(calendarId); - assertEquals(chrono, expected, "Expected chronology not found"); + assertEquals(expected, chrono, "Expected chronology not found"); } @Test diff --git a/test/jdk/java/time/test/java/time/chrono/TestIsoChronoImpl.java b/test/jdk/java/time/test/java/time/chrono/TestIsoChronoImpl.java index 59f5016a6fc..adc8949e61e 100644 --- a/test/jdk/java/time/test/java/time/chrono/TestIsoChronoImpl.java +++ b/test/jdk/java/time/test/java/time/chrono/TestIsoChronoImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -58,7 +58,8 @@ import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoField.YEAR_OF_ERA; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DayOfWeek; import java.time.LocalDate; @@ -69,16 +70,16 @@ import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestIsoChronoImpl { - @DataProvider(name = "RangeVersusCalendar") Object[][] provider_rangeVersusCalendar() { return new Object[][]{ {LocalDate.of(1583, 1, 1), LocalDate.of(2100, 1, 1)}, @@ -88,10 +89,11 @@ public class TestIsoChronoImpl { //----------------------------------------------------------------------- // Verify ISO Calendar matches java.util.Calendar for range //----------------------------------------------------------------------- - @Test(dataProvider = "RangeVersusCalendar") + @ParameterizedTest + @MethodSource("provider_rangeVersusCalendar") public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) { GregorianCalendar cal = new GregorianCalendar(); - assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type"); + assertEquals("gregory", cal.getCalendarType(), "Unexpected calendar type"); LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate); cal.setTimeZone(TimeZone.getTimeZone("GMT+00")); @@ -100,9 +102,9 @@ public class TestIsoChronoImpl { cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH)); while (isoDate.isBefore(isoEndDate)) { - assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + "; cal: " + cal); - assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate); - assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate); + assertEquals(cal.get(Calendar.DAY_OF_MONTH), isoDate.get(DAY_OF_MONTH), "Day mismatch in " + isoDate + "; cal: " + cal); + assertEquals(cal.get(Calendar.MONTH) + 1, isoDate.get(MONTH_OF_YEAR), "Month mismatch in " + isoDate); + assertEquals(cal.get(Calendar.YEAR), isoDate.get(YEAR_OF_ERA), "Year mismatch in " + isoDate); isoDate = isoDate.plus(1, ChronoUnit.DAYS); cal.add(Calendar.DAY_OF_MONTH, 1); @@ -113,10 +115,11 @@ public class TestIsoChronoImpl { // Verify ISO Calendar matches java.util.Calendar // DayOfWeek, WeekOfMonth, WeekOfYear for range //----------------------------------------------------------------------- - @Test(dataProvider = "RangeVersusCalendar") + @ParameterizedTest + @MethodSource("provider_rangeVersusCalendar") public void test_DayOfWeek_IsoChronology_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) { GregorianCalendar cal = new GregorianCalendar(); - assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type"); + assertEquals("gregory", cal.getCalendarType(), "Unexpected calendar type"); LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate); for (DayOfWeek firstDayOfWeek : DayOfWeek.values()) { @@ -132,29 +135,29 @@ public class TestIsoChronoImpl { // For every date in the range while (isoDate.isBefore(isoEndDate)) { - assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + "; cal: " + cal); - assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate); - assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate); + assertEquals(cal.get(Calendar.DAY_OF_MONTH), isoDate.get(DAY_OF_MONTH), "Day mismatch in " + isoDate + "; cal: " + cal); + assertEquals(cal.get(Calendar.MONTH) + 1, isoDate.get(MONTH_OF_YEAR), "Month mismatch in " + isoDate); + assertEquals(cal.get(Calendar.YEAR), isoDate.get(YEAR_OF_ERA), "Year mismatch in " + isoDate); int jdow = Math.floorMod(cal.get(Calendar.DAY_OF_WEEK) - 2, 7) + 1; int dow = isoDate.get(weekDef.dayOfWeek()); - assertEquals(jdow, dow, "Calendar DayOfWeek does not match ISO DayOfWeek"); + assertEquals(dow, jdow, "Calendar DayOfWeek does not match ISO DayOfWeek"); int jweekOfMonth = cal.get(Calendar.WEEK_OF_MONTH); int isoWeekOfMonth = isoDate.get(weekDef.weekOfMonth()); - assertEquals(jweekOfMonth, isoWeekOfMonth, "Calendar WeekOfMonth does not match ISO WeekOfMonth"); + assertEquals(isoWeekOfMonth, jweekOfMonth, "Calendar WeekOfMonth does not match ISO WeekOfMonth"); int jweekOfYear = cal.get(Calendar.WEEK_OF_YEAR); int weekOfYear = isoDate.get(weekDef.weekOfWeekBasedYear()); - assertEquals(jweekOfYear, weekOfYear, "GregorianCalendar WeekOfYear does not match WeekOfWeekBasedYear"); + assertEquals(weekOfYear, jweekOfYear, "GregorianCalendar WeekOfYear does not match WeekOfWeekBasedYear"); int jWeekYear = cal.getWeekYear(); int weekBasedYear = isoDate.get(weekDef.weekBasedYear()); - assertEquals(jWeekYear, weekBasedYear, "GregorianCalendar getWeekYear does not match YearOfWeekBasedYear"); + assertEquals(weekBasedYear, jWeekYear, "GregorianCalendar getWeekYear does not match YearOfWeekBasedYear"); int jweeksInWeekyear = cal.getWeeksInWeekYear(); int weeksInWeekBasedYear = (int)isoDate.range(weekDef.weekOfWeekBasedYear()).getMaximum(); - assertEquals(jweeksInWeekyear, weeksInWeekBasedYear, "length of weekBasedYear"); + assertEquals(weeksInWeekBasedYear, jweeksInWeekyear, "length of weekBasedYear"); isoDate = isoDate.plus(1, ChronoUnit.DAYS); cal.add(Calendar.DAY_OF_MONTH, 1); diff --git a/test/jdk/java/time/test/java/time/chrono/TestJapaneseChronoImpl.java b/test/jdk/java/time/test/java/time/chrono/TestJapaneseChronoImpl.java index fc2fa9798af..6ed24d579dd 100644 --- a/test/jdk/java/time/test/java/time/chrono/TestJapaneseChronoImpl.java +++ b/test/jdk/java/time/test/java/time/chrono/TestJapaneseChronoImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,7 +54,7 @@ */ package test.java.time.chrono; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDate; import java.time.LocalTime; @@ -71,19 +71,20 @@ import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestJapaneseChronoImpl { /** * Range of years to check consistency with java.util.Calendar */ - @DataProvider(name="RangeVersusCalendar") Object[][] provider_rangeVersusCalendar() { return new Object[][] { {LocalDate.of(1873, 1, 1), LocalDate.of(2100, 1, 1)}, @@ -93,13 +94,14 @@ public class TestJapaneseChronoImpl { //----------------------------------------------------------------------- // Verify Japanese Calendar matches java.util.Calendar for range //----------------------------------------------------------------------- - @Test(dataProvider="RangeVersusCalendar") + @ParameterizedTest + @MethodSource("provider_rangeVersusCalendar") public void test_JapaneseChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) { Locale locale = Locale.forLanguageTag("ja-JP-u-ca-japanese"); - assertEquals(locale.toString(), "ja_JP_#u-ca-japanese", "Unexpected locale"); + assertEquals("ja_JP_#u-ca-japanese", locale.toString(), "Unexpected locale"); Calendar cal = java.util.Calendar.getInstance(locale); - assertEquals(cal.getCalendarType(), "japanese", "Unexpected calendar type"); + assertEquals("japanese", cal.getCalendarType(), "Unexpected calendar type"); JapaneseDate jDate = JapaneseChronology.INSTANCE.date(isoStartDate); @@ -110,9 +112,9 @@ public class TestJapaneseChronoImpl { cal.setTimeInMillis(millis); while (jDate.isBefore(isoEndDate)) { - assertEquals(jDate.get(ChronoField.DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + jDate + "; cal: " + cal); - assertEquals(jDate.get(ChronoField.MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + jDate); - assertEquals(jDate.get(ChronoField.YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + jDate); + assertEquals(cal.get(Calendar.DAY_OF_MONTH), jDate.get(ChronoField.DAY_OF_MONTH), "Day mismatch in " + jDate + "; cal: " + cal); + assertEquals(cal.get(Calendar.MONTH) + 1, jDate.get(ChronoField.MONTH_OF_YEAR), "Month mismatch in " + jDate); + assertEquals(cal.get(Calendar.YEAR), jDate.get(ChronoField.YEAR_OF_ERA), "Year mismatch in " + jDate); jDate = jDate.plus(1, ChronoUnit.DAYS); cal.add(Calendar.DAY_OF_MONTH, 1); @@ -136,11 +138,11 @@ public class TestJapaneseChronoImpl { cal.setTimeZone(TimeZone.getTimeZone("GMT+00")); cal.setTimeInMillis(millis); - assertEquals(jd.get(ChronoField.DAY_OF_YEAR), cal.get(Calendar.DAY_OF_YEAR), + assertEquals(cal.get(Calendar.DAY_OF_YEAR), jd.get(ChronoField.DAY_OF_YEAR), "different DAY_OF_YEAR values in " + era + ", year: " + year); - assertEquals(jd.range(ChronoField.DAY_OF_YEAR).getMaximum(), cal.getActualMaximum(Calendar.DAY_OF_YEAR), + assertEquals(cal.getActualMaximum(Calendar.DAY_OF_YEAR), jd.range(ChronoField.DAY_OF_YEAR).getMaximum(), "different maximum for DAY_OF_YEAR in " + era + ", year: " + year); - assertEquals(jd.range(ChronoField.DAY_OF_YEAR).getMinimum(), cal.getActualMinimum(Calendar.DAY_OF_YEAR), + assertEquals(cal.getActualMinimum(Calendar.DAY_OF_YEAR), jd.range(ChronoField.DAY_OF_YEAR).getMinimum(), "different minimum for DAY_OF_YEAR in " + era + ", year: " + year); } } diff --git a/test/jdk/java/time/test/java/time/chrono/TestJapaneseChronology.java b/test/jdk/java/time/test/java/time/chrono/TestJapaneseChronology.java index 6e7df8638f9..85c33a964a3 100644 --- a/test/jdk/java/time/test/java/time/chrono/TestJapaneseChronology.java +++ b/test/jdk/java/time/test/java/time/chrono/TestJapaneseChronology.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -29,20 +29,22 @@ import java.time.temporal.*; import java.util.List; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests for the Japanese chronology */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestJapaneseChronology { private static final JapaneseChronology JAPANESE = JapaneseChronology.INSTANCE; private static final Locale jaJPJP = Locale.forLanguageTag("ja-JP-u-ca-japanese"); - @DataProvider(name="transitions") Object[][] transitionData() { return new Object[][] { // Japanese era, yearOfEra, month, dayOfMonth, gregorianYear @@ -62,7 +64,6 @@ public class TestJapaneseChronology { }; } - @DataProvider(name="day_year_data") Object[][] dayYearData() { return new Object[][] { // Japanese era, yearOfEra, dayOfYear, month, dayOfMonth @@ -80,7 +81,6 @@ public class TestJapaneseChronology { }; } - @DataProvider(name="range_data") Object[][] rangeData() { return new Object[][] { // field, minSmallest, minLargest, maxSmallest, maxLargest @@ -91,7 +91,6 @@ public class TestJapaneseChronology { }; } - @DataProvider(name="invalid_dates") Object[][] invalidDatesData() { return new Object[][] { // Japanese era, yearOfEra, month, dayOfMonth @@ -114,7 +113,6 @@ public class TestJapaneseChronology { }; } - @DataProvider(name="invalid_eraYear") Object[][] invalidEraYearData() { return new Object[][] { // Japanese era, yearOfEra @@ -136,7 +134,6 @@ public class TestJapaneseChronology { }; } - @DataProvider(name="invalid_day_year_data") Object[][] invalidDayYearData() { return new Object[][] { // Japanese era, yearOfEra, dayOfYear @@ -155,7 +152,6 @@ public class TestJapaneseChronology { }; } - @DataProvider Object[][] eraNameData() { return new Object[][] { // Japanese era, name, exception @@ -171,56 +167,69 @@ public class TestJapaneseChronology { @Test public void test_ofLocale() { // must be a singleton - assertEquals(Chronology.ofLocale(jaJPJP) == JAPANESE, true); + assertEquals(true, Chronology.ofLocale(jaJPJP) == JAPANESE); } - @Test(dataProvider="transitions") + @ParameterizedTest + @MethodSource("transitionData") public void test_transitions(JapaneseEra era, int yearOfEra, int month, int dayOfMonth, int gregorianYear) { - assertEquals(JAPANESE.prolepticYear(era, yearOfEra), gregorianYear); + assertEquals(gregorianYear, JAPANESE.prolepticYear(era, yearOfEra)); JapaneseDate jdate1 = JapaneseDate.of(era, yearOfEra, month, dayOfMonth); JapaneseDate jdate2 = JapaneseDate.of(gregorianYear, month, dayOfMonth); - assertEquals(jdate1, jdate2); + assertEquals(jdate2, jdate1); } - @Test(dataProvider="range_data") + @ParameterizedTest + @MethodSource("rangeData") public void test_range(ChronoField field, int minSmallest, int minLargest, int maxSmallest, int maxLargest) { ValueRange range = JAPANESE.range(field); - assertEquals(range.getMinimum(), minSmallest); - assertEquals(range.getLargestMinimum(), minLargest); - assertEquals(range.getSmallestMaximum(), maxSmallest); - assertEquals(range.getMaximum(), maxLargest); + assertEquals(minSmallest, range.getMinimum()); + assertEquals(minLargest, range.getLargestMinimum()); + assertEquals(maxSmallest, range.getSmallestMaximum()); + assertEquals(maxLargest, range.getMaximum()); } - @Test(dataProvider="day_year_data") + @ParameterizedTest + @MethodSource("dayYearData") public void test_firstDayOfEra(JapaneseEra era, int yearOfEra, int dayOfYear, int month, int dayOfMonth) { JapaneseDate date1 = JAPANESE.dateYearDay(era, yearOfEra, dayOfYear); JapaneseDate date2 = JAPANESE.date(era, yearOfEra, month, dayOfMonth); - assertEquals(date1, date2); + assertEquals(date2, date1); } - @Test(dataProvider="invalid_dates", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("invalidDatesData") public void test_invalidDate(JapaneseEra era, int yearOfEra, int month, int dayOfMonth) { - JapaneseDate jdate = JapaneseDate.of(era, yearOfEra, month, dayOfMonth); - System.out.printf("No DateTimeException with %s %d.%02d.%02d%n", era, yearOfEra, month, dayOfMonth); + Assertions.assertThrows(DateTimeException.class, () -> { + JapaneseDate jdate = JapaneseDate.of(era, yearOfEra, month, dayOfMonth); + System.out.printf("No DateTimeException with %s %d.%02d.%02d%n", era, yearOfEra, month, dayOfMonth); + }); } - @Test(dataProvider="invalid_eraYear", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("invalidEraYearData") public void test_invalidEraYear(JapaneseEra era, int yearOfEra) { - int year = JAPANESE.prolepticYear(era, yearOfEra); - System.out.printf("No DateTimeException with era=%s, year=%d%n", era, yearOfEra); + Assertions.assertThrows(DateTimeException.class, () -> { + int year = JAPANESE.prolepticYear(era, yearOfEra); + System.out.printf("No DateTimeException with era=%s, year=%d%n", era, yearOfEra); + }); } - @Test(dataProvider="invalid_day_year_data", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("invalidDayYearData") public void test_invalidDayYear(JapaneseEra era, int yearOfEra, int dayOfYear) { - JapaneseDate date = JAPANESE.dateYearDay(era, yearOfEra, dayOfYear); - System.out.printf("No DateTimeException with era=%s, year=%d, dayOfYear=%d%n", era, yearOfEra, dayOfYear); + Assertions.assertThrows(DateTimeException.class, () -> { + JapaneseDate date = JAPANESE.dateYearDay(era, yearOfEra, dayOfYear); + System.out.printf("No DateTimeException with era=%s, year=%d, dayOfYear=%d%n", era, yearOfEra, dayOfYear); + }); } - @Test(dataProvider="eraNameData") + @ParameterizedTest + @MethodSource("eraNameData") public void test_eraName(String eraName, JapaneseEra era, Class expectedEx) { try { - assertEquals(JapaneseEra.valueOf(eraName), era); + assertEquals(era, JapaneseEra.valueOf(eraName)); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } diff --git a/test/jdk/java/time/test/java/time/chrono/TestServiceLoader.java b/test/jdk/java/time/test/java/time/chrono/TestServiceLoader.java index 3eaa4253681..93e00b48b7a 100644 --- a/test/jdk/java/time/test/java/time/chrono/TestServiceLoader.java +++ b/test/jdk/java/time/test/java/time/chrono/TestServiceLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,21 +59,20 @@ */ package test.java.time.chrono; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.time.chrono.Chronology; import java.util.HashMap; import java.util.Map; import java.util.ServiceLoader; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Tests that a custom Chronology is available via the ServiceLoader. * The CopticChronology is configured via META-INF/services/java.time.chrono.Chronology. */ -@Test public class TestServiceLoader { @Test @@ -85,7 +84,7 @@ public class TestServiceLoader { } var coptic = chronos.get("Coptic"); assertNotNull(coptic, "CopticChronology not found"); - assertEquals(coptic.isIsoBased(), false); + assertEquals(false, coptic.isIsoBased()); } } diff --git a/test/jdk/java/time/test/java/time/chrono/TestThaiBuddhistChronoImpl.java b/test/jdk/java/time/test/java/time/chrono/TestThaiBuddhistChronoImpl.java index e878ac0dcb3..bb32a9e7d65 100644 --- a/test/jdk/java/time/test/java/time/chrono/TestThaiBuddhistChronoImpl.java +++ b/test/jdk/java/time/test/java/time/chrono/TestThaiBuddhistChronoImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -54,7 +54,7 @@ */ package test.java.time.chrono; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDate; import java.time.chrono.ThaiBuddhistChronology; @@ -65,19 +65,19 @@ import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestThaiBuddhistChronoImpl { /** * Range of years to check consistency with java.util.Calendar */ - @DataProvider(name="RangeVersusCalendar") Object[][] provider_rangeVersusCalendar() { return new Object[][] { {LocalDate.of(1583, 1, 1), LocalDate.of(2100, 1, 1)}, @@ -87,12 +87,13 @@ public class TestThaiBuddhistChronoImpl { //----------------------------------------------------------------------- // Verify ThaiBuddhist Calendar matches java.util.Calendar for range //----------------------------------------------------------------------- - @Test(dataProvider="RangeVersusCalendar") + @ParameterizedTest + @MethodSource("provider_rangeVersusCalendar") public void test_ThaiBuddhistChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) { Locale locale = Locale.forLanguageTag("th-TH--u-ca-buddhist"); - assertEquals(locale.toString(), "th_TH", "Unexpected locale"); + assertEquals("th_TH", locale.toString(), "Unexpected locale"); Calendar cal = java.util.Calendar.getInstance(locale); - assertEquals(cal.getCalendarType(), "buddhist", "Unexpected calendar type"); + assertEquals("buddhist", cal.getCalendarType(), "Unexpected calendar type"); ThaiBuddhistDate thaiDate = ThaiBuddhistChronology.INSTANCE.date(isoStartDate); @@ -102,9 +103,9 @@ public class TestThaiBuddhistChronoImpl { cal.set(Calendar.DAY_OF_MONTH, thaiDate.get(ChronoField.DAY_OF_MONTH)); while (thaiDate.isBefore(isoEndDate)) { - assertEquals(thaiDate.get(ChronoField.DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + thaiDate + "; cal: " + cal); - assertEquals(thaiDate.get(ChronoField.MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + thaiDate); - assertEquals(thaiDate.get(ChronoField.YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + thaiDate); + assertEquals(cal.get(Calendar.DAY_OF_MONTH), thaiDate.get(ChronoField.DAY_OF_MONTH), "Day mismatch in " + thaiDate + "; cal: " + cal); + assertEquals(cal.get(Calendar.MONTH) + 1, thaiDate.get(ChronoField.MONTH_OF_YEAR), "Month mismatch in " + thaiDate); + assertEquals(cal.get(Calendar.YEAR), thaiDate.get(ChronoField.YEAR_OF_ERA), "Year mismatch in " + thaiDate); thaiDate = thaiDate.plus(1, ChronoUnit.DAYS); cal.add(Calendar.DAY_OF_MONTH, 1); diff --git a/test/jdk/java/time/test/java/time/chrono/TestUmmAlQuraChronology.java b/test/jdk/java/time/test/java/time/chrono/TestUmmAlQuraChronology.java index 8d68abfd227..2dfd112596b 100644 --- a/test/jdk/java/time/test/java/time/chrono/TestUmmAlQuraChronology.java +++ b/test/jdk/java/time/test/java/time/chrono/TestUmmAlQuraChronology.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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,11 @@ import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_YEAR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.DateTimeException; import java.time.DayOfWeek; @@ -64,15 +65,18 @@ import java.time.temporal.ValueRange; import java.time.temporal.WeekFields; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests for the Umm alQura chronology and data. * Note: The dates used for testing are just a sample of calendar data. * @bug 8067800 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestUmmAlQuraChronology { private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2); @@ -82,21 +86,22 @@ public class TestUmmAlQuraChronology { @Test public void test_aliases() { HijrahChronology hc = (HijrahChronology) Chronology.of("Hijrah"); - assertEquals(hc, HijrahChronology.INSTANCE, "Alias for Hijrah-umalqura"); + assertEquals(HijrahChronology.INSTANCE, hc, "Alias for Hijrah-umalqura"); hc = (HijrahChronology) Chronology.of("islamic"); - assertEquals(hc, HijrahChronology.INSTANCE, "Alias for Hijrah-umalqura"); + assertEquals(HijrahChronology.INSTANCE, hc, "Alias for Hijrah-umalqura"); } // Test to check if the exception is thrown for an incorrect chronology id - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_badChronology() { - Chronology test = Chronology.of("Hijrah-ummalqura"); + Assertions.assertThrows(DateTimeException.class, () -> { + Chronology test = Chronology.of("Hijrah-ummalqura"); + }); } //-------------------------------------------------------------------------- // regular data factory for Umm alQura dates and the corresponding ISO dates //-------------------------------------------------------------------------- - @DataProvider(name = "UmmAlQuraVsISODates") Object[][] data_UmmAlQuraVsISODates() { return new Object[][] { {HijrahDate.of(1318, 1, 1), LocalDate.of(1900, 04, 30)}, @@ -110,9 +115,10 @@ public class TestUmmAlQuraChronology { } // Test to verify the epoch days for given Hijrah & ISO date instances - @Test(dataProvider="UmmAlQuraVsISODates") + @ParameterizedTest + @MethodSource("data_UmmAlQuraVsISODates") public void Test_UmmAlQuraVsISODates(HijrahDate hd, LocalDate ld) { - assertEquals(hd.toEpochDay(), ld.toEpochDay(), "Umm alQura date and ISO date should have same epochDay"); + assertEquals(ld.toEpochDay(), hd.toEpochDay(), "Umm alQura date and ISO date should have same epochDay"); } // UmmAlQura chronology ranges for year, month and days for the HijrahChronology @@ -120,28 +126,27 @@ public class TestUmmAlQuraChronology { public void Test_UmmAlQuraChronoRange() { HijrahChronology chrono = HijrahChronology.INSTANCE; ValueRange year = chrono.range(YEAR); - assertEquals(year.getMinimum(), 1300, "Minimum year"); - assertEquals(year.getLargestMinimum(), 1300, "Largest minimum year"); - assertEquals(year.getMaximum(), 1600, "Largest year"); - assertEquals(year.getSmallestMaximum(), 1600, "Smallest Maximum year"); + assertEquals(1300, year.getMinimum(), "Minimum year"); + assertEquals(1300, year.getLargestMinimum(), "Largest minimum year"); + assertEquals(1600, year.getMaximum(), "Largest year"); + assertEquals(1600, year.getSmallestMaximum(), "Smallest Maximum year"); ValueRange month = chrono.range(MONTH_OF_YEAR); - assertEquals(month.getMinimum(), 1, "Minimum month"); - assertEquals(month.getLargestMinimum(), 1, "Largest minimum month"); - assertEquals(month.getMaximum(), 12, "Largest month"); - assertEquals(month.getSmallestMaximum(), 12, "Smallest Maximum month"); + assertEquals(1, month.getMinimum(), "Minimum month"); + assertEquals(1, month.getLargestMinimum(), "Largest minimum month"); + assertEquals(12, month.getMaximum(), "Largest month"); + assertEquals(12, month.getSmallestMaximum(), "Smallest Maximum month"); ValueRange day = chrono.range(DAY_OF_MONTH); - assertEquals(day.getMinimum(), 1, "Minimum day"); - assertEquals(day.getLargestMinimum(), 1, "Largest minimum day"); - assertEquals(day.getMaximum(), 30, "Largest day"); - assertEquals(day.getSmallestMaximum(), 29, "Smallest Maximum day"); + assertEquals(1, day.getMinimum(), "Minimum day"); + assertEquals(1, day.getLargestMinimum(), "Largest minimum day"); + assertEquals(30, day.getMaximum(), "Largest day"); + assertEquals(29, day.getSmallestMaximum(), "Smallest Maximum day"); } //----------------------------------------------------------------------- // regular data factory for dates and the corresponding range values //----------------------------------------------------------------------- - @DataProvider(name = "dates") Object[][] data_dates() { return new Object[][]{ {HijrahDate.of(1300, 5, 1), 1300, 1600, 1, 12, 1, 30, 30}, @@ -153,7 +158,8 @@ public class TestUmmAlQuraChronology { } // Test to verify the min/max field ranges for given dates - @Test(dataProvider="dates") + @ParameterizedTest + @MethodSource("data_dates") public void Test_UmmAlQuraRanges(HijrahDate date, int minYear, int maxYear, int minMonth, int maxMonth, @@ -161,33 +167,33 @@ public class TestUmmAlQuraChronology { // Check the chronology ranges HijrahChronology chrono = date.getChronology(); ValueRange yearRange = chrono.range(YEAR); - assertEquals(yearRange.getMinimum(), minYear, "Minimum year for Hijrah chronology"); - assertEquals(yearRange.getLargestMinimum(), minYear, "Largest minimum year for Hijrah chronology"); - assertEquals(yearRange.getMaximum(), maxYear, "Maximum year for Hijrah chronology"); - assertEquals(yearRange.getSmallestMaximum(), maxYear, "Smallest Maximum year for Hijrah chronology"); + assertEquals(minYear, yearRange.getMinimum(), "Minimum year for Hijrah chronology"); + assertEquals(minYear, yearRange.getLargestMinimum(), "Largest minimum year for Hijrah chronology"); + assertEquals(maxYear, yearRange.getMaximum(), "Maximum year for Hijrah chronology"); + assertEquals(maxYear, yearRange.getSmallestMaximum(), "Smallest Maximum year for Hijrah chronology"); ValueRange monthRange = chrono.range(MONTH_OF_YEAR); - assertEquals(monthRange.getMinimum(), minMonth, "Minimum month for Hijrah chronology"); - assertEquals(monthRange.getMaximum(), maxMonth, "Maximum month for Hijrah chronology"); + assertEquals(minMonth, monthRange.getMinimum(), "Minimum month for Hijrah chronology"); + assertEquals(maxMonth, monthRange.getMaximum(), "Maximum month for Hijrah chronology"); ValueRange daysRange = chrono.range(DAY_OF_MONTH); - assertEquals(daysRange.getMinimum(), minDay, "Minimum day for chronology"); - assertEquals(daysRange.getMaximum(), maxChronoDay, "Maximum day for Hijrah chronology"); + assertEquals(minDay, daysRange.getMinimum(), "Minimum day for chronology"); + assertEquals(maxChronoDay, daysRange.getMaximum(), "Maximum day for Hijrah chronology"); // Check the date ranges yearRange = date.range(YEAR); - assertEquals(yearRange.getMinimum(), minYear, "Minimum year for Hijrah date"); - assertEquals(yearRange.getLargestMinimum(), minYear, "Largest minimum year for Hijrah date"); - assertEquals(yearRange.getMaximum(), maxYear, "Maximum year for Hijrah date"); - assertEquals(yearRange.getSmallestMaximum(), maxYear, "Smallest maximum year for Hijrah date"); + assertEquals(minYear, yearRange.getMinimum(), "Minimum year for Hijrah date"); + assertEquals(minYear, yearRange.getLargestMinimum(), "Largest minimum year for Hijrah date"); + assertEquals(maxYear, yearRange.getMaximum(), "Maximum year for Hijrah date"); + assertEquals(maxYear, yearRange.getSmallestMaximum(), "Smallest maximum year for Hijrah date"); monthRange = date.range(MONTH_OF_YEAR); - assertEquals(monthRange.getMinimum(), minMonth, "Minimum month for HijrahDate"); - assertEquals(monthRange.getMaximum(), maxMonth, "Maximum month for HijrahDate"); + assertEquals(minMonth, monthRange.getMinimum(), "Minimum month for HijrahDate"); + assertEquals(maxMonth, monthRange.getMaximum(), "Maximum month for HijrahDate"); daysRange = date.range(DAY_OF_MONTH); - assertEquals(daysRange.getMinimum(), minDay, "Minimum day for HijrahDate"); - assertEquals(daysRange.getMaximum(), maxDay, "Maximum day for HijrahDate"); + assertEquals(minDay, daysRange.getMinimum(), "Minimum day for HijrahDate"); + assertEquals(maxDay, daysRange.getMaximum(), "Maximum day for HijrahDate"); } @@ -223,7 +229,6 @@ public class TestUmmAlQuraChronology { } // Data provider to verify the dateYearDay() method - @DataProvider(name="dateYearDay") Object[][] data_dateYearDay() { return new Object[][] { {HijrahChronology.INSTANCE.dateYearDay(1434, 42), HijrahChronology.INSTANCE.date(1434, 02, 13)}, @@ -236,9 +241,10 @@ public class TestUmmAlQuraChronology { } // Test to verify the dateYearDay() method - @Test(dataProvider="dateYearDay") + @ParameterizedTest + @MethodSource("data_dateYearDay") public void test_DateYearDay(ChronoLocalDate date1, ChronoLocalDate date2) { - assertEquals(date1, date2); + assertEquals(date2, date1); } //----------------------------------------------------------------------- @@ -250,7 +256,7 @@ public class TestUmmAlQuraChronology { for (int i = 1; i <= hd1.lengthOfYear(); i++) { HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(1434, i); int doy = hd.get(DAY_OF_YEAR); - assertEquals(doy, i, "get(DAY_OF_YEAR) incorrect for " + i); + assertEquals(i, doy, "get(DAY_OF_YEAR) incorrect for " + i); } } @@ -260,54 +266,57 @@ public class TestUmmAlQuraChronology { for (int i = 1; i <= hd.lengthOfYear(); i++) { HijrahDate hd2 = hd.with(DAY_OF_YEAR, i); int doy = hd2.get(DAY_OF_YEAR); - assertEquals(doy, i, "with(DAY_OF_YEAR) incorrect for " + i + " " + hd2); + assertEquals(i, doy, "with(DAY_OF_YEAR) incorrect for " + i + " " + hd2); } } - @Test(expectedExceptions=java.time.DateTimeException.class) + @Test public void test_withDayOfYearTooSmall() { - HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(1435, 1); - HijrahDate hd2 = hd.with(DAY_OF_YEAR, 0); + Assertions.assertThrows(DateTimeException.class, () -> { + HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(1435, 1); + HijrahDate hd2 = hd.with(DAY_OF_YEAR, 0); + }); } - @Test(expectedExceptions=java.time.DateTimeException.class) + @Test public void test_withDayOfYearTooLarge() { - HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(1435, 1); - HijrahDate hd2 = hd.with(DAY_OF_YEAR, hd.lengthOfYear() + 1); + Assertions.assertThrows(DateTimeException.class, () -> { + HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(1435, 1); + HijrahDate hd2 = hd.with(DAY_OF_YEAR, hd.lengthOfYear() + 1); + }); } // Test to verify the with() method with ChronoField is set to DAY_OF_WEEK @Test public void test_adjustWithDayOfWeek() { - assertEquals(HijrahChronology.INSTANCE.date(1320, 1, 15).with(ChronoField.DAY_OF_WEEK, 4), HijrahDate.of(1320, 1, 15)); - assertEquals(HijrahChronology.INSTANCE.date(1421, 11, 15).with(ChronoField.DAY_OF_WEEK, 1), HijrahDate.of(1421, 11, 11)); - assertEquals(HijrahChronology.INSTANCE.date(1529, 7, 18).with(ChronoField.DAY_OF_WEEK, 6), HijrahDate.of(1529, 7, 20)); - assertEquals(HijrahChronology.INSTANCE.date(1534, 2, 10).with(ChronoField.DAY_OF_WEEK, 5), HijrahDate.of(1534, 2, 12)); - assertEquals(HijrahChronology.INSTANCE.date(1552, 4, 1).with(ChronoField.DAY_OF_WEEK, 2), HijrahDate.of(1552, 3, 26)); + assertEquals(HijrahDate.of(1320, 1, 15), HijrahChronology.INSTANCE.date(1320, 1, 15).with(ChronoField.DAY_OF_WEEK, 4)); + assertEquals(HijrahDate.of(1421, 11, 11), HijrahChronology.INSTANCE.date(1421, 11, 15).with(ChronoField.DAY_OF_WEEK, 1)); + assertEquals(HijrahDate.of(1529, 7, 20), HijrahChronology.INSTANCE.date(1529, 7, 18).with(ChronoField.DAY_OF_WEEK, 6)); + assertEquals(HijrahDate.of(1534, 2, 12), HijrahChronology.INSTANCE.date(1534, 2, 10).with(ChronoField.DAY_OF_WEEK, 5)); + assertEquals(HijrahDate.of(1552, 3, 26), HijrahChronology.INSTANCE.date(1552, 4, 1).with(ChronoField.DAY_OF_WEEK, 2)); } // Test to verify the with() method with ChronoField is set to DAY_OF_MONTH @Test public void test_adjustWithDayOfMonth() { - assertEquals(HijrahChronology.INSTANCE.date(1320, 1, 15).with(ChronoField.DAY_OF_MONTH, 2), HijrahDate.of(1320, 1, 2)); - assertEquals(HijrahChronology.INSTANCE.date(1421, 11, 15).with(ChronoField.DAY_OF_MONTH, 9), HijrahDate.of(1421, 11, 9)); - assertEquals(HijrahChronology.INSTANCE.date(1529, 7, 18).with(ChronoField.DAY_OF_MONTH, 13), HijrahDate.of(1529, 7, 13)); - assertEquals(HijrahChronology.INSTANCE.date(1534, 12, 10).with(ChronoField.DAY_OF_MONTH, 29), HijrahDate.of(1534, 12, 29)); - assertEquals(HijrahChronology.INSTANCE.date(1552, 4, 1).with(ChronoField.DAY_OF_MONTH, 6), HijrahDate.of(1552, 4, 6)); + assertEquals(HijrahDate.of(1320, 1, 2), HijrahChronology.INSTANCE.date(1320, 1, 15).with(ChronoField.DAY_OF_MONTH, 2)); + assertEquals(HijrahDate.of(1421, 11, 9), HijrahChronology.INSTANCE.date(1421, 11, 15).with(ChronoField.DAY_OF_MONTH, 9)); + assertEquals(HijrahDate.of(1529, 7, 13), HijrahChronology.INSTANCE.date(1529, 7, 18).with(ChronoField.DAY_OF_MONTH, 13)); + assertEquals(HijrahDate.of(1534, 12, 29), HijrahChronology.INSTANCE.date(1534, 12, 10).with(ChronoField.DAY_OF_MONTH, 29)); + assertEquals(HijrahDate.of(1552, 4, 6), HijrahChronology.INSTANCE.date(1552, 4, 1).with(ChronoField.DAY_OF_MONTH, 6)); } // Test to verify the with() method with ChronoField is set to DAY_OF_YEAR @Test public void test_adjustWithDayOfYear() { - assertEquals(HijrahChronology.INSTANCE.date(1320, 1, 15).with(ChronoField.DAY_OF_YEAR, 24), HijrahDate.of(1320, 1, 24)); - assertEquals(HijrahChronology.INSTANCE.date(1421, 11, 15).with(ChronoField.DAY_OF_YEAR, 135), HijrahDate.of(1421, 5, 18)); - assertEquals(HijrahChronology.INSTANCE.date(1529, 7, 18).with(ChronoField.DAY_OF_YEAR, 64), HijrahDate.of(1529, 3, 5)); - assertEquals(HijrahChronology.INSTANCE.date(1534, 2, 10).with(ChronoField.DAY_OF_YEAR, 354), HijrahDate.of(1534, 12, 29)); - assertEquals(HijrahChronology.INSTANCE.date(1552, 4, 1).with(ChronoField.DAY_OF_YEAR, 291), HijrahDate.of(1552, 10, 26)); + assertEquals(HijrahDate.of(1320, 1, 24), HijrahChronology.INSTANCE.date(1320, 1, 15).with(ChronoField.DAY_OF_YEAR, 24)); + assertEquals(HijrahDate.of(1421, 5, 18), HijrahChronology.INSTANCE.date(1421, 11, 15).with(ChronoField.DAY_OF_YEAR, 135)); + assertEquals(HijrahDate.of(1529, 3, 5), HijrahChronology.INSTANCE.date(1529, 7, 18).with(ChronoField.DAY_OF_YEAR, 64)); + assertEquals(HijrahDate.of(1534, 12, 29), HijrahChronology.INSTANCE.date(1534, 2, 10).with(ChronoField.DAY_OF_YEAR, 354)); + assertEquals(HijrahDate.of(1552, 10, 26), HijrahChronology.INSTANCE.date(1552, 4, 1).with(ChronoField.DAY_OF_YEAR, 291)); } // Data provider to get the difference between two dates in terms of days, months and years - @DataProvider(name="datesForDiff") Object[][] data_datesForDiffs() { return new Object[][] { {HijrahDate.of(1350, 5, 15), HijrahDate.of(1351, 12, 29), 574, 19, 1}, @@ -319,15 +328,15 @@ public class TestUmmAlQuraChronology { } // Test to verify the difference between two given dates in terms of days, months and years - @Test(dataProvider="datesForDiff") + @ParameterizedTest + @MethodSource("data_datesForDiffs") public void test_diffBetweenDates(ChronoLocalDate from, ChronoLocalDate to, long days, long months, long years) { - assertEquals(from.until(to, ChronoUnit.DAYS), days); - assertEquals(from.until(to, ChronoUnit.MONTHS), months); - assertEquals(from.until(to, ChronoUnit.YEARS), years); + assertEquals(days, from.until(to, ChronoUnit.DAYS)); + assertEquals(months, from.until(to, ChronoUnit.MONTHS)); + assertEquals(years, from.until(to, ChronoUnit.YEARS)); } // Data provider to get the difference between two dates as a period - @DataProvider(name="datesForPeriod") Object[][] data_Period() { return new Object[][] { {HijrahDate.of(1350, 5, 15), HijrahDate.of(1434, 7, 20), HijrahChronology.INSTANCE.period(84, 2, 5)}, @@ -339,34 +348,35 @@ public class TestUmmAlQuraChronology { } // Test to get the Period between two given dates - @Test(dataProvider="datesForPeriod") + @ParameterizedTest + @MethodSource("data_Period") public void test_until(HijrahDate h1, HijrahDate h2, ChronoPeriod p) { ChronoPeriod period = h1.until(h2); - assertEquals(period, p); + assertEquals(p, period); } // Test to get the Period between dates in different chronologies - @Test(dataProvider="datesForPeriod") + @ParameterizedTest + @MethodSource("data_Period") public void test_periodUntilDiffChrono(HijrahDate h1, HijrahDate h2, ChronoPeriod p) { MinguoDate m = MinguoChronology.INSTANCE.date(h2); ChronoPeriod period = h1.until(m); - assertEquals(period, p); + assertEquals(p, period); } // Test to get the adjusted date from a given date using TemporalAdjuster methods @Test public void test_temporalDayAdjustments() { HijrahDate date = HijrahDate.of(1554, 7, 21); - assertEquals(date.with(TemporalAdjusters.firstDayOfMonth()), HijrahDate.of(1554, 7, 1)); - assertEquals(date.with(TemporalAdjusters.lastDayOfMonth()), HijrahDate.of(1554, 7, 29)); - assertEquals(date.with(TemporalAdjusters.firstDayOfNextMonth()), HijrahDate.of(1554, 8, 1)); - assertEquals(date.with(TemporalAdjusters.firstDayOfNextYear()), HijrahDate.of(1555, 1, 1)); - assertEquals(date.with(TemporalAdjusters.firstDayOfYear()), HijrahDate.of(1554, 1, 1)); - assertEquals(date.with(TemporalAdjusters.lastDayOfYear()), HijrahDate.of(1554, 12, 30)); + assertEquals(HijrahDate.of(1554, 7, 1), date.with(TemporalAdjusters.firstDayOfMonth())); + assertEquals(HijrahDate.of(1554, 7, 29), date.with(TemporalAdjusters.lastDayOfMonth())); + assertEquals(HijrahDate.of(1554, 8, 1), date.with(TemporalAdjusters.firstDayOfNextMonth())); + assertEquals(HijrahDate.of(1555, 1, 1), date.with(TemporalAdjusters.firstDayOfNextYear())); + assertEquals(HijrahDate.of(1554, 1, 1), date.with(TemporalAdjusters.firstDayOfYear())); + assertEquals(HijrahDate.of(1554, 12, 30), date.with(TemporalAdjusters.lastDayOfYear())); } // Data provider for string representation of the date instances - @DataProvider(name="toString") Object[][] data_toString() { return new Object[][] { {HijrahChronology.INSTANCE.date(1320, 1, 1), "Hijrah-umalqura AH 1320-01-01"}, @@ -378,13 +388,13 @@ public class TestUmmAlQuraChronology { } // Test to verify the returned string value of a given date instance - @Test(dataProvider="toString") + @ParameterizedTest + @MethodSource("data_toString") public void test_toString(ChronoLocalDate hijrahDate, String expected) { - assertEquals(hijrahDate.toString(), expected); + assertEquals(expected, hijrahDate.toString()); } // Data provider for maximum number of days - @DataProvider(name="monthDays") Object[][] data_monthDays() { return new Object[][] { {1432, 1, 29}, @@ -397,27 +407,28 @@ public class TestUmmAlQuraChronology { } // Test to verify the maximum number of days by adding one month to a given date - @Test (dataProvider="monthDays") + @ParameterizedTest + @MethodSource("data_monthDays") public void test_valueRange_monthDays(int year, int month, int maxlength) { ChronoLocalDate date = HijrahChronology.INSTANCE.date(year, month, 1); ValueRange range = null; for (int i=1; i<=12; i++) { range = date.range(ChronoField.DAY_OF_MONTH); date = date.plus(1, ChronoUnit.MONTHS); - assertEquals(range.getMaximum(), month, maxlength); + assertEquals(month, range.getMaximum(), maxlength); } } // Test to get the last day of the month by adjusting the date with lastDayOfMonth() method - @Test(dataProvider="monthDays") + @ParameterizedTest + @MethodSource("data_monthDays") public void test_lastDayOfMonth(int year, int month, int numDays) { HijrahDate hDate = HijrahChronology.INSTANCE.date(year, month, 1); hDate = hDate.with(TemporalAdjusters.lastDayOfMonth()); - assertEquals(hDate.get(ChronoField.DAY_OF_MONTH), numDays); + assertEquals(numDays, hDate.get(ChronoField.DAY_OF_MONTH)); } // Data provider for the 12 islamic month names in a formatted date - @DataProvider(name="patternMonthNames") Object[][] data_patternMonthNames() { return new Object[][] { {1434, 1, 1, "01 AH Thu Muharram 1434"}, @@ -436,15 +447,15 @@ public class TestUmmAlQuraChronology { } // Test to verify the formatted dates - @Test(dataProvider="patternMonthNames") + @ParameterizedTest + @MethodSource("data_patternMonthNames") public void test_ofPattern(int year, int month, int day, String expected) { DateTimeFormatter test = DateTimeFormatter.ofPattern("dd G E MMMM yyyy", Locale.US); - assertEquals(test.format(HijrahDate.of(year, month, day)), expected); + assertEquals(expected, test.format(HijrahDate.of(year, month, day))); } // Data provider for localized dates - @DataProvider(name="chronoDateTimes") - Object[][] data_chronodatetimes() { + Object[][] data_chronodatetimes() { return new Object[][] { {1432, 12, 29, "Safar 1, 1434 AH"}, {1433, 1, 30, "Safar 30, 1434 AH"}, @@ -453,7 +464,8 @@ public class TestUmmAlQuraChronology { } // Test to verify the localized dates using ofLocalizedDate() method - @Test(dataProvider="chronoDateTimes") + @ParameterizedTest + @MethodSource("data_chronodatetimes") public void test_formatterOfLocalizedDate(int year, int month, int day, String expected) { HijrahDate hd = HijrahChronology.INSTANCE.date(year, month, day); ChronoLocalDateTime hdt = hd.atTime(LocalTime.NOON); @@ -464,12 +476,11 @@ public class TestUmmAlQuraChronology { hdt = hdt.plus(1, ChronoUnit.MINUTES); hdt = hdt.plus(1, ChronoUnit.SECONDS); DateTimeFormatter df = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withChronology(Chronology.of("Hijrah-umalqura")).withLocale(Locale.US); - assertEquals(df.format(hdt), expected); + assertEquals(expected, df.format(hdt)); } // Data provider to get the day of the week in a given date // The day of the week varies if the week starts with a saturday or sunday - @DataProvider(name="dayOfWeek") Object[][] data_dayOfweek() { return new Object[][] { {HijrahDate.of(1434, 6, 24), 1, 7}, @@ -481,14 +492,14 @@ public class TestUmmAlQuraChronology { } // Test to get the day of the week based on a Saturday/Sunday as the first day of the week - @Test(dataProvider="dayOfWeek") + @ParameterizedTest + @MethodSource("data_dayOfweek") public void test_dayOfWeek(HijrahDate date, int satStart, int sunStart) { - assertEquals(date.get(WeekFields.of(DayOfWeek.SATURDAY, 7).dayOfWeek()), satStart); - assertEquals(date.get(WeekFields.of(DayOfWeek.SUNDAY, 7).dayOfWeek()), sunStart); + assertEquals(satStart, date.get(WeekFields.of(DayOfWeek.SATURDAY, 7).dayOfWeek())); + assertEquals(sunStart, date.get(WeekFields.of(DayOfWeek.SUNDAY, 7).dayOfWeek())); } // Data sample to get the epoch days of a date instance - @DataProvider(name="epochDays") Object[][] data_epochdays() { return new Object[][] { {1332, -20486}, @@ -502,14 +513,14 @@ public class TestUmmAlQuraChronology { } // Test to verify the number of epoch days of a date instance - @Test(dataProvider="epochDays") + @ParameterizedTest + @MethodSource("data_epochdays") public void test_epochDays(int y, long epoch) { HijrahDate date = HijrahDate.of(y, 1, 1); - assertEquals(date.toEpochDay(), epoch); + assertEquals(epoch, date.toEpochDay()); } // Data provider to verify whether a given hijrah year is a leap year or not - @DataProvider(name="leapYears") Object[][] data_leapyears() { return new Object[][] { {1302, true}, @@ -524,15 +535,15 @@ public class TestUmmAlQuraChronology { } // Test to verify whether a given hijrah year is a leap year or not - @Test(dataProvider="leapYears") + @ParameterizedTest + @MethodSource("data_leapyears") public void test_leapYears(int y, boolean leapyear) { HijrahDate date = HijrahDate.of(y, 1, 1); - assertEquals(date.isLeapYear(), leapyear); + assertEquals(leapyear, date.isLeapYear()); } // Data provider to verify that a given hijrah year is outside the range of supported years // The values are dependent on the currently configured UmmAlQura calendar data - @DataProvider(name="OutOfRangeLeapYears") Object[][] data_invalid_leapyears() { return new Object[][] { {1299}, @@ -542,14 +553,14 @@ public class TestUmmAlQuraChronology { }; } - @Test(dataProvider="OutOfRangeLeapYears") + @ParameterizedTest + @MethodSource("data_invalid_leapyears") public void test_notLeapYears(int y) { assertFalse(HijrahChronology.INSTANCE.isLeapYear(y), "Out of range leap year"); } // Date samples to convert HijrahDate to LocalDate and vice versa - @DataProvider(name="samples") Object[][] data_samples() { return new Object[][] { {HijrahChronology.INSTANCE.date(1319, 12, 30), LocalDate.of(1902, 4, 9)}, @@ -562,45 +573,50 @@ public class TestUmmAlQuraChronology { } // Test to get LocalDate instance from a given HijrahDate - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_toLocalDate(ChronoLocalDate hijrahDate, LocalDate iso) { - assertEquals(LocalDate.from(hijrahDate), iso); + assertEquals(iso, LocalDate.from(hijrahDate)); } // Test to adjust HijrahDate with a given LocalDate - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_adjust_toLocalDate(ChronoLocalDate hijrahDate, LocalDate iso) { - assertEquals(hijrahDate.with(iso), hijrahDate); + assertEquals(hijrahDate, hijrahDate.with(iso)); } // Test to get a HijrahDate from a calendrical - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_fromCalendrical(ChronoLocalDate hijrahDate, LocalDate iso) { - assertEquals(HijrahChronology.INSTANCE.date(iso), hijrahDate); + assertEquals(hijrahDate, HijrahChronology.INSTANCE.date(iso)); } // Test to verify the day of week of a given HijrahDate and LocalDate - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_dayOfWeekEqualIsoDayOfWeek(ChronoLocalDate hijrahDate, LocalDate iso) { - assertEquals(hijrahDate.get(ChronoField.DAY_OF_WEEK), iso.get(ChronoField.DAY_OF_WEEK), "Hijrah day of week should be same as ISO day of week"); + assertEquals(iso.get(ChronoField.DAY_OF_WEEK), hijrahDate.get(ChronoField.DAY_OF_WEEK), "Hijrah day of week should be same as ISO day of week"); } // Test to get the local date by applying the MIN adjustment with hijrah date - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_LocalDate_adjustToHijrahDate(ChronoLocalDate hijrahDate, LocalDate localDate) { LocalDate test = LocalDate.MIN.with(hijrahDate); - assertEquals(test, localDate); + assertEquals(localDate, test); } // Test to get the local date time by applying the MIN adjustment with hijrah date - @Test(dataProvider="samples") + @ParameterizedTest + @MethodSource("data_samples") public void test_LocalDateTime_adjustToHijrahDate(ChronoLocalDate hijrahDate, LocalDate localDate) { LocalDateTime test = LocalDateTime.MIN.with(hijrahDate); - assertEquals(test, LocalDateTime.of(localDate, LocalTime.MIDNIGHT)); + assertEquals(LocalDateTime.of(localDate, LocalTime.MIDNIGHT), test); } // Sample dates for comparison - @DataProvider(name="datesForComparison") Object[][] data_datesForComparison() { return new Object[][] { {HijrahChronology.INSTANCE.date(1434, 6, 26), LocalDate.of(2013, 5, 5), -1, 1}, @@ -612,42 +628,42 @@ public class TestUmmAlQuraChronology { } // Test to compare dates in both forward and reverse order - @Test(dataProvider="datesForComparison") + @ParameterizedTest + @MethodSource("data_datesForComparison") public void test_compareDates(HijrahDate hdate, LocalDate ldate, int result1, int result2) { - assertEquals(ldate.compareTo(hdate), result1); - assertEquals(hdate.compareTo(ldate), result2); + assertEquals(result1, ldate.compareTo(hdate)); + assertEquals(result2, hdate.compareTo(ldate)); } // Test to verify the values of various chrono fields for a given hijrah date instance @Test public void test_chronoFields() { ChronoLocalDate hdate = HijrahChronology.INSTANCE.date(1434, 6, 28); - assertEquals(hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), 7); - assertEquals(hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), 7); - assertEquals(hdate.get(ChronoField.ALIGNED_WEEK_OF_MONTH), 4); - assertEquals(hdate.get(ChronoField.ALIGNED_WEEK_OF_YEAR), 25); - assertEquals(hdate.get(ChronoField.ERA), 1); - assertEquals(hdate.get(ChronoField.YEAR_OF_ERA), 1434); - assertEquals(hdate.get(ChronoField.MONTH_OF_YEAR), 6); - assertEquals(hdate.get(ChronoField.DAY_OF_MONTH), 28); - assertEquals(hdate.get(ChronoField.DAY_OF_WEEK), 3); - assertEquals(hdate.get(ChronoField.DAY_OF_YEAR), 175); + assertEquals(7, hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); + assertEquals(7, hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + assertEquals(4, hdate.get(ChronoField.ALIGNED_WEEK_OF_MONTH)); + assertEquals(25, hdate.get(ChronoField.ALIGNED_WEEK_OF_YEAR)); + assertEquals(1, hdate.get(ChronoField.ERA)); + assertEquals(1434, hdate.get(ChronoField.YEAR_OF_ERA)); + assertEquals(6, hdate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(28, hdate.get(ChronoField.DAY_OF_MONTH)); + assertEquals(3, hdate.get(ChronoField.DAY_OF_WEEK)); + assertEquals(175, hdate.get(ChronoField.DAY_OF_YEAR)); } // Test to verify the returned hijrah date after adjusting the day of week as Saturday @Test public void test_adjustInto() { - assertEquals(DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1434, 6, 28)), HijrahDate.of(1434, 7, 1)); - assertEquals(DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1432, 4, 13)), HijrahDate.of(1432, 4, 14)); - assertEquals(DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1433, 11, 29)), HijrahDate.of(1433, 12, 4)); - assertEquals(DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1434, 5, 10)), HijrahDate.of(1434, 5, 11)); - assertEquals(DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1434, 9, 11)), HijrahDate.of(1434, 9, 12)); + assertEquals(HijrahDate.of(1434, 7, 1), DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1434, 6, 28))); + assertEquals(HijrahDate.of(1432, 4, 14), DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1432, 4, 13))); + assertEquals(HijrahDate.of(1433, 12, 4), DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1433, 11, 29))); + assertEquals(HijrahDate.of(1434, 5, 11), DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1434, 5, 10))); + assertEquals(HijrahDate.of(1434, 9, 12), DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1434, 9, 11))); } //----------------------------------------------------------------------- // zonedDateTime(TemporalAccessor) //----------------------------------------------------------------------- - @DataProvider(name="zonedDateTime") Object[][] data_zonedDateTime() { return new Object[][] { {ZonedDateTime.of(2012, 2, 29, 2, 7, 1, 1, ZONE_RIYADH), HijrahChronology.INSTANCE.date(1433, 4, 7), LocalTime.of(2, 7, 1, 1), null}, @@ -661,13 +677,14 @@ public class TestUmmAlQuraChronology { } // Test to check the zoned date times - @Test(dataProvider="zonedDateTime") + @ParameterizedTest + @MethodSource("data_zonedDateTime") public void test_zonedDateTime(TemporalAccessor accessor, HijrahDate expectedDate, LocalTime expectedTime, Class expectedEx) { if (expectedEx == null) { ChronoZonedDateTime result = HijrahChronology.INSTANCE.zonedDateTime(accessor); - assertEquals(result.toLocalDate(), expectedDate); - assertEquals(HijrahDate.from(accessor), expectedDate); - assertEquals(result.toLocalTime(), expectedTime); + assertEquals(expectedDate, result.toLocalDate()); + assertEquals(expectedDate, HijrahDate.from(accessor)); + assertEquals(expectedTime, result.toLocalTime()); } else { try { @@ -688,18 +705,17 @@ public class TestUmmAlQuraChronology { ZonedDateTime zonedDateTime = ZonedDateTime.of(2012, 2, 29, 2, 7, 1, 1, ZONE_RIYADH); ChronoZonedDateTime result = HijrahChronology.INSTANCE.zonedDateTime(offsetDateTime.toInstant(), offsetDateTime.getOffset()); - assertEquals(result.toLocalDate(), HijrahChronology.INSTANCE.date(1433, 4, 7)); - assertEquals(result.toLocalTime(), LocalTime.of(2, 7, 1, 1)); + assertEquals(HijrahChronology.INSTANCE.date(1433, 4, 7), result.toLocalDate()); + assertEquals(LocalTime.of(2, 7, 1, 1), result.toLocalTime()); result = HijrahChronology.INSTANCE.zonedDateTime(zonedDateTime.toInstant(), zonedDateTime.getOffset()); - assertEquals(result.toLocalDate(), HijrahChronology.INSTANCE.date(1433, 4, 7)); - assertEquals(result.toLocalTime(), LocalTime.of(2, 7, 1, 1)); + assertEquals(HijrahChronology.INSTANCE.date(1433, 4, 7), result.toLocalDate()); + assertEquals(LocalTime.of(2, 7, 1, 1), result.toLocalTime()); } //----------------------------------------------------------------------- // localDateTime() //----------------------------------------------------------------------- - @DataProvider(name="localDateTime") Object[][] data_localDateTime() { return new Object[][] { {LocalDateTime.of(2012, 2, 29, 2, 7), HijrahChronology.INSTANCE.date(1433, 4, 7), LocalTime.of(2, 7), null}, @@ -713,13 +729,14 @@ public class TestUmmAlQuraChronology { } // Test to verify local date time values from various date instances defined in the localDateTime data provider - @Test(dataProvider="localDateTime") + @ParameterizedTest + @MethodSource("data_localDateTime") public void test_localDateTime(TemporalAccessor accessor, HijrahDate expectedDate, LocalTime expectedTime, Class expectedEx) { if (expectedEx == null) { ChronoLocalDateTime result = HijrahChronology.INSTANCE.localDateTime(accessor); - assertEquals(result.toLocalDate(), expectedDate); - assertEquals(HijrahDate.from(accessor), expectedDate); - assertEquals(result.toLocalTime(), expectedTime); + assertEquals(expectedDate, result.toLocalDate()); + assertEquals(expectedDate, HijrahDate.from(accessor)); + assertEquals(expectedTime, result.toLocalTime()); } else { try { ChronoLocalDateTime result = HijrahChronology.INSTANCE.localDateTime(accessor); @@ -731,7 +748,6 @@ public class TestUmmAlQuraChronology { } // Sample Hijrah & Minguo Dates - @DataProvider(name="hijrahToMinguo") Object[][] data_hijrahToMinguo() { return new Object[][] { {HijrahDate.of(1350,5,15), MinguoDate.of(20,9,28)}, @@ -743,13 +759,13 @@ public class TestUmmAlQuraChronology { } // Test to verify the date conversion from Hijrah to Minguo chronology - @Test(dataProvider="hijrahToMinguo") + @ParameterizedTest + @MethodSource("data_hijrahToMinguo") public void test_hijrahToMinguo(HijrahDate hijrah, MinguoDate minguo) { - assertEquals(MinguoChronology.INSTANCE.date(hijrah), minguo); + assertEquals(minguo, MinguoChronology.INSTANCE.date(hijrah)); } // Sample Hijrah & Thai Dates - @DataProvider(name="hijrahToThai") Object[][] data_hijrahToThai() { return new Object[][] { {HijrahDate.of(1350,5,15), ThaiBuddhistDate.of(2474,9,28)}, @@ -761,13 +777,13 @@ public class TestUmmAlQuraChronology { } // Test to verify the date conversion from Hijrah to Thai chronology - @Test(dataProvider="hijrahToThai") + @ParameterizedTest + @MethodSource("data_hijrahToThai") public void test_hijrahToThai(HijrahDate hijrah, ThaiBuddhistDate thai) { - assertEquals(ThaiBuddhistChronology.INSTANCE.date(hijrah), thai); + assertEquals(thai, ThaiBuddhistChronology.INSTANCE.date(hijrah)); } // Sample Hijrah & Japanese Dates - @DataProvider(name="hijrahToJapanese") Object[][] data_hijrahToJapanese() { return new Object[][] { {HijrahDate.of(1350,5,15), "Japanese Showa 6-09-28"}, @@ -781,12 +797,12 @@ public class TestUmmAlQuraChronology { } // Test to verify the date conversion from Hijrah to Japanese chronology - @Test(dataProvider="hijrahToJapanese") + @ParameterizedTest + @MethodSource("data_hijrahToJapanese") public void test_hijrahToJapanese(HijrahDate hijrah, String japanese) { - assertEquals(JapaneseChronology.INSTANCE.date(hijrah).toString(), japanese); + assertEquals(japanese, JapaneseChronology.INSTANCE.date(hijrah).toString()); } - @DataProvider(name="alignedDayOfWeekInMonthTestDates") Object[][] data_alignedDayOfWeekInMonth() { return new Object[][] { {1437, 9, 1, 1, 1}, @@ -799,18 +815,20 @@ public class TestUmmAlQuraChronology { //----------------------------------------------------------------------- // Test for aligned-week-of-month calculation based on the day-of-month //----------------------------------------------------------------------- - @Test(dataProvider="alignedDayOfWeekInMonthTestDates") + @ParameterizedTest + @MethodSource("data_alignedDayOfWeekInMonth") public void test_alignedWeekOfMonth(int year, int month, int dom, int wom, int dowm) { HijrahDate date = HijrahChronology.INSTANCE.date(year, month, dom); - assertEquals(date.getLong(ChronoField.ALIGNED_WEEK_OF_MONTH), wom); + assertEquals(wom, date.getLong(ChronoField.ALIGNED_WEEK_OF_MONTH)); } //----------------------------------------------------------------------- // Test for aligned-day-of-week calculation based on the day-of-month //----------------------------------------------------------------------- - @Test(dataProvider="alignedDayOfWeekInMonthTestDates") + @ParameterizedTest + @MethodSource("data_alignedDayOfWeekInMonth") public void test_alignedDayOfWeekInMonth(int year, int month, int dom, int wom, int dowm) { HijrahDate date = HijrahChronology.INSTANCE.date(year, month, dom); - assertEquals(date.getLong(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), dowm); + assertEquals(dowm, date.getLong(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); } } diff --git a/test/jdk/java/time/test/java/time/format/AbstractTestPrinterParser.java b/test/jdk/java/time/test/java/time/format/AbstractTestPrinterParser.java index 023f5c190ad..b4e9590c23d 100644 --- a/test/jdk/java/time/test/java/time/format/AbstractTestPrinterParser.java +++ b/test/jdk/java/time/test/java/time/format/AbstractTestPrinterParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -72,13 +72,11 @@ import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalField; import java.util.Locale; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeEach; /** * Abstract PrinterParser test. */ -@Test public class AbstractTestPrinterParser { protected StringBuilder buf; @@ -88,7 +86,7 @@ public class AbstractTestPrinterParser { protected DecimalStyle decimalStyle; - @BeforeMethod + @BeforeEach public void setUp() { buf = new StringBuilder(); builder = new DateTimeFormatterBuilder(); diff --git a/test/jdk/java/time/test/java/time/format/TestCharLiteralParser.java b/test/jdk/java/time/test/java/time/format/TestCharLiteralParser.java index 696aab0f539..d1896c865e1 100644 --- a/test/jdk/java/time/test/java/time/format/TestCharLiteralParser.java +++ b/test/jdk/java/time/test/java/time/format/TestCharLiteralParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -60,24 +60,25 @@ package test.java.time.format; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.text.ParsePosition; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalQueries; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test CharLiteralPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestCharLiteralParser extends AbstractTestPrinterParser { - @DataProvider(name="success") Object[][] data_success() { return new Object[][] { // match @@ -100,24 +101,24 @@ public class TestCharLiteralParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="success") + @ParameterizedTest + @MethodSource("data_success") public void test_parse_success(char c, boolean caseSensitive, String text, int pos, int expectedPos) { setCaseSensitive(caseSensitive); ParsePosition ppos = new ParsePosition(pos); TemporalAccessor parsed = getFormatter(c).parseUnresolved(text, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getIndex(), expectedPos); + assertEquals(expectedPos, ppos.getIndex()); } else { - assertEquals(ppos.getIndex(), expectedPos); - assertEquals(parsed.isSupported(YEAR), false); - assertEquals(parsed.query(TemporalQueries.chronology()), null); - assertEquals(parsed.query(TemporalQueries.zoneId()), null); + assertEquals(expectedPos, ppos.getIndex()); + assertEquals(false, parsed.isSupported(YEAR)); + assertEquals(null, parsed.query(TemporalQueries.chronology())); + assertEquals(null, parsed.query(TemporalQueries.zoneId())); } } //----------------------------------------------------------------------- - @DataProvider(name="error") Object[][] data_error() { return new Object[][] { {'a', "a", -1, IndexOutOfBoundsException.class}, @@ -125,7 +126,8 @@ public class TestCharLiteralParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="error") + @ParameterizedTest + @MethodSource("data_error") public void test_parse_error(char c, String text, int pos, Class expected) { try { ParsePosition ppos = new ParsePosition(pos); diff --git a/test/jdk/java/time/test/java/time/format/TestCharLiteralPrinter.java b/test/jdk/java/time/test/java/time/format/TestCharLiteralPrinter.java index 6aaf6a5b97d..71b7c7bed53 100644 --- a/test/jdk/java/time/test/java/time/format/TestCharLiteralPrinter.java +++ b/test/jdk/java/time/test/java/time/format/TestCharLiteralPrinter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,42 +59,45 @@ */ package test.java.time.format; -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * Test CharLiteralPrinterParser. */ -@Test public class TestCharLiteralPrinter extends AbstractTestPrinterParser { //----------------------------------------------------------------------- + @Test public void test_print_emptyCalendrical() throws Exception { buf.append("EXISTING"); getFormatter('a').formatTo(EMPTY_DTA, buf); - assertEquals(buf.toString(), "EXISTINGa"); + assertEquals("EXISTINGa", buf.toString()); } + @Test public void test_print_dateTime() throws Exception { buf.append("EXISTING"); getFormatter('a').formatTo(dta, buf); - assertEquals(buf.toString(), "EXISTINGa"); + assertEquals("EXISTINGa", buf.toString()); } + @Test public void test_print_emptyAppendable() throws Exception { getFormatter('a').formatTo(dta, buf); - assertEquals(buf.toString(), "a"); + assertEquals("a", buf.toString()); } //----------------------------------------------------------------------- + @Test public void test_toString() throws Exception { - assertEquals(getFormatter('a').toString(), "'a'"); + assertEquals("'a'", getFormatter('a').toString()); } //----------------------------------------------------------------------- + @Test public void test_toString_apos() throws Exception { - assertEquals(getFormatter('\'').toString(), "''"); + assertEquals("''", getFormatter('\'').toString()); } } diff --git a/test/jdk/java/time/test/java/time/format/TestDateTimeFormatter.java b/test/jdk/java/time/test/java/time/format/TestDateTimeFormatter.java index f6c1b253573..2ccc0da8f58 100644 --- a/test/jdk/java/time/test/java/time/format/TestDateTimeFormatter.java +++ b/test/jdk/java/time/test/java/time/format/TestDateTimeFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -60,11 +60,12 @@ package test.java.time.format; import static java.time.temporal.ChronoField.DAY_OF_MONTH; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.time.DateTimeException; import java.time.DayOfWeek; @@ -93,14 +94,16 @@ import java.time.temporal.TemporalAccessor; import java.util.Locale; import java.util.function.Function; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatter. * @bug 8085887 8293146 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestDateTimeFormatter { @Test @@ -203,7 +206,6 @@ public class TestDateTimeFormatter { assertTrue(msg.contains("11:30:56"), msg); } - @DataProvider(name="nozone_exception_cases") Object[][] exceptionCases() { return new Object[][] { {LocalDateTime.of(2000, 1, 1, 1, 1), "z", "ZoneId"}, @@ -213,7 +215,8 @@ public class TestDateTimeFormatter { // Test cases that should throw an exception with a cogent message // containing the Type being queried and the Temporal being queried. - @Test(dataProvider="nozone_exception_cases") + @ParameterizedTest + @MethodSource("exceptionCases") public void test_throws_message(Temporal temporal, String pattern, String queryName) { DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern); try { @@ -277,7 +280,6 @@ public class TestDateTimeFormatter { private static final DateTimeFormatter STRICT_WEEK = DateTimeFormatter.ofPattern("YYYY-'W'ww-e") .withResolverStyle(ResolverStyle.STRICT); private static final Locale EGYPT = Locale.forLanguageTag("en-EG"); - @DataProvider(name = "week53Dates") Object[][] data_week53Dates() { return new Object[][] { // WeekFields[SUNDAY,1] @@ -321,15 +323,14 @@ public class TestDateTimeFormatter { }; } - @Test (dataProvider = "week53Dates") + @ParameterizedTest + @MethodSource("data_week53Dates") public void test_week_53(String weekDate, Locale locale, LocalDate expected) { var f = STRICT_WEEK.withLocale(locale); if (expected != null) { - assertEquals(LocalDate.parse(weekDate, f), expected); + assertEquals(expected, LocalDate.parse(weekDate, f)); } else { - assertThrows(DateTimeException.class, () -> { - LocalDate.parse(weekDate, f); - }); + assertThrows(DateTimeException.class, () -> LocalDate.parse(weekDate, f)); } } } diff --git a/test/jdk/java/time/test/java/time/format/TestDateTimeFormatterBuilder.java b/test/jdk/java/time/test/java/time/format/TestDateTimeFormatterBuilder.java index 6d62dfe1265..294d204a216 100644 --- a/test/jdk/java/time/test/java/time/format/TestDateTimeFormatterBuilder.java +++ b/test/jdk/java/time/test/java/time/format/TestDateTimeFormatterBuilder.java @@ -66,9 +66,10 @@ import static java.time.temporal.ChronoField.HOUR_OF_DAY; import static java.time.temporal.ChronoField.MINUTE_OF_HOUR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; import java.text.ParsePosition; import java.time.LocalDate; @@ -95,19 +96,22 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatterBuilder. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestDateTimeFormatterBuilder { private DateTimeFormatterBuilder builder; - @BeforeMethod + @BeforeEach public void setUp() { builder = new DateTimeFormatterBuilder(); } @@ -116,7 +120,7 @@ public class TestDateTimeFormatterBuilder { @Test public void test_toFormatter_empty() throws Exception { DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), ""); + assertEquals("", f.toString()); } //----------------------------------------------------------------------- @@ -124,14 +128,14 @@ public class TestDateTimeFormatterBuilder { public void test_parseCaseSensitive() throws Exception { builder.parseCaseSensitive(); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "ParseCaseSensitive(true)"); + assertEquals("ParseCaseSensitive(true)", f.toString()); } @Test public void test_parseCaseInsensitive() throws Exception { builder.parseCaseInsensitive(); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "ParseCaseSensitive(false)"); + assertEquals("ParseCaseSensitive(false)", f.toString()); } //----------------------------------------------------------------------- @@ -139,14 +143,14 @@ public class TestDateTimeFormatterBuilder { public void test_parseStrict() throws Exception { builder.parseStrict(); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "ParseStrict(true)"); + assertEquals("ParseStrict(true)", f.toString()); } @Test public void test_parseLenient() throws Exception { builder.parseLenient(); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "ParseStrict(false)"); + assertEquals("ParseStrict(false)", f.toString()); } //----------------------------------------------------------------------- @@ -154,12 +158,12 @@ public class TestDateTimeFormatterBuilder { public void test_appendValue_1arg() throws Exception { builder.appendValue(DAY_OF_MONTH); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(DayOfMonth)"); + assertEquals("Value(DayOfMonth)", f.toString()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValue_1arg_null() throws Exception { - builder.appendValue(null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValue(null)); } //----------------------------------------------------------------------- @@ -167,22 +171,22 @@ public class TestDateTimeFormatterBuilder { public void test_appendValue_2arg() throws Exception { builder.appendValue(DAY_OF_MONTH, 3); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(DayOfMonth,3)"); + assertEquals("Value(DayOfMonth,3)", f.toString()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValue_2arg_null() throws Exception { - builder.appendValue(null, 3); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValue(null, 3)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_2arg_widthTooSmall() throws Exception { - builder.appendValue(DAY_OF_MONTH, 0); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 0)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_2arg_widthTooBig() throws Exception { - builder.appendValue(DAY_OF_MONTH, 20); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 20)); } //----------------------------------------------------------------------- @@ -190,42 +194,42 @@ public class TestDateTimeFormatterBuilder { public void test_appendValue_3arg() throws Exception { builder.appendValue(DAY_OF_MONTH, 2, 3, SignStyle.NORMAL); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(DayOfMonth,2,3,NORMAL)"); + assertEquals("Value(DayOfMonth,2,3,NORMAL)", f.toString()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValue_3arg_nullField() throws Exception { - builder.appendValue(null, 2, 3, SignStyle.NORMAL); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValue(null, 2, 3, SignStyle.NORMAL)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_3arg_minWidthTooSmall() throws Exception { - builder.appendValue(DAY_OF_MONTH, 0, 2, SignStyle.NORMAL); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 0, 2, SignStyle.NORMAL)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_3arg_minWidthTooBig() throws Exception { - builder.appendValue(DAY_OF_MONTH, 20, 2, SignStyle.NORMAL); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 20, 2, SignStyle.NORMAL)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_3arg_maxWidthTooSmall() throws Exception { - builder.appendValue(DAY_OF_MONTH, 2, 0, SignStyle.NORMAL); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 2, 0, SignStyle.NORMAL)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_3arg_maxWidthTooBig() throws Exception { - builder.appendValue(DAY_OF_MONTH, 2, 20, SignStyle.NORMAL); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 2, 20, SignStyle.NORMAL)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendValue_3arg_maxWidthMinWidth() throws Exception { - builder.appendValue(DAY_OF_MONTH, 4, 2, SignStyle.NORMAL); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendValue(DAY_OF_MONTH, 4, 2, SignStyle.NORMAL)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValue_3arg_nullSignStyle() throws Exception { - builder.appendValue(DAY_OF_MONTH, 2, 3, null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValue(DAY_OF_MONTH, 2, 3, null)); } //----------------------------------------------------------------------- @@ -233,30 +237,30 @@ public class TestDateTimeFormatterBuilder { public void test_appendValue_subsequent2_parse3() throws Exception { builder.appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL).appendValue(DAY_OF_MONTH, 2); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear,1,2,NORMAL)Value(DayOfMonth,2)"); + assertEquals("Value(MonthOfYear,1,2,NORMAL)Value(DayOfMonth,2)", f.toString()); TemporalAccessor parsed = f.parseUnresolved("123", new ParsePosition(0)); - assertEquals(parsed.getLong(MONTH_OF_YEAR), 1L); - assertEquals(parsed.getLong(DAY_OF_MONTH), 23L); + assertEquals(1L, parsed.getLong(MONTH_OF_YEAR)); + assertEquals(23L, parsed.getLong(DAY_OF_MONTH)); } @Test public void test_appendValue_subsequent2_parse4() throws Exception { builder.appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL).appendValue(DAY_OF_MONTH, 2); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear,1,2,NORMAL)Value(DayOfMonth,2)"); + assertEquals("Value(MonthOfYear,1,2,NORMAL)Value(DayOfMonth,2)", f.toString()); TemporalAccessor parsed = f.parseUnresolved("0123", new ParsePosition(0)); - assertEquals(parsed.getLong(MONTH_OF_YEAR), 1L); - assertEquals(parsed.getLong(DAY_OF_MONTH), 23L); + assertEquals(1L, parsed.getLong(MONTH_OF_YEAR)); + assertEquals(23L, parsed.getLong(DAY_OF_MONTH)); } @Test public void test_appendValue_subsequent2_parse5() throws Exception { builder.appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL).appendValue(DAY_OF_MONTH, 2).appendLiteral('4'); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear,1,2,NORMAL)Value(DayOfMonth,2)'4'"); + assertEquals("Value(MonthOfYear,1,2,NORMAL)Value(DayOfMonth,2)'4'", f.toString()); TemporalAccessor parsed = f.parseUnresolved("01234", new ParsePosition(0)); - assertEquals(parsed.getLong(MONTH_OF_YEAR), 1L); - assertEquals(parsed.getLong(DAY_OF_MONTH), 23L); + assertEquals(1L, parsed.getLong(MONTH_OF_YEAR)); + assertEquals(23L, parsed.getLong(DAY_OF_MONTH)); } @Test @@ -266,38 +270,38 @@ public class TestDateTimeFormatterBuilder { .appendValue(MONTH_OF_YEAR, 2) .appendValue(DAY_OF_MONTH, 2); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(Year,4,10,EXCEEDS_PAD)Value(MonthOfYear,2)Value(DayOfMonth,2)"); + assertEquals("Value(Year,4,10,EXCEEDS_PAD)Value(MonthOfYear,2)Value(DayOfMonth,2)", f.toString()); TemporalAccessor parsed = f.parseUnresolved("20090630", new ParsePosition(0)); - assertEquals(parsed.getLong(YEAR), 2009L); - assertEquals(parsed.getLong(MONTH_OF_YEAR), 6L); - assertEquals(parsed.getLong(DAY_OF_MONTH), 30L); + assertEquals(2009L, parsed.getLong(YEAR)); + assertEquals(6L, parsed.getLong(MONTH_OF_YEAR)); + assertEquals(30L, parsed.getLong(DAY_OF_MONTH)); } //----------------------------------------------------------------------- - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendValueReduced_null() throws Exception { - builder.appendValueReduced(null, 2, 2, 2000); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendValueReduced(null, 2, 2, 2000)); } @Test public void test_appendValueReduced() throws Exception { builder.appendValueReduced(YEAR, 2, 2, 2000); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "ReducedValue(Year,2,2,2000)"); + assertEquals("ReducedValue(Year,2,2,2000)", f.toString()); TemporalAccessor parsed = f.parseUnresolved("12", new ParsePosition(0)); - assertEquals(parsed.getLong(YEAR), 2012L); + assertEquals(2012L, parsed.getLong(YEAR)); } @Test public void test_appendValueReduced_subsequent_parse() throws Exception { builder.appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL).appendValueReduced(YEAR, 2, 2, 2000); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear,1,2,NORMAL)ReducedValue(Year,2,2,2000)"); + assertEquals("Value(MonthOfYear,1,2,NORMAL)ReducedValue(Year,2,2,2000)", f.toString()); ParsePosition ppos = new ParsePosition(0); TemporalAccessor parsed = f.parseUnresolved("123", ppos); assertNotNull(parsed, "Parse failed: " + ppos.toString()); - assertEquals(parsed.getLong(MONTH_OF_YEAR), 1L); - assertEquals(parsed.getLong(YEAR), 2023L); + assertEquals(1L, parsed.getLong(MONTH_OF_YEAR)); + assertEquals(2023L, parsed.getLong(YEAR)); } //----------------------------------------------------------------------- @@ -307,42 +311,42 @@ public class TestDateTimeFormatterBuilder { public void test_appendFraction_4arg() throws Exception { builder.appendFraction(MINUTE_OF_HOUR, 1, 9, false); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Fraction(MinuteOfHour,1,9)"); + assertEquals("Fraction(MinuteOfHour,1,9)", f.toString()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendFraction_4arg_nullRule() throws Exception { - builder.appendFraction(null, 1, 9, false); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendFraction(null, 1, 9, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_invalidRuleNotFixedSet() throws Exception { - builder.appendFraction(DAY_OF_MONTH, 1, 9, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(DAY_OF_MONTH, 1, 9, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_minTooSmall() throws Exception { - builder.appendFraction(MINUTE_OF_HOUR, -1, 9, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(MINUTE_OF_HOUR, -1, 9, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_minTooBig() throws Exception { - builder.appendFraction(MINUTE_OF_HOUR, 10, 9, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(MINUTE_OF_HOUR, 10, 9, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_maxTooSmall() throws Exception { - builder.appendFraction(MINUTE_OF_HOUR, 0, -1, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(MINUTE_OF_HOUR, 0, -1, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_maxTooBig() throws Exception { - builder.appendFraction(MINUTE_OF_HOUR, 1, 10, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(MINUTE_OF_HOUR, 1, 10, false)); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_appendFraction_4arg_maxWidthMinWidth() throws Exception { - builder.appendFraction(MINUTE_OF_HOUR, 9, 3, false); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendFraction(MINUTE_OF_HOUR, 9, 3, false)); } //----------------------------------------------------------------------- @@ -352,12 +356,12 @@ public class TestDateTimeFormatterBuilder { public void test_appendText_1arg() throws Exception { builder.appendText(MONTH_OF_YEAR); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Text(MonthOfYear)"); + assertEquals("Text(MonthOfYear)", f.toString()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendText_1arg_null() throws Exception { - builder.appendText(null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendText(null)); } //----------------------------------------------------------------------- @@ -365,17 +369,17 @@ public class TestDateTimeFormatterBuilder { public void test_appendText_2arg() throws Exception { builder.appendText(MONTH_OF_YEAR, TextStyle.SHORT); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Text(MonthOfYear,SHORT)"); + assertEquals("Text(MonthOfYear,SHORT)", f.toString()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendText_2arg_nullRule() throws Exception { - builder.appendText(null, TextStyle.SHORT); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendText(null, TextStyle.SHORT)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendText_2arg_nullStyle() throws Exception { - builder.appendText(MONTH_OF_YEAR, (TextStyle) null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendText(MONTH_OF_YEAR, (TextStyle) null)); } //----------------------------------------------------------------------- @@ -396,17 +400,17 @@ public class TestDateTimeFormatterBuilder { map.put(12L, "DBR"); builder.appendText(MONTH_OF_YEAR, map); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Text(MonthOfYear)"); // TODO: toString should be different? + assertEquals("Text(MonthOfYear)", f.toString()); // TODO: toString should be different? } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendTextMap_nullRule() throws Exception { - builder.appendText(null, new HashMap()); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendText(null, new HashMap())); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendTextMap_nullStyle() throws Exception { - builder.appendText(MONTH_OF_YEAR, (Map) null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendText(MONTH_OF_YEAR, (Map) null)); } //----------------------------------------------------------------------- @@ -416,10 +420,9 @@ public class TestDateTimeFormatterBuilder { public void test_appendOffsetId() throws Exception { builder.appendOffsetId(); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Offset(+HH:MM:ss,'Z')"); + assertEquals("Offset(+HH:MM:ss,'Z')", f.toString()); } - @DataProvider(name="offsetPatterns") Object[][] data_offsetPatterns() { return new Object[][] { {"+HH", 2, 0, 0, "+02"}, @@ -466,24 +469,25 @@ public class TestDateTimeFormatterBuilder { }; } - @Test(dataProvider="offsetPatterns") + @ParameterizedTest + @MethodSource("data_offsetPatterns") public void test_appendOffset_format(String pattern, int h, int m, int s, String expected) throws Exception { builder.appendOffset(pattern, "Z"); DateTimeFormatter f = builder.toFormatter(); ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(h, m, s); - assertEquals(f.format(offset), expected); + assertEquals(expected, f.format(offset)); } - @Test(dataProvider="offsetPatterns") + @ParameterizedTest + @MethodSource("data_offsetPatterns") public void test_appendOffset_parse(String pattern, int h, int m, int s, String expected) throws Exception { builder.appendOffset(pattern, "Z"); DateTimeFormatter f = builder.toFormatter(); ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(h, m, s); ZoneOffset parsed = f.parse(expected, ZoneOffset::from); - assertEquals(f.format(parsed), expected); + assertEquals(expected, f.format(parsed)); } - @DataProvider(name="badOffsetPatterns") Object[][] data_badOffsetPatterns() { return new Object[][] { {"HH"}, @@ -498,19 +502,20 @@ public class TestDateTimeFormatterBuilder { }; } - @Test(dataProvider="badOffsetPatterns", expectedExceptions=IllegalArgumentException.class) + @ParameterizedTest + @MethodSource("data_badOffsetPatterns") public void test_appendOffset_badPattern(String pattern) throws Exception { - builder.appendOffset(pattern, "Z"); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.appendOffset(pattern, "Z")); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendOffset_3arg_nullText() throws Exception { - builder.appendOffset("+HH:MM", null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendOffset("+HH:MM", null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendOffset_3arg_nullPattern() throws Exception { - builder.appendOffset(null, "Z"); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendOffset(null, "Z")); } //----------------------------------------------------------------------- @@ -520,19 +525,19 @@ public class TestDateTimeFormatterBuilder { public void test_appendZoneId() throws Exception { builder.appendZoneId(); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "ZoneId()"); + assertEquals("ZoneId()", f.toString()); } @Test public void test_appendZoneText_1arg() throws Exception { builder.appendZoneText(TextStyle.FULL); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "ZoneText(FULL)"); + assertEquals("ZoneText(FULL)", f.toString()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendZoneText_1arg_nullText() throws Exception { - builder.appendZoneText(null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendZoneText(null)); } //----------------------------------------------------------------------- @@ -542,15 +547,14 @@ public class TestDateTimeFormatterBuilder { public void test_appendDayPeriodText_1arg() throws Exception { builder.appendDayPeriodText(TextStyle.FULL); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "DayPeriod(FULL)"); + assertEquals("DayPeriod(FULL)", f.toString()); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_appendDayPeriodText_1arg_nullText() throws Exception { - builder.appendDayPeriodText(null); + Assertions.assertThrows(NullPointerException.class, () -> builder.appendDayPeriodText(null)); } - @DataProvider(name="dayPeriodFormat") Object[][] data_dayPeriodFormat() { return new Object[][] { {0, 0, TextStyle.FULL, Locale.US, "midnight"}, @@ -588,15 +592,15 @@ public class TestDateTimeFormatterBuilder { {23, 0, TextStyle.NARROW, Locale.JAPAN, "\u591c\u4e2d"}, }; } - @Test (dataProvider="dayPeriodFormat") + @ParameterizedTest + @MethodSource("data_dayPeriodFormat") public void test_dayPeriodFormat(int hod, int moh, TextStyle ts, Locale l, String expected) throws Exception { builder.appendDayPeriodText(ts); LocalTime t = LocalTime.of(hod, moh); DateTimeFormatter f = builder.toFormatter().withLocale(l); - assertEquals(f.format(t), expected); + assertEquals(expected, f.format(t)); } - @DataProvider(name="dayPeriodParse") Object[][] data_dayPeriodParse() { return new Object[][] { {TextStyle.FULL, Locale.US, 0, 0, "midnight"}, @@ -638,16 +642,16 @@ public class TestDateTimeFormatterBuilder { {TextStyle.NARROW, Locale.JAPAN, 21, 0, "\u591c"}, }; } - @Test (dataProvider="dayPeriodParse") + @ParameterizedTest + @MethodSource("data_dayPeriodParse") public void test_dayPeriodParse(TextStyle ts, Locale l, long hod, long moh, String dayPeriod) throws Exception { builder.appendDayPeriodText(ts); DateTimeFormatter f = builder.toFormatter().withLocale(l); var p = f.parse(dayPeriod); - assertEquals(p.getLong(HOUR_OF_DAY), hod); - assertEquals(p.getLong(MINUTE_OF_HOUR), moh); + assertEquals(hod, p.getLong(HOUR_OF_DAY)); + assertEquals(moh, p.getLong(MINUTE_OF_HOUR)); } - @DataProvider(name="dayPeriodParsePattern") Object[][] data_dayPeriodParsePattern() { return new Object[][] { {"H B", "23 at night", 23}, @@ -663,15 +667,15 @@ public class TestDateTimeFormatterBuilder { }; } - @Test (dataProvider="dayPeriodParsePattern") + @ParameterizedTest + @MethodSource("data_dayPeriodParsePattern") public void test_dayPeriodParsePattern(String pattern, String hourDayPeriod, long expected) throws Exception { builder.appendPattern(pattern); DateTimeFormatter f = builder.toFormatter().withLocale(Locale.US); var p = f.parse(hourDayPeriod); - assertEquals(p.getLong(HOUR_OF_DAY), expected); + assertEquals(expected, p.getLong(HOUR_OF_DAY)); } - @DataProvider(name="dayPeriodParseMidnight") Object[][] data_dayPeriodParseMidnight() { return new Object[][] { {"u-M-d H:m B", "2020-11-07 00:00 midnight", 7, 0}, @@ -679,16 +683,16 @@ public class TestDateTimeFormatterBuilder { }; } - @Test (dataProvider="dayPeriodParseMidnight") + @ParameterizedTest + @MethodSource("data_dayPeriodParseMidnight") public void test_dayPeriodParseMidnight(String pattern, String dateTime, long expectedDOM, long expectedHOD) throws Exception { builder.appendPattern(pattern); DateTimeFormatter f = builder.toFormatter().withLocale(Locale.US); var p = f.parse(dateTime); - assertEquals(p.getLong(DAY_OF_MONTH), expectedDOM); - assertEquals(p.getLong(HOUR_OF_DAY), expectedHOD); + assertEquals(expectedDOM, p.getLong(DAY_OF_MONTH)); + assertEquals(expectedHOD, p.getLong(HOUR_OF_DAY)); } - @DataProvider(name="dayPeriodParseInvalid") Object[][] data_dayPeriodParseInvalid() { return new Object[][] { {TextStyle.FULL, ResolverStyle.SMART, Locale.US, "00:01 midnight", "00:00"}, @@ -748,7 +752,8 @@ public class TestDateTimeFormatterBuilder { {TextStyle.NARROW, ResolverStyle.LENIENT, Locale.JAPAN, "23:00 \u591c", "19:00-23:00"}, }; } - @Test (dataProvider="dayPeriodParseInvalid") + @ParameterizedTest + @MethodSource("data_dayPeriodParseInvalid") public void test_dayPeriodParseInvalid(TextStyle ts, ResolverStyle rs, Locale l, String dayPeriod, String periodRange) throws Exception { try { builder.append(ISO_LOCAL_TIME).appendLiteral(' ').appendDayPeriodText(ts) @@ -759,13 +764,11 @@ public class TestDateTimeFormatterBuilder { throw new RuntimeException("DateTimeParseException should be thrown"); } } catch (DateTimeParseException e) { - assertEquals(e.getCause().getMessage(), - "Conflict found: Resolved time " + dayPeriod.substring(0, 5) + " conflicts with " + - "DayPeriod(" + periodRange + ")"); + assertEquals("Conflict found: Resolved time " + dayPeriod.substring(0, 5) + " conflicts with " + + "DayPeriod(" + periodRange + ")", e.getCause().getMessage()); } } - @DataProvider(name="dayPeriodParsePatternInvalid") Object[][] data_dayPeriodParsePatternInvalid() { return new Object[][] { {"H B", ResolverStyle.SMART, "47 at night", 23, null}, @@ -794,7 +797,8 @@ public class TestDateTimeFormatterBuilder { }; } - @Test (dataProvider="dayPeriodParsePatternInvalid") + @ParameterizedTest + @MethodSource("data_dayPeriodParsePatternInvalid") public void test_dayPeriodParsePatternInvalid(String pattern, ResolverStyle rs, String hourDayPeriod, long expected, Period expectedExcessDays) throws Exception { try { builder.appendPattern(pattern); @@ -803,18 +807,20 @@ public class TestDateTimeFormatterBuilder { if (rs != ResolverStyle.LENIENT) { throw new RuntimeException("DateTimeParseException should be thrown"); } - assertEquals(p.getLong(HOUR_OF_DAY), expected); - assertEquals(p.query(DateTimeFormatter.parsedExcessDays()), expectedExcessDays); + assertEquals(expected, p.getLong(HOUR_OF_DAY)); + assertEquals(expectedExcessDays, p.query(DateTimeFormatter.parsedExcessDays())); } catch (DateTimeParseException e) { // exception successfully thrown } } - @Test (expectedExceptions = DateTimeParseException.class) + @Test public void test_dayPeriodParseStrictNoTime() { - builder.appendPattern("B"); - DateTimeFormatter f = builder.toFormatter().withLocale(Locale.US).withResolverStyle(ResolverStyle.STRICT); - LocalTime.parse("at night", f); + Assertions.assertThrows(DateTimeParseException.class, () -> { + builder.appendPattern("B"); + DateTimeFormatter f = builder.toFormatter().withLocale(Locale.US).withResolverStyle(ResolverStyle.STRICT); + LocalTime.parse("at night", f); + }); } @Test @@ -880,7 +886,7 @@ public class TestDateTimeFormatterBuilder { .appendPattern(" B") .toFormatter() .withLocale(Locale.US); - assertEquals((long)dtf.parse("0 in the morning").getLong(ChronoField.HOUR_OF_DAY), 6L); + assertEquals(6L, (long)dtf.parse("0 in the morning").getLong(ChronoField.HOUR_OF_DAY)); try { dtf.parse("0 at night"); fail("DateTimeParseException should be thrown"); @@ -895,24 +901,24 @@ public class TestDateTimeFormatterBuilder { @Test public void test_padNext_1arg() { builder.appendValue(MONTH_OF_YEAR).appendLiteral(':').padNext(2).appendValue(DAY_OF_MONTH); - assertEquals(builder.toFormatter().format(LocalDate.of(2013, 2, 1)), "2: 1"); + assertEquals("2: 1", builder.toFormatter().format(LocalDate.of(2013, 2, 1))); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_padNext_1arg_invalidWidth() throws Exception { - builder.padNext(0); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.padNext(0)); } //----------------------------------------------------------------------- @Test public void test_padNext_2arg_dash() throws Exception { builder.appendValue(MONTH_OF_YEAR).appendLiteral(':').padNext(2, '-').appendValue(DAY_OF_MONTH); - assertEquals(builder.toFormatter().format(LocalDate.of(2013, 2, 1)), "2:-1"); + assertEquals("2:-1", builder.toFormatter().format(LocalDate.of(2013, 2, 1))); } - @Test(expectedExceptions=IllegalArgumentException.class) + @Test public void test_padNext_2arg_invalidWidth() throws Exception { - builder.padNext(0, '-'); + Assertions.assertThrows(IllegalArgumentException.class, () -> builder.padNext(0, '-')); } //----------------------------------------------------------------------- @@ -921,8 +927,8 @@ public class TestDateTimeFormatterBuilder { builder.appendValue(MONTH_OF_YEAR).appendLiteral(':') .padNext(5).optionalStart().appendValue(DAY_OF_MONTH).optionalEnd() .appendLiteral(':').appendValue(YEAR); - assertEquals(builder.toFormatter().format(LocalDate.of(2013, 2, 1)), "2: 1:2013"); - assertEquals(builder.toFormatter().format(YearMonth.of(2013, 2)), "2: :2013"); + assertEquals("2: 1:2013", builder.toFormatter().format(LocalDate.of(2013, 2, 1))); + assertEquals("2: :2013", builder.toFormatter().format(YearMonth.of(2013, 2))); } //----------------------------------------------------------------------- @@ -932,21 +938,21 @@ public class TestDateTimeFormatterBuilder { public void test_optionalStart_noEnd() throws Exception { builder.appendValue(MONTH_OF_YEAR).optionalStart().appendValue(DAY_OF_MONTH).appendValue(DAY_OF_WEEK); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear)[Value(DayOfMonth)Value(DayOfWeek)]"); + assertEquals("Value(MonthOfYear)[Value(DayOfMonth)Value(DayOfWeek)]", f.toString()); } @Test public void test_optionalStart2_noEnd() throws Exception { builder.appendValue(MONTH_OF_YEAR).optionalStart().appendValue(DAY_OF_MONTH).optionalStart().appendValue(DAY_OF_WEEK); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear)[Value(DayOfMonth)[Value(DayOfWeek)]]"); + assertEquals("Value(MonthOfYear)[Value(DayOfMonth)[Value(DayOfWeek)]]", f.toString()); } @Test public void test_optionalStart_doubleStart() throws Exception { builder.appendValue(MONTH_OF_YEAR).optionalStart().optionalStart().appendValue(DAY_OF_MONTH); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear)[[Value(DayOfMonth)]]"); + assertEquals("Value(MonthOfYear)[[Value(DayOfMonth)]]", f.toString()); } //----------------------------------------------------------------------- @@ -954,7 +960,7 @@ public class TestDateTimeFormatterBuilder { public void test_optionalEnd() throws Exception { builder.appendValue(MONTH_OF_YEAR).optionalStart().appendValue(DAY_OF_MONTH).optionalEnd().appendValue(DAY_OF_WEEK); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear)[Value(DayOfMonth)]Value(DayOfWeek)"); + assertEquals("Value(MonthOfYear)[Value(DayOfMonth)]Value(DayOfWeek)", f.toString()); } @Test @@ -962,39 +968,38 @@ public class TestDateTimeFormatterBuilder { builder.appendValue(MONTH_OF_YEAR).optionalStart().appendValue(DAY_OF_MONTH) .optionalStart().appendValue(DAY_OF_WEEK).optionalEnd().appendValue(DAY_OF_MONTH).optionalEnd(); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear)[Value(DayOfMonth)[Value(DayOfWeek)]Value(DayOfMonth)]"); + assertEquals("Value(MonthOfYear)[Value(DayOfMonth)[Value(DayOfWeek)]Value(DayOfMonth)]", f.toString()); } @Test public void test_optionalEnd_doubleStartSingleEnd() throws Exception { builder.appendValue(MONTH_OF_YEAR).optionalStart().optionalStart().appendValue(DAY_OF_MONTH).optionalEnd(); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear)[[Value(DayOfMonth)]]"); + assertEquals("Value(MonthOfYear)[[Value(DayOfMonth)]]", f.toString()); } @Test public void test_optionalEnd_doubleStartDoubleEnd() throws Exception { builder.appendValue(MONTH_OF_YEAR).optionalStart().optionalStart().appendValue(DAY_OF_MONTH).optionalEnd().optionalEnd(); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear)[[Value(DayOfMonth)]]"); + assertEquals("Value(MonthOfYear)[[Value(DayOfMonth)]]", f.toString()); } @Test public void test_optionalStartEnd_immediateStartEnd() throws Exception { builder.appendValue(MONTH_OF_YEAR).optionalStart().optionalEnd().appendValue(DAY_OF_MONTH); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), "Value(MonthOfYear)Value(DayOfMonth)"); + assertEquals("Value(MonthOfYear)Value(DayOfMonth)", f.toString()); } - @Test(expectedExceptions=IllegalStateException.class) + @Test public void test_optionalEnd_noStart() throws Exception { - builder.optionalEnd(); + Assertions.assertThrows(IllegalStateException.class, () -> builder.optionalEnd()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- - @DataProvider(name="validPatterns") Object[][] dataValid() { return new Object[][] { {"'a'", "'a'"}, @@ -1162,15 +1167,15 @@ public class TestDateTimeFormatterBuilder { }; } - @Test(dataProvider="validPatterns") + @ParameterizedTest + @MethodSource("dataValid") public void test_appendPattern_valid(String input, String expected) throws Exception { builder.appendPattern(input); DateTimeFormatter f = builder.toFormatter(); - assertEquals(f.toString(), expected); + assertEquals(expected, f.toString()); } //----------------------------------------------------------------------- - @DataProvider(name="invalidPatterns") Object[][] dataInvalid() { return new Object[][] { {"'"}, @@ -1241,17 +1246,19 @@ public class TestDateTimeFormatterBuilder { }; } - @Test(dataProvider="invalidPatterns", expectedExceptions=IllegalArgumentException.class) + @ParameterizedTest + @MethodSource("dataInvalid") public void test_appendPattern_invalid(String input) throws Exception { - try { - builder.appendPattern(input); - } catch (IllegalArgumentException ex) { - throw ex; - } + Assertions.assertThrows(IllegalArgumentException.class, () -> { + try { + builder.appendPattern(input); + } catch (IllegalArgumentException ex) { + throw ex; + } + }); } //----------------------------------------------------------------------- - @DataProvider(name="localePatterns") Object[][] localizedDateTimePatterns() { return new Object[][] { {FormatStyle.FULL, FormatStyle.FULL, IsoChronology.INSTANCE, Locale.US, "EEEE, MMMM d, y, h:mm:ss\u202fa zzzz"}, @@ -1269,26 +1276,27 @@ public class TestDateTimeFormatterBuilder { }; } - @Test(dataProvider="localePatterns") + @ParameterizedTest + @MethodSource("localizedDateTimePatterns") public void test_getLocalizedDateTimePattern(FormatStyle dateStyle, FormatStyle timeStyle, Chronology chrono, Locale locale, String expected) { String actual = DateTimeFormatterBuilder.getLocalizedDateTimePattern(dateStyle, timeStyle, chrono, locale); - assertEquals(actual, expected, "Pattern " + convertNonAscii(actual)); + assertEquals(expected, actual, "Pattern " + convertNonAscii(actual)); } - @Test(expectedExceptions=java.lang.IllegalArgumentException.class) + @Test public void test_getLocalizedDateTimePatternIAE() { - DateTimeFormatterBuilder.getLocalizedDateTimePattern(null, null, IsoChronology.INSTANCE, Locale.US); + Assertions.assertThrows(IllegalArgumentException.class, () -> DateTimeFormatterBuilder.getLocalizedDateTimePattern(null, null, IsoChronology.INSTANCE, Locale.US)); } - @Test(expectedExceptions=java.lang.NullPointerException.class) + @Test public void test_getLocalizedChronoNPE() { - DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, FormatStyle.SHORT, null, Locale.US); + Assertions.assertThrows(NullPointerException.class, () -> DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, FormatStyle.SHORT, null, Locale.US)); } - @Test(expectedExceptions=java.lang.NullPointerException.class) + @Test public void test_getLocalizedLocaleNPE() { - DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, FormatStyle.SHORT, IsoChronology.INSTANCE, null); + Assertions.assertThrows(NullPointerException.class, () -> DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, FormatStyle.SHORT, IsoChronology.INSTANCE, null)); } /** diff --git a/test/jdk/java/time/test/java/time/format/TestDateTimeFormatterBuilderWithLocale.java b/test/jdk/java/time/test/java/time/format/TestDateTimeFormatterBuilderWithLocale.java index a0981f0c4d8..ff44426dbe9 100644 --- a/test/jdk/java/time/test/java/time/format/TestDateTimeFormatterBuilderWithLocale.java +++ b/test/jdk/java/time/test/java/time/format/TestDateTimeFormatterBuilderWithLocale.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -84,27 +84,26 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatterBuilder. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestDateTimeFormatterBuilderWithLocale { private DateTimeFormatterBuilder builder; - @BeforeMethod + @BeforeEach public void setUp() { builder = new DateTimeFormatterBuilder(); } //----------------------------------------------------------------------- - @DataProvider(name="patternPrint") Object[][] data_patternPrint() { return new Object[][] { {"Q", date(2012, 2, 10), "1"}, @@ -115,15 +114,15 @@ public class TestDateTimeFormatterBuilderWithLocale { }; } - @Test(dataProvider="patternPrint") + @ParameterizedTest + @MethodSource("data_patternPrint") public void test_appendPattern_patternPrint(String input, Temporal temporal, String expected) throws Exception { DateTimeFormatter f = builder.appendPattern(input).toFormatter(Locale.UK); String test = f.format(temporal); - assertEquals(test, expected); + assertEquals(expected, test); } //----------------------------------------------------------------------- - @DataProvider(name="mapTextLookup") Object[][] data_mapTextLookup() { return new Object[][] { {IsoChronology.INSTANCE.date(1, 1, 1), Locale.ENGLISH}, @@ -133,7 +132,8 @@ public class TestDateTimeFormatterBuilderWithLocale { }; } - @Test(dataProvider="mapTextLookup") + @ParameterizedTest + @MethodSource("data_mapTextLookup") public void test_appendText_mapTextLookup(ChronoLocalDate date, Locale locale) { final String firstYear = "firstYear"; final String firstMonth = "firstMonth"; @@ -146,16 +146,15 @@ public class TestDateTimeFormatterBuilderWithLocale { .toFormatter(locale) .withResolverStyle(ResolverStyle.STRICT); - assertEquals(date.format(formatter), firstYearMonth); + assertEquals(firstYearMonth, date.format(formatter)); TemporalAccessor ta = formatter.parse(firstYearMonth); - assertEquals(ta.getLong(ChronoField.YEAR_OF_ERA), first); - assertEquals(ta.getLong(ChronoField.MONTH_OF_YEAR), first); + assertEquals(first, ta.getLong(ChronoField.YEAR_OF_ERA)); + assertEquals(first, ta.getLong(ChronoField.MONTH_OF_YEAR)); } //----------------------------------------------------------------------- - @DataProvider(name="localePatterns") Object[][] localizedDateTimePatterns() { return new Object[][] { // French Locale and ISO Chronology @@ -202,11 +201,12 @@ public class TestDateTimeFormatterBuilderWithLocale { }; } - @Test(dataProvider="localePatterns") + @ParameterizedTest + @MethodSource("localizedDateTimePatterns") public void test_getLocalizedDateTimePattern(FormatStyle dateStyle, FormatStyle timeStyle, Chronology chrono, Locale locale, String expected) { String actual = DateTimeFormatterBuilder.getLocalizedDateTimePattern(dateStyle, timeStyle, chrono, locale); - assertEquals(actual, expected, "Pattern " + convertNonAscii(actual)); + assertEquals(expected, actual, "Pattern " + convertNonAscii(actual)); } /** diff --git a/test/jdk/java/time/test/java/time/format/TestDateTimeParsing.java b/test/jdk/java/time/test/java/time/format/TestDateTimeParsing.java index 67c91e6ad7e..f50a99f8a0e 100644 --- a/test/jdk/java/time/test/java/time/format/TestDateTimeParsing.java +++ b/test/jdk/java/time/test/java/time/format/TestDateTimeParsing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -71,8 +71,9 @@ import static java.time.temporal.ChronoField.NANO_OF_SECOND; import static java.time.temporal.ChronoField.OFFSET_SECONDS; import static java.time.temporal.ChronoField.SECOND_OF_DAY; import static java.util.Locale.US; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import java.text.ParsePosition; import java.time.DateTimeException; @@ -88,14 +89,18 @@ import java.time.format.SignStyle; import java.time.temporal.TemporalAccessor; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @test * @summary Test parsing of edge cases. * @bug 8223773 8272473 8319640 */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestDateTimeParsing { private static final ZoneId PARIS = ZoneId.of("Europe/Paris"); @@ -132,7 +137,6 @@ public class TestDateTimeParsing { private static final String DTPE_MESSAGE = "Invalid value for HourOfAmPm (valid values 0 - 11): 12"; - @DataProvider(name = "instantZones") Object[][] data_instantZones() { return new Object[][] { {LOCALFIELDS_ZONEID, "2014-06-30 01:02:03 Europe/Paris", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, PARIS)}, @@ -154,37 +158,40 @@ public class TestDateTimeParsing { }; } - @Test(dataProvider = "instantZones") + @ParameterizedTest + @MethodSource("data_instantZones") public void test_parse_instantZones_ZDT(DateTimeFormatter formatter, String text, ZonedDateTime expected) { TemporalAccessor actual = formatter.parse(text); - assertEquals(ZonedDateTime.from(actual), expected); + assertEquals(expected, ZonedDateTime.from(actual)); } - @Test(dataProvider = "instantZones") + @ParameterizedTest + @MethodSource("data_instantZones") public void test_parse_instantZones_LDT(DateTimeFormatter formatter, String text, ZonedDateTime expected) { TemporalAccessor actual = formatter.parse(text); - assertEquals(LocalDateTime.from(actual), expected.toLocalDateTime()); + assertEquals(expected.toLocalDateTime(), LocalDateTime.from(actual)); } - @Test(dataProvider = "instantZones") + @ParameterizedTest + @MethodSource("data_instantZones") public void test_parse_instantZones_Instant(DateTimeFormatter formatter, String text, ZonedDateTime expected) { TemporalAccessor actual = formatter.parse(text); - assertEquals(Instant.from(actual), expected.toInstant()); + assertEquals(expected.toInstant(), Instant.from(actual)); } - @Test(dataProvider = "instantZones") + @ParameterizedTest + @MethodSource("data_instantZones") public void test_parse_instantZones_supported(DateTimeFormatter formatter, String text, ZonedDateTime expected) { TemporalAccessor actual = formatter.parse(text); - assertEquals(actual.isSupported(INSTANT_SECONDS), true); - assertEquals(actual.isSupported(EPOCH_DAY), true); - assertEquals(actual.isSupported(SECOND_OF_DAY), true); - assertEquals(actual.isSupported(NANO_OF_SECOND), true); - assertEquals(actual.isSupported(MICRO_OF_SECOND), true); - assertEquals(actual.isSupported(MILLI_OF_SECOND), true); + assertEquals(true, actual.isSupported(INSTANT_SECONDS)); + assertEquals(true, actual.isSupported(EPOCH_DAY)); + assertEquals(true, actual.isSupported(SECOND_OF_DAY)); + assertEquals(true, actual.isSupported(NANO_OF_SECOND)); + assertEquals(true, actual.isSupported(MICRO_OF_SECOND)); + assertEquals(true, actual.isSupported(MILLI_OF_SECOND)); } //----------------------------------------------------------------------- - @DataProvider(name = "instantNoZone") Object[][] data_instantNoZone() { return new Object[][] { {INSTANT, "2014-06-30T01:02:03Z", ZonedDateTime.of(2014, 6, 30, 1, 2, 3, 0, ZoneOffset.UTC).toInstant()}, @@ -193,55 +200,65 @@ public class TestDateTimeParsing { }; } - @Test(dataProvider = "instantNoZone", expectedExceptions = DateTimeException.class) + @ParameterizedTest + @MethodSource("data_instantNoZone") public void test_parse_instantNoZone_ZDT(DateTimeFormatter formatter, String text, Instant expected) { - TemporalAccessor actual = formatter.parse(text); - ZonedDateTime.from(actual); + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAccessor actual = formatter.parse(text); + ZonedDateTime.from(actual); + }); } - @Test(dataProvider = "instantNoZone", expectedExceptions = DateTimeException.class) + @ParameterizedTest + @MethodSource("data_instantNoZone") public void test_parse_instantNoZone_LDT(DateTimeFormatter formatter, String text, Instant expected) { - TemporalAccessor actual = formatter.parse(text); - LocalDateTime.from(actual); + Assertions.assertThrows(DateTimeException.class, () -> { + TemporalAccessor actual = formatter.parse(text); + LocalDateTime.from(actual); + }); } - @Test(dataProvider = "instantNoZone") + @ParameterizedTest + @MethodSource("data_instantNoZone") public void test_parse_instantNoZone_Instant(DateTimeFormatter formatter, String text, Instant expected) { TemporalAccessor actual = formatter.parse(text); - assertEquals(Instant.from(actual), expected); + assertEquals(expected, Instant.from(actual)); } - @Test(dataProvider = "instantNoZone") + @ParameterizedTest + @MethodSource("data_instantNoZone") public void test_parse_instantNoZone_supported(DateTimeFormatter formatter, String text, Instant expected) { TemporalAccessor actual = formatter.parse(text); - assertEquals(actual.isSupported(INSTANT_SECONDS), true); - assertEquals(actual.isSupported(EPOCH_DAY), false); - assertEquals(actual.isSupported(SECOND_OF_DAY), false); - assertEquals(actual.isSupported(NANO_OF_SECOND), true); - assertEquals(actual.isSupported(MICRO_OF_SECOND), true); - assertEquals(actual.isSupported(MILLI_OF_SECOND), true); + assertEquals(true, actual.isSupported(INSTANT_SECONDS)); + assertEquals(false, actual.isSupported(EPOCH_DAY)); + assertEquals(false, actual.isSupported(SECOND_OF_DAY)); + assertEquals(true, actual.isSupported(NANO_OF_SECOND)); + assertEquals(true, actual.isSupported(MICRO_OF_SECOND)); + assertEquals(true, actual.isSupported(MILLI_OF_SECOND)); } // Bug 8223773: validation check for the range of HourOfAmPm in SMART mode. // Should throw a DateTimeParseException, as 12 is out of range for HourOfAmPm. - @Test(expectedExceptions = DateTimeParseException.class) + @Test public void test_validateHourOfAmPm() { - try { - new DateTimeFormatterBuilder() - .appendValue(HOUR_OF_AMPM,2) - .appendText(AMPM_OF_DAY) - .toFormatter(US) - .parse("12PM"); - } catch (DateTimeParseException e) { - Throwable cause = e.getCause(); - if (cause == null || - !DTPE_MESSAGE.equals(cause.getMessage())) { - throw new RuntimeException( - "DateTimeParseException was thrown with different reason: " + e); - } else { - throw e; + Assertions.assertThrows(DateTimeParseException.class, () -> { + try { + new DateTimeFormatterBuilder() + .appendValue(HOUR_OF_AMPM,2) + .appendText(AMPM_OF_DAY) + .toFormatter(US) + .parse("12PM"); + } catch (DateTimeParseException e) { + Throwable cause = e.getCause(); + if (cause == null || + !DTPE_MESSAGE.equals(cause.getMessage())) { + throw new RuntimeException( + "DateTimeParseException was thrown with different reason: " + e); + } else { + throw e; + } } - } + }); } // Checks ::toFormat().parseObject(text, pos) do not throw DateTimeException diff --git a/test/jdk/java/time/test/java/time/format/TestDateTimeTextProvider.java b/test/jdk/java/time/test/java/time/format/TestDateTimeTextProvider.java index f2a14374c49..80336b7b761 100644 --- a/test/jdk/java/time/test/java/time/format/TestDateTimeTextProvider.java +++ b/test/jdk/java/time/test/java/time/format/TestDateTimeTextProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -62,7 +62,8 @@ package test.java.time.format; import static java.time.temporal.ChronoField.AMPM_OF_DAY; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; @@ -70,19 +71,19 @@ import java.time.format.TextStyle; import java.time.temporal.TemporalField; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test SimpleDateTimeTextProvider. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestDateTimeTextProvider extends AbstractTestPrinterParser { Locale enUS = Locale.US; //----------------------------------------------------------------------- - @DataProvider(name = "Text") Object[][] data_text() { return new Object[][] { {DAY_OF_WEEK, 1, TextStyle.SHORT, enUS, "Mon"}, @@ -133,10 +134,11 @@ public class TestDateTimeTextProvider extends AbstractTestPrinterParser { }; } - @Test(dataProvider = "Text") + @ParameterizedTest + @MethodSource("data_text") public void test_getText(TemporalField field, Number value, TextStyle style, Locale locale, String expected) { DateTimeFormatter fmt = getFormatter(field, style).withLocale(locale); - assertEquals(fmt.format(ZonedDateTime.now().with(field, value.longValue())), expected); + assertEquals(expected, fmt.format(ZonedDateTime.now().with(field, value.longValue()))); } } diff --git a/test/jdk/java/time/test/java/time/format/TestDateTimeTextProviderWithLocale.java b/test/jdk/java/time/test/java/time/format/TestDateTimeTextProviderWithLocale.java index 65d65251862..35b793bb769 100644 --- a/test/jdk/java/time/test/java/time/format/TestDateTimeTextProviderWithLocale.java +++ b/test/jdk/java/time/test/java/time/format/TestDateTimeTextProviderWithLocale.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -69,7 +69,8 @@ package test.java.time.format; import static java.time.temporal.ChronoField.AMPM_OF_DAY; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; @@ -77,20 +78,20 @@ import java.time.format.TextStyle; import java.time.temporal.TemporalField; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test SimpleDateTimeTextProviderWithLocale. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestDateTimeTextProviderWithLocale extends AbstractTestPrinterParser { Locale enUS = Locale.US; Locale ptBR = Locale.of("pt", "BR"); //----------------------------------------------------------------------- - @DataProvider(name = "Text") Object[][] data_text() { return new Object[][] { {DAY_OF_WEEK, 1, TextStyle.SHORT, ptBR, "seg."}, @@ -138,10 +139,11 @@ public class TestDateTimeTextProviderWithLocale extends AbstractTestPrinterParse }; } - @Test(dataProvider = "Text") + @ParameterizedTest + @MethodSource("data_text") public void test_getText(TemporalField field, Number value, TextStyle style, Locale locale, String expected) { DateTimeFormatter fmt = getFormatter(field, style).withLocale(locale); - assertEquals(fmt.format(ZonedDateTime.now().with(field, value.longValue())), expected); + assertEquals(expected, fmt.format(ZonedDateTime.now().with(field, value.longValue()))); } } diff --git a/test/jdk/java/time/test/java/time/format/TestDecimalStyle.java b/test/jdk/java/time/test/java/time/format/TestDecimalStyle.java index b506d547ada..48f7da3e80c 100644 --- a/test/jdk/java/time/test/java/time/format/TestDecimalStyle.java +++ b/test/jdk/java/time/test/java/time/format/TestDecimalStyle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,17 +59,16 @@ */ package test.java.time.format; -import static org.testng.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; import java.time.format.DecimalStyle; import java.util.Locale; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test DecimalStyle. */ -@Test public class TestDecimalStyle { @Test diff --git a/test/jdk/java/time/test/java/time/format/TestFractionPrinterParser.java b/test/jdk/java/time/test/java/time/format/TestFractionPrinterParser.java index 4dbca06709d..0c079173d1f 100644 --- a/test/jdk/java/time/test/java/time/format/TestFractionPrinterParser.java +++ b/test/jdk/java/time/test/java/time/format/TestFractionPrinterParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -60,8 +60,9 @@ package test.java.time.format; import static java.time.temporal.ChronoField.*; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.text.ParsePosition; import java.time.DateTimeException; @@ -71,8 +72,12 @@ import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalField; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.temporal.MockFieldValue; /** @@ -80,7 +85,7 @@ import test.java.time.temporal.MockFieldValue; * * @bug 8230136 8276220 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestFractionPrinterParser extends AbstractTestPrinterParser { private DateTimeFormatter getFormatter(TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) { @@ -90,12 +95,11 @@ public class TestFractionPrinterParser extends AbstractTestPrinterParser { //----------------------------------------------------------------------- // print //----------------------------------------------------------------------- - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_emptyCalendrical() throws Exception { - getFormatter(NANO_OF_SECOND, 0, 9, true).formatTo(EMPTY_DTA, buf); + Assertions.assertThrows(DateTimeException.class, () -> getFormatter(NANO_OF_SECOND, 0, 9, true).formatTo(EMPTY_DTA, buf)); } - @DataProvider(name="OOB_Nanos") Object[][] provider_oob_nanos() { return new Object[][]{ {-1}, @@ -108,12 +112,12 @@ public class TestFractionPrinterParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="OOB_Nanos", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("provider_oob_nanos") public void test_print_oob_nanos(long value) throws Exception { - getFormatter(NANO_OF_SECOND, 0, 9, true).formatTo(new MockFieldValue(NANO_OF_SECOND, value), buf); + Assertions.assertThrows(DateTimeException.class, () -> getFormatter(NANO_OF_SECOND, 0, 9, true).formatTo(new MockFieldValue(NANO_OF_SECOND, value), buf)); } - @DataProvider(name="OOB_Micros") Object[][] provider_oob_micros() { return new Object[][]{ {-1}, @@ -126,25 +130,27 @@ public class TestFractionPrinterParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="OOB_Micros", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("provider_oob_micros") public void test_print_oob_micros(long value) throws Exception { - getFormatter(MICRO_OF_SECOND, 0, 9, true).formatTo(new MockFieldValue(MICRO_OF_SECOND, value), buf); + Assertions.assertThrows(DateTimeException.class, () -> getFormatter(MICRO_OF_SECOND, 0, 9, true).formatTo(new MockFieldValue(MICRO_OF_SECOND, value), buf)); } + @Test public void test_print_append() throws Exception { buf.append("EXISTING"); getFormatter(NANO_OF_SECOND, 0, 9, true).formatTo(LocalTime.of(12, 30, 40, 3), buf); - assertEquals(buf.toString(), "EXISTING.000000003"); + assertEquals("EXISTING.000000003", buf.toString()); } + @Test public void test_print_append_micros() throws Exception { buf.append("EXISTING"); getFormatter(MICRO_OF_SECOND, 0, 6, true).formatTo(LocalTime.of(12, 30, 40, 3000), buf); - assertEquals(buf.toString(), "EXISTING.000003"); + assertEquals("EXISTING.000003", buf.toString()); } //----------------------------------------------------------------------- - @DataProvider(name="Nanos") Object[][] provider_nanos() { return new Object[][] { {0, 9, 0, ""}, @@ -266,26 +272,27 @@ public class TestFractionPrinterParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="Nanos") + @ParameterizedTest + @MethodSource("provider_nanos") public void test_print_nanos(int minWidth, int maxWidth, int value, String result) throws Exception { getFormatter(NANO_OF_SECOND, minWidth, maxWidth, true).formatTo(new MockFieldValue(NANO_OF_SECOND, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), result); + assertEquals(result, buf.toString()); } - @Test(dataProvider="Nanos") + @ParameterizedTest + @MethodSource("provider_nanos") public void test_print_nanos_noDecimalPoint(int minWidth, int maxWidth, int value, String result) throws Exception { getFormatter(NANO_OF_SECOND, minWidth, maxWidth, false).formatTo(new MockFieldValue(NANO_OF_SECOND, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), (result.startsWith(".") ? result.substring(1) : result)); + assertEquals((result.startsWith(".") ? result.substring(1) : result), buf.toString()); } //----------------------------------------------------------------------- - @DataProvider(name="Micros") Object[][] provider_micros() { return new Object[][] { {0, 6, 0, ""}, @@ -342,26 +349,27 @@ public class TestFractionPrinterParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="Micros") + @ParameterizedTest + @MethodSource("provider_micros") public void test_print_micros(int minWidth, int maxWidth, int value, String result) throws Exception { getFormatter(MICRO_OF_SECOND, minWidth, maxWidth, true).formatTo(new MockFieldValue(MICRO_OF_SECOND, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), result); + assertEquals(result, buf.toString()); } - @Test(dataProvider="Micros") + @ParameterizedTest + @MethodSource("provider_micros") public void test_print_micros_noDecimalPoint(int minWidth, int maxWidth, int value, String result) throws Exception { getFormatter(MICRO_OF_SECOND, minWidth, maxWidth, false).formatTo(new MockFieldValue(MICRO_OF_SECOND, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), (result.startsWith(".") ? result.substring(1) : result)); + assertEquals((result.startsWith(".") ? result.substring(1) : result), buf.toString()); } //----------------------------------------------------------------------- - @DataProvider(name="Seconds") Object[][] provider_seconds() { return new Object[][] { {0, 9, 0, ""}, @@ -384,51 +392,56 @@ public class TestFractionPrinterParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="Seconds") + @ParameterizedTest + @MethodSource("provider_seconds") public void test_print_seconds(int minWidth, int maxWidth, int value, String result) throws Exception { getFormatter(SECOND_OF_MINUTE, minWidth, maxWidth, true).formatTo(new MockFieldValue(SECOND_OF_MINUTE, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), result); + assertEquals(result, buf.toString()); } - @Test(dataProvider="Seconds") + @ParameterizedTest + @MethodSource("provider_seconds") public void test_print_seconds_noDecimalPoint(int minWidth, int maxWidth, int value, String result) throws Exception { getFormatter(SECOND_OF_MINUTE, minWidth, maxWidth, false).formatTo(new MockFieldValue(SECOND_OF_MINUTE, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), (result.startsWith(".") ? result.substring(1) : result)); + assertEquals((result.startsWith(".") ? result.substring(1) : result), buf.toString()); } //----------------------------------------------------------------------- // parse //----------------------------------------------------------------------- - @Test(dataProvider="Nanos") + @ParameterizedTest + @MethodSource("provider_nanos") public void test_reverseParse(int minWidth, int maxWidth, int value, String result) throws Exception { ParsePosition pos = new ParsePosition(0); int expectedValue = fixParsedValue(maxWidth, value); TemporalAccessor parsed = getFormatter(NANO_OF_SECOND, minWidth, maxWidth, true).parseUnresolved(result, pos); - assertEquals(pos.getIndex(), result.length()); + assertEquals(result.length(), pos.getIndex()); assertParsed(parsed, NANO_OF_SECOND, value == 0 && minWidth == 0 ? null : (long) expectedValue); } - @Test(dataProvider="Nanos") + @ParameterizedTest + @MethodSource("provider_nanos") public void test_reverseParse_noDecimalPoint(int minWidth, int maxWidth, int value, String result) throws Exception { ParsePosition pos = new ParsePosition((result.startsWith(".") ? 1 : 0)); TemporalAccessor parsed = getFormatter(NANO_OF_SECOND, minWidth, maxWidth, false).parseUnresolved(result, pos); - assertEquals(pos.getIndex(), result.length()); + assertEquals(result.length(), pos.getIndex()); int expectedValue = fixParsedValue(maxWidth, value); assertParsed(parsed, NANO_OF_SECOND, value == 0 && minWidth == 0 ? null : (long) expectedValue); } - @Test(dataProvider="Nanos") + @ParameterizedTest + @MethodSource("provider_nanos") public void test_reverseParse_followedByNonDigit(int minWidth, int maxWidth, int value, String result) throws Exception { ParsePosition pos = new ParsePosition(0); int expectedValue = fixParsedValue(maxWidth, value); TemporalAccessor parsed = getFormatter(NANO_OF_SECOND, minWidth, maxWidth, true).parseUnresolved(result + " ", pos); - assertEquals(pos.getIndex(), result.length()); + assertEquals(result.length(), pos.getIndex()); assertParsed(parsed, NANO_OF_SECOND, value == 0 && minWidth == 0 ? null : (long) expectedValue); } @@ -441,12 +454,13 @@ public class TestFractionPrinterParser extends AbstractTestPrinterParser { // assertParsed(parseContext, NANO_OF_SECOND, value == 0 && minWidth == 0 ? null : (long) expectedValue); // } - @Test(dataProvider="Nanos") + @ParameterizedTest + @MethodSource("provider_nanos") public void test_reverseParse_preceededByNonDigit(int minWidth, int maxWidth, int value, String result) throws Exception { ParsePosition pos = new ParsePosition(1); int expectedValue = fixParsedValue(maxWidth, value); TemporalAccessor parsed = getFormatter(NANO_OF_SECOND, minWidth, maxWidth, true).parseUnresolved(" " + result, pos); - assertEquals(pos.getIndex(), result.length() + 1); + assertEquals(result.length() + 1, pos.getIndex()); assertParsed(parsed, NANO_OF_SECOND, value == 0 && minWidth == 0 ? null : (long) expectedValue); } @@ -458,25 +472,25 @@ public class TestFractionPrinterParser extends AbstractTestPrinterParser { return value; } - @Test(dataProvider="Seconds") + @ParameterizedTest + @MethodSource("provider_seconds") public void test_reverseParse_seconds(int minWidth, int maxWidth, int value, String result) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(SECOND_OF_MINUTE, minWidth, maxWidth, true).parseUnresolved(result, pos); - assertEquals(pos.getIndex(), result.length()); + assertEquals(result.length(), pos.getIndex()); assertParsed(parsed, SECOND_OF_MINUTE, value == 0 && minWidth == 0 ? null : (long) value); } private void assertParsed(TemporalAccessor parsed, TemporalField field, Long value) { if (value == null) { - assertEquals(parsed.isSupported(field), false); + assertEquals(false, parsed.isSupported(field)); } else { - assertEquals(parsed.isSupported(field), true); - assertEquals(parsed.getLong(field), (long) value); + assertEquals(true, parsed.isSupported(field)); + assertEquals((long) value, parsed.getLong(field)); } } //----------------------------------------------------------------------- - @DataProvider(name="ParseNothing") Object[][] provider_parseNothing() { return new Object[][] { {NANO_OF_SECOND, 3, 6, true, "", 0, 0}, @@ -489,15 +503,15 @@ public class TestFractionPrinterParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider = "ParseNothing") + @ParameterizedTest + @MethodSource("provider_parseNothing") public void test_parse_nothing(TemporalField field, int min, int max, boolean decimalPoint, String text, int pos, int expected) { ParsePosition ppos = new ParsePosition(pos); TemporalAccessor parsed = getFormatter(field, min, max, decimalPoint).parseUnresolved(text, ppos); - assertEquals(ppos.getErrorIndex(), expected); - assertEquals(parsed, null); + assertEquals(expected, ppos.getErrorIndex()); + assertEquals(null, parsed); } - @DataProvider(name="ParseMinWidth") Object[][] provider_parseMinWidth() { return new Object[][] { {MILLI_OF_SECOND, 3, 3, true, ".1x"}, @@ -506,22 +520,26 @@ public class TestFractionPrinterParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="ParseMinWidth", expectedExceptions=DateTimeException.class) + @ParameterizedTest + @MethodSource("provider_parseMinWidth") public void test_parse_minWidth(TemporalField field, int min, int max, boolean decimalPoint, String text) throws Exception { - builder - .appendFraction(field, min, max, decimalPoint) - .appendLiteral("x") - .toFormatter(locale) - .parse(text); + Assertions + .assertThrows(DateTimeException.class, () -> builder + .appendFraction(field, min, max, decimalPoint) + .appendLiteral("x") + .toFormatter(locale) + .parse(text)); } //----------------------------------------------------------------------- + @Test public void test_toString() throws Exception { - assertEquals(getFormatter(NANO_OF_SECOND, 3, 6, true).toString(), "Fraction(NanoOfSecond,3,6,DecimalPoint)"); + assertEquals("Fraction(NanoOfSecond,3,6,DecimalPoint)", getFormatter(NANO_OF_SECOND, 3, 6, true).toString()); } + @Test public void test_toString_noDecimalPoint() throws Exception { - assertEquals(getFormatter(NANO_OF_SECOND, 3, 6, false).toString(), "Fraction(NanoOfSecond,3,6)"); + assertEquals("Fraction(NanoOfSecond,3,6)", getFormatter(NANO_OF_SECOND, 3, 6, false).toString()); } } diff --git a/test/jdk/java/time/test/java/time/format/TestLocalizedOffsetPrinterParser.java b/test/jdk/java/time/test/java/time/format/TestLocalizedOffsetPrinterParser.java index d1b1c25ba98..36b491178a7 100644 --- a/test/jdk/java/time/test/java/time/format/TestLocalizedOffsetPrinterParser.java +++ b/test/jdk/java/time/test/java/time/format/TestLocalizedOffsetPrinterParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -35,7 +35,7 @@ package test.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDateTime; import java.time.OffsetDateTime; @@ -47,20 +47,20 @@ import java.time.format.TextStyle; import java.util.Locale; import java.util.Objects; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatterBuilder.appendOffset(). */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestLocalizedOffsetPrinterParser { private static final LocalDateTime DT_2012_06_30_12_30_40 = LocalDateTime.of(2012, 6, 30, 12, 30, 40); private static final Locale LOCALE_GA = Locale.of("ga"); - @DataProvider(name="print_localized_custom_locale") Object[][] data_print_localized_custom_locale() { return new Object[][] { {TextStyle.FULL, DT_2012_06_30_12_30_40, ZoneOffset.UTC, LOCALE_GA, "MAG"}, @@ -69,7 +69,8 @@ public class TestLocalizedOffsetPrinterParser { }; } - @Test(dataProvider="print_localized_custom_locale") + @ParameterizedTest + @MethodSource("data_print_localized_custom_locale") public void test_print_localized_custom_locale(TextStyle style, LocalDateTime ldt, ZoneOffset offset, Locale locale, String expected) { Objects.requireNonNull(locale, "Locale must not be null"); @@ -78,27 +79,27 @@ public class TestLocalizedOffsetPrinterParser { ZonedDateTime zdt = ldt.atZone(offset); DateTimeFormatter f = new DateTimeFormatterBuilder().appendLocalizedOffset(style).toFormatter(locale); - assertEquals(f.format(odt), expected); - assertEquals(f.format(zdt), expected); - assertEquals(f.parse(expected, ZoneOffset::from), offset); + assertEquals(expected, f.format(odt)); + assertEquals(expected, f.format(zdt)); + assertEquals(offset, f.parse(expected, ZoneOffset::from)); if (style == TextStyle.FULL) { f = new DateTimeFormatterBuilder().appendPattern("ZZZZ").toFormatter(locale); - assertEquals(f.format(odt), expected); - assertEquals(f.format(zdt), expected); - assertEquals(f.parse(expected, ZoneOffset::from), offset); + assertEquals(expected, f.format(odt)); + assertEquals(expected, f.format(zdt)); + assertEquals(offset, f.parse(expected, ZoneOffset::from)); f = new DateTimeFormatterBuilder().appendPattern("OOOO").toFormatter(locale); - assertEquals(f.format(odt), expected); - assertEquals(f.format(zdt), expected); - assertEquals(f.parse(expected, ZoneOffset::from), offset); + assertEquals(expected, f.format(odt)); + assertEquals(expected, f.format(zdt)); + assertEquals(offset, f.parse(expected, ZoneOffset::from)); } if (style == TextStyle.SHORT) { f = new DateTimeFormatterBuilder().appendPattern("O").toFormatter(locale); - assertEquals(f.format(odt), expected); - assertEquals(f.format(zdt), expected); - assertEquals(f.parse(expected, ZoneOffset::from), offset); + assertEquals(expected, f.format(odt)); + assertEquals(expected, f.format(zdt)); + assertEquals(offset, f.parse(expected, ZoneOffset::from)); } } diff --git a/test/jdk/java/time/test/java/time/format/TestLocalizedPattern.java b/test/jdk/java/time/test/java/time/format/TestLocalizedPattern.java index aa8ff763aad..1be115bc0ed 100644 --- a/test/jdk/java/time/test/java/time/format/TestLocalizedPattern.java +++ b/test/jdk/java/time/test/java/time/format/TestLocalizedPattern.java @@ -22,7 +22,7 @@ */ package test.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DateTimeException; import java.time.ZonedDateTime; @@ -34,14 +34,16 @@ import java.util.List; import java.util.Locale; import java.util.ResourceBundle; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatter.ofLocalizedPattern() related methods. * @bug 8176706 8284840 8354548 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestLocalizedPattern { private static final ZonedDateTime ZDT = @@ -52,7 +54,6 @@ public class TestLocalizedPattern { Locale.forLanguageTag("ja-JP-u-ca-japanese") ); - @DataProvider(name = "validSkeletons") Object[][] data_validSkeletons() { return SAMPLE_LOCALES.stream() .flatMap(l -> { @@ -63,43 +64,46 @@ public class TestLocalizedPattern { .toArray(new Object[0][0]); } - @DataProvider(name = "invalidSkeletons") Object[][] data_invalidSkeletons() { return new Object[][] { {"afo"}, {"hB"}, {"uMMM"}, {"MMMMMM"}, {"BhmsyMMM"}, }; } - @DataProvider(name = "unavailableSkeletons") Object[][] data_unavailableSkeletons() { return new Object[][] { {"yyyyyy"}, {"BBh"}, {"yMMMMEdBBh"}, }; } - @Test(dataProvider = "validSkeletons") + @ParameterizedTest + @MethodSource("data_validSkeletons") public void test_ofLocalizedPattern(String skeleton, String expected, Locale l) { var dtf = DateTimeFormatter.ofLocalizedPattern(skeleton).localizedBy(l); - assertEquals(dtf.format(ZDT), expected); + assertEquals(expected, dtf.format(ZDT)); } - @Test(dataProvider = "invalidSkeletons", expectedExceptions = IllegalArgumentException.class) + @ParameterizedTest + @MethodSource("data_invalidSkeletons") public void test_ofLocalizedPattern_invalid(String skeleton) { - DateTimeFormatter.ofLocalizedPattern(skeleton); + Assertions.assertThrows(IllegalArgumentException.class, () -> DateTimeFormatter.ofLocalizedPattern(skeleton)); } - @Test(dataProvider = "invalidSkeletons", expectedExceptions = IllegalArgumentException.class) + @ParameterizedTest + @MethodSource("data_invalidSkeletons") public void test_appendLocalized_invalid(String skeleton) { - new DateTimeFormatterBuilder().appendLocalized(skeleton); + Assertions.assertThrows(IllegalArgumentException.class, () -> new DateTimeFormatterBuilder().appendLocalized(skeleton)); } - @Test(dataProvider = "unavailableSkeletons", expectedExceptions = DateTimeException.class) + @ParameterizedTest + @MethodSource("data_unavailableSkeletons") public void test_ofLocalizedPattern_unavailable(String skeleton) { - DateTimeFormatter.ofLocalizedPattern(skeleton).format(ZDT); + Assertions.assertThrows(DateTimeException.class, () -> DateTimeFormatter.ofLocalizedPattern(skeleton).format(ZDT)); } - @Test(dataProvider = "unavailableSkeletons", expectedExceptions = DateTimeException.class) + @ParameterizedTest + @MethodSource("data_unavailableSkeletons") public void test_getLocalizedDateTimePattern_unavailable(String skeleton) { - DateTimeFormatterBuilder.getLocalizedDateTimePattern(skeleton, IsoChronology.INSTANCE, Locale.US); + Assertions.assertThrows(DateTimeException.class, () -> DateTimeFormatterBuilder.getLocalizedDateTimePattern(skeleton, IsoChronology.INSTANCE, Locale.US)); } } diff --git a/test/jdk/java/time/test/java/time/format/TestNarrowMonthNamesAndDayNames.java b/test/jdk/java/time/test/java/time/format/TestNarrowMonthNamesAndDayNames.java index 3e105665d14..92b7d1366b6 100644 --- a/test/jdk/java/time/test/java/time/format/TestNarrowMonthNamesAndDayNames.java +++ b/test/jdk/java/time/test/java/time/format/TestNarrowMonthNamesAndDayNames.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -28,7 +28,7 @@ */ package test.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DayOfWeek; import java.time.Month; @@ -37,9 +37,11 @@ import java.util.Arrays; import java.util.List; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestNarrowMonthNamesAndDayNames { static { @@ -59,7 +61,6 @@ public class TestNarrowMonthNamesAndDayNames { * Locale en_US, de_DE, fr_FR, no_NO will have same Narrow and * Narrow_Standalone month Names for COMPAT Provider. */ - @DataProvider(name = "MonthNarrows") public Object[][] monthNameData() { return new Object[][]{{new String[]{ "J", @@ -80,27 +81,23 @@ public class TestNarrowMonthNamesAndDayNames { //----------------------------------------------------------------------- // Check Narrow and Narrow_standalone month name values //----------------------------------------------------------------------- - @Test(dataProvider = "MonthNarrows") + @ParameterizedTest + @MethodSource("monthNameData") public void compareMonthNarrowValues(String[] monthNarrowExpected) { - LOCARR.forEach((loc) -> { - TEXTSTYLELIST.forEach((style) -> { - MONTHVALUES.forEach((value) -> { - String result = value.getDisplayName(style, loc); - int index = value.ordinal(); - assertEquals(result, monthNarrowExpected[index], "Test failed" - + " for COMPAT Provider for locale " - + loc + " for style " + style.name() - + " with Month value " + value.name()); - }); - }); - }); + LOCARR.forEach((loc) -> TEXTSTYLELIST.forEach((style) -> MONTHVALUES.forEach((value) -> { + String result = value.getDisplayName(style, loc); + int index = value.ordinal(); + assertEquals(monthNarrowExpected[index], result, "Test failed" + + " for COMPAT Provider for locale " + + loc + " for style " + style.name() + + " with Month value " + value.name()); + }))); } /** * Locale en_US, de_DE, fr_FR, no_NO will have different Narrow and * Narrow_Standalone Day Names for COMPAT Provider. */ - @DataProvider(name = "DayNarrows") public Object[][] dayNameData() { return new Object[][]{ {Locale.US, new String[]{"M", "T", "W", "T", "F", "S", "S"}}, @@ -112,17 +109,16 @@ public class TestNarrowMonthNamesAndDayNames { //----------------------------------------------------------------------- // Check Narrow and Narrow_standalone Day name values //----------------------------------------------------------------------- - @Test(dataProvider = "DayNarrows") + @ParameterizedTest + @MethodSource("dayNameData") public void compareDayNarrowValues(Locale locale, String[] dayNarrowExpected) { - TEXTSTYLELIST.forEach((style) -> { - DAYVALUES.forEach((value) -> { - String result = value.getDisplayName(style, locale); - int index = value.ordinal(); - assertEquals(result, dayNarrowExpected[index], "Test failed" - + " for COMPAT Provider for locale " - + locale + " for style " + style.name() - + " with Day value " + value.name()); - }); - }); + TEXTSTYLELIST.forEach((style) -> DAYVALUES.forEach((value) -> { + String result = value.getDisplayName(style, locale); + int index = value.ordinal(); + assertEquals(dayNarrowExpected[index], result, "Test failed" + + " for COMPAT Provider for locale " + + locale + " for style " + style.name() + + " with Day value " + value.name()); + })); } } diff --git a/test/jdk/java/time/test/java/time/format/TestNonIsoFormatter.java b/test/jdk/java/time/test/java/time/format/TestNonIsoFormatter.java index edca2ae8ceb..cb824e1ea7f 100644 --- a/test/jdk/java/time/test/java/time/format/TestNonIsoFormatter.java +++ b/test/jdk/java/time/test/java/time/format/TestNonIsoFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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,7 +30,7 @@ package test.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDate; import java.time.chrono.ChronoLocalDate; @@ -51,9 +51,11 @@ import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalQueries; import java.util.Locale; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test DateTimeFormatter with non-ISO chronology. @@ -61,7 +63,7 @@ import org.testng.annotations.Test; * Strings in test data are all dependent on CLDR data which may change * in future CLDR releases. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestNonIsoFormatter { private static final Chronology ISO8601 = IsoChronology.INSTANCE; private static final Chronology JAPANESE = JapaneseChronology.INSTANCE; @@ -76,11 +78,10 @@ public class TestNonIsoFormatter { private static final Locale thTHTH = Locale.forLanguageTag("th-TH-u-nu-thai"); private static final Locale jaJPJP = Locale.forLanguageTag("ja-JP-u-ca-japanese"); - @BeforeMethod + @BeforeEach public void setUp() { } - @DataProvider(name="format_data") Object[][] formatData() { return new Object[][] { // Chronology, Format Locale, Numbering Locale, ChronoLocalDate, expected string @@ -102,7 +103,6 @@ public class TestNonIsoFormatter { }; } - @DataProvider(name="invalid_text") Object[][] invalidText() { return new Object[][] { // TODO: currently fixed Chronology and Locale. @@ -113,7 +113,6 @@ public class TestNonIsoFormatter { }; } - @DataProvider(name="chrono_names") Object[][] chronoNamesData() { return new Object[][] { // Chronology, Locale, Chronology Name @@ -137,7 +136,6 @@ public class TestNonIsoFormatter { }; } - @DataProvider(name="lenient_eraYear") Object[][] lenientEraYear() { return new Object[][] { // Chronology, lenient era/year, strict era/year @@ -147,17 +145,19 @@ public class TestNonIsoFormatter { }; } - @Test(dataProvider="format_data") + @ParameterizedTest + @MethodSource("formatData") public void test_formatLocalizedDate(Chronology chrono, Locale formatLocale, Locale numberingLocale, ChronoLocalDate date, String expected) { DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL) .withChronology(chrono).withLocale(formatLocale) .withDecimalStyle(DecimalStyle.of(numberingLocale)); String text = dtf.format(date); - assertEquals(text, expected); + assertEquals(expected, text); } - @Test(dataProvider="format_data") + @ParameterizedTest + @MethodSource("formatData") public void test_parseLocalizedText(Chronology chrono, Locale formatLocale, Locale numberingLocale, ChronoLocalDate expected, String text) { DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL) @@ -165,28 +165,33 @@ public class TestNonIsoFormatter { .withDecimalStyle(DecimalStyle.of(numberingLocale)); TemporalAccessor temporal = dtf.parse(text); ChronoLocalDate date = chrono.date(temporal); - assertEquals(date, expected); + assertEquals(expected, date); } - @Test(dataProvider="invalid_text", expectedExceptions=DateTimeParseException.class) + @ParameterizedTest + @MethodSource("invalidText") public void test_parseInvalidText(String text) { - DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL) - .withChronology(JAPANESE).withLocale(Locale.JAPANESE); - dtf.parse(text); + Assertions.assertThrows(DateTimeParseException.class, () -> { + DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL) + .withChronology(JAPANESE).withLocale(Locale.JAPANESE); + dtf.parse(text); + }); } - @Test(dataProvider="chrono_names") + @ParameterizedTest + @MethodSource("chronoNamesData") public void test_chronoNames(Chronology chrono, Locale locale, String expected) { DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendChronologyText(TextStyle.SHORT) .toFormatter(locale); String text = dtf.format(chrono.dateNow()); - assertEquals(text, expected); + assertEquals(expected, text); TemporalAccessor ta = dtf.parse(text); Chronology cal = ta.query(TemporalQueries.chronology()); - assertEquals(cal, chrono); + assertEquals(chrono, cal); } - @Test(dataProvider="lenient_eraYear") + @ParameterizedTest + @MethodSource("lenientEraYear") public void test_lenientEraYear(Chronology chrono, String lenient, String strict) { String mdStr = "-01-01"; DateTimeFormatter dtf = new DateTimeFormatterBuilder() @@ -194,6 +199,6 @@ public class TestNonIsoFormatter { .toFormatter(Locale.ROOT) .withChronology(chrono); DateTimeFormatter dtfLenient = dtf.withResolverStyle(ResolverStyle.LENIENT); - assertEquals(LocalDate.parse(lenient+mdStr, dtfLenient), LocalDate.parse(strict+mdStr, dtf)); + assertEquals(LocalDate.parse(strict+mdStr, dtf), LocalDate.parse(lenient+mdStr, dtfLenient)); } } diff --git a/test/jdk/java/time/test/java/time/format/TestNumberParser.java b/test/jdk/java/time/test/java/time/format/TestNumberParser.java index f3ac13b791d..ea92dfcaea5 100644 --- a/test/jdk/java/time/test/java/time/format/TestNumberParser.java +++ b/test/jdk/java/time/test/java/time/format/TestNumberParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -63,9 +63,10 @@ import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.DAY_OF_YEAR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.text.ParsePosition; import java.time.format.DateTimeFormatter; @@ -74,17 +75,17 @@ import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalField; import java.time.temporal.TemporalQueries; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test NumberPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestNumberParser extends AbstractTestPrinterParser { //----------------------------------------------------------------------- - @DataProvider(name="error") Object[][] data_error() { return new Object[][] { {DAY_OF_MONTH, 1, 2, SignStyle.NEVER, "12", -1, IndexOutOfBoundsException.class}, @@ -92,7 +93,8 @@ public class TestNumberParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="error") + @ParameterizedTest + @MethodSource("data_error") public void test_parse_error(TemporalField field, int min, int max, SignStyle style, String text, int pos, Class expected) { try { getFormatter(field, min, max, style).parseUnresolved(text, new ParsePosition(pos)); @@ -103,7 +105,6 @@ public class TestNumberParser extends AbstractTestPrinterParser { } //----------------------------------------------------------------------- - @DataProvider(name="parseData") Object[][] provider_parseData() { return new Object[][] { // normal @@ -163,7 +164,8 @@ public class TestNumberParser extends AbstractTestPrinterParser { } //----------------------------------------------------------------------- - @Test(dataProvider="parseData") + @ParameterizedTest + @MethodSource("provider_parseData") public void test_parse_fresh(int minWidth, int maxWidth, SignStyle signStyle, int subsequentWidth, String text, int pos, int expectedPos, long expectedValue) { ParsePosition ppos = new ParsePosition(pos); DateTimeFormatter dtf = getFormatter(DAY_OF_MONTH, minWidth, maxWidth, signStyle); @@ -173,17 +175,18 @@ public class TestNumberParser extends AbstractTestPrinterParser { } TemporalAccessor parsed = dtf.parseUnresolved(text, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), expectedPos); + assertEquals(expectedPos, ppos.getErrorIndex()); } else { assertTrue(subsequentWidth >= 0); - assertEquals(ppos.getIndex(), expectedPos + subsequentWidth); - assertEquals(parsed.getLong(DAY_OF_MONTH), expectedValue); - assertEquals(parsed.query(TemporalQueries.chronology()), null); - assertEquals(parsed.query(TemporalQueries.zoneId()), null); + assertEquals(expectedPos + subsequentWidth, ppos.getIndex()); + assertEquals(expectedValue, parsed.getLong(DAY_OF_MONTH)); + assertEquals(null, parsed.query(TemporalQueries.chronology())); + assertEquals(null, parsed.query(TemporalQueries.zoneId())); } } - @Test(dataProvider="parseData") + @ParameterizedTest + @MethodSource("provider_parseData") public void test_parse_textField(int minWidth, int maxWidth, SignStyle signStyle, int subsequentWidth, String text, int pos, int expectedPos, long expectedValue) { ParsePosition ppos = new ParsePosition(pos); DateTimeFormatter dtf = getFormatter(DAY_OF_WEEK, minWidth, maxWidth, signStyle); @@ -193,18 +196,17 @@ public class TestNumberParser extends AbstractTestPrinterParser { } TemporalAccessor parsed = dtf.parseUnresolved(text, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), expectedPos); + assertEquals(expectedPos, ppos.getErrorIndex()); } else { assertTrue(subsequentWidth >= 0); - assertEquals(ppos.getIndex(), expectedPos + subsequentWidth); - assertEquals(parsed.getLong(DAY_OF_WEEK), expectedValue); - assertEquals(parsed.query(TemporalQueries.chronology()), null); - assertEquals(parsed.query(TemporalQueries.zoneId()), null); + assertEquals(expectedPos + subsequentWidth, ppos.getIndex()); + assertEquals(expectedValue, parsed.getLong(DAY_OF_WEEK)); + assertEquals(null, parsed.query(TemporalQueries.chronology())); + assertEquals(null, parsed.query(TemporalQueries.zoneId())); } } //----------------------------------------------------------------------- - @DataProvider(name="parseSignsStrict") Object[][] provider_parseSignsStrict() { return new Object[][] { // basics @@ -304,22 +306,22 @@ public class TestNumberParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="parseSignsStrict") + @ParameterizedTest + @MethodSource("provider_parseSignsStrict") public void test_parseSignsStrict(String input, int min, int max, SignStyle style, int parseLen, Integer parseVal) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(DAY_OF_MONTH, min, max, style).parseUnresolved(input, pos); if (pos.getErrorIndex() != -1) { - assertEquals(pos.getErrorIndex(), parseLen); + assertEquals(parseLen, pos.getErrorIndex()); } else { - assertEquals(pos.getIndex(), parseLen); - assertEquals(parsed.getLong(DAY_OF_MONTH), (long)parseVal); - assertEquals(parsed.query(TemporalQueries.chronology()), null); - assertEquals(parsed.query(TemporalQueries.zoneId()), null); + assertEquals(parseLen, pos.getIndex()); + assertEquals((long)parseVal, parsed.getLong(DAY_OF_MONTH)); + assertEquals(null, parsed.query(TemporalQueries.chronology())); + assertEquals(null, parsed.query(TemporalQueries.zoneId())); } } //----------------------------------------------------------------------- - @DataProvider(name="parseSignsLenient") Object[][] provider_parseSignsLenient() { return new Object[][] { // never @@ -413,23 +415,23 @@ public class TestNumberParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="parseSignsLenient") + @ParameterizedTest + @MethodSource("provider_parseSignsLenient") public void test_parseSignsLenient(String input, int min, int max, SignStyle style, int parseLen, Integer parseVal) throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(DAY_OF_MONTH, min, max, style).parseUnresolved(input, pos); if (pos.getErrorIndex() != -1) { - assertEquals(pos.getErrorIndex(), parseLen); + assertEquals(parseLen, pos.getErrorIndex()); } else { - assertEquals(pos.getIndex(), parseLen); - assertEquals(parsed.getLong(DAY_OF_MONTH), (long)parseVal); - assertEquals(parsed.query(TemporalQueries.chronology()), null); - assertEquals(parsed.query(TemporalQueries.zoneId()), null); + assertEquals(parseLen, pos.getIndex()); + assertEquals((long)parseVal, parsed.getLong(DAY_OF_MONTH)); + assertEquals(null, parsed.query(TemporalQueries.chronology())); + assertEquals(null, parsed.query(TemporalQueries.zoneId())); } } //----------------------------------------------------------------------- - @DataProvider(name="parseDigitsLenient") Object[][] provider_parseDigitsLenient() { return new Object[][] { // never @@ -504,23 +506,23 @@ public class TestNumberParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="parseDigitsLenient") + @ParameterizedTest + @MethodSource("provider_parseDigitsLenient") public void test_parseDigitsLenient(String input, int min, int max, SignStyle style, int parseLen, Integer parseVal) throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(DAY_OF_MONTH, min, max, style).parseUnresolved(input, pos); if (pos.getErrorIndex() != -1) { - assertEquals(pos.getErrorIndex(), parseLen); + assertEquals(parseLen, pos.getErrorIndex()); } else { - assertEquals(pos.getIndex(), parseLen); - assertEquals(parsed.getLong(DAY_OF_MONTH), (long)parseVal); - assertEquals(parsed.query(TemporalQueries.chronology()), null); - assertEquals(parsed.query(TemporalQueries.zoneId()), null); + assertEquals(parseLen, pos.getIndex()); + assertEquals((long)parseVal, parsed.getLong(DAY_OF_MONTH)); + assertEquals(null, parsed.query(TemporalQueries.chronology())); + assertEquals(null, parsed.query(TemporalQueries.zoneId())); } } //----------------------------------------------------------------------- - @DataProvider(name="parseDigitsAdjacentLenient") Object[][] provider_parseDigitsAdjacentLenient() { return new Object[][] { // never @@ -538,7 +540,8 @@ public class TestNumberParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="parseDigitsAdjacentLenient") + @ParameterizedTest + @MethodSource("provider_parseDigitsAdjacentLenient") public void test_parseDigitsAdjacentLenient(String input, int parseLen, Integer parseMonth, Integer parsedDay) throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); @@ -547,13 +550,13 @@ public class TestNumberParser extends AbstractTestPrinterParser { .appendValue(DAY_OF_MONTH, 2).toFormatter(locale).withDecimalStyle(decimalStyle); TemporalAccessor parsed = f.parseUnresolved(input, pos); if (pos.getErrorIndex() != -1) { - assertEquals(pos.getErrorIndex(), parseLen); + assertEquals(parseLen, pos.getErrorIndex()); } else { - assertEquals(pos.getIndex(), parseLen); - assertEquals(parsed.getLong(MONTH_OF_YEAR), (long) parseMonth); - assertEquals(parsed.getLong(DAY_OF_MONTH), (long) parsedDay); - assertEquals(parsed.query(TemporalQueries.chronology()), null); - assertEquals(parsed.query(TemporalQueries.zoneId()), null); + assertEquals(parseLen, pos.getIndex()); + assertEquals((long) parseMonth, parsed.getLong(MONTH_OF_YEAR)); + assertEquals((long) parsedDay, parsed.getLong(DAY_OF_MONTH)); + assertEquals(null, parsed.query(TemporalQueries.chronology())); + assertEquals(null, parsed.query(TemporalQueries.zoneId())); } } diff --git a/test/jdk/java/time/test/java/time/format/TestNumberPrinter.java b/test/jdk/java/time/test/java/time/format/TestNumberPrinter.java index dedcc37e2ce..59038df910f 100644 --- a/test/jdk/java/time/test/java/time/format/TestNumberPrinter.java +++ b/test/jdk/java/time/test/java/time/format/TestNumberPrinter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -61,37 +61,42 @@ package test.java.time.format; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.HOUR_OF_DAY; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.time.DateTimeException; import java.time.LocalDate; import java.time.format.SignStyle; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.temporal.MockFieldValue; /** * Test SimpleNumberPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestNumberPrinter extends AbstractTestPrinterParser { //----------------------------------------------------------------------- - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_emptyCalendrical() throws Exception { - getFormatter(DAY_OF_MONTH, 1, 2, SignStyle.NEVER).formatTo(EMPTY_DTA, buf); + Assertions.assertThrows(DateTimeException.class, () -> getFormatter(DAY_OF_MONTH, 1, 2, SignStyle.NEVER).formatTo(EMPTY_DTA, buf)); } + @Test public void test_print_append() throws Exception { buf.append("EXISTING"); getFormatter(DAY_OF_MONTH, 1, 2, SignStyle.NEVER).formatTo(LocalDate.of(2012, 1, 3), buf); - assertEquals(buf.toString(), "EXISTING3"); + assertEquals("EXISTING3", buf.toString()); } //----------------------------------------------------------------------- - @DataProvider(name="Pad") Object[][] provider_pad() { return new Object[][] { {1, 1, -10, null}, @@ -181,72 +186,77 @@ public class TestNumberPrinter extends AbstractTestPrinterParser { }; } - @Test(dataProvider="Pad") + @ParameterizedTest + @MethodSource("provider_pad") public void test_pad_NOT_NEGATIVE(int minPad, int maxPad, long value, String result) throws Exception { try { getFormatter(DAY_OF_MONTH, minPad, maxPad, SignStyle.NOT_NEGATIVE).formatTo(new MockFieldValue(DAY_OF_MONTH, value), buf); if (result == null || value < 0) { fail("Expected exception"); } - assertEquals(buf.toString(), result); + assertEquals(result, buf.toString()); } catch (DateTimeException ex) { if (result == null || value < 0) { - assertEquals(ex.getMessage().contains(DAY_OF_MONTH.toString()), true); + assertEquals(true, ex.getMessage().contains(DAY_OF_MONTH.toString())); } else { throw ex; } } } - @Test(dataProvider="Pad") + @ParameterizedTest + @MethodSource("provider_pad") public void test_pad_NEVER(int minPad, int maxPad, long value, String result) throws Exception { try { getFormatter(DAY_OF_MONTH, minPad, maxPad, SignStyle.NEVER).formatTo(new MockFieldValue(DAY_OF_MONTH, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), result); + assertEquals(result, buf.toString()); } catch (DateTimeException ex) { if (result != null) { throw ex; } - assertEquals(ex.getMessage().contains(DAY_OF_MONTH.toString()), true); + assertEquals(true, ex.getMessage().contains(DAY_OF_MONTH.toString())); } } - @Test(dataProvider="Pad") + @ParameterizedTest + @MethodSource("provider_pad") public void test_pad_NORMAL(int minPad, int maxPad, long value, String result) throws Exception { try { getFormatter(DAY_OF_MONTH, minPad, maxPad, SignStyle.NORMAL).formatTo(new MockFieldValue(DAY_OF_MONTH, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), (value < 0 ? "-" + result : result)); + assertEquals((value < 0 ? "-" + result : result), buf.toString()); } catch (DateTimeException ex) { if (result != null) { throw ex; } - assertEquals(ex.getMessage().contains(DAY_OF_MONTH.toString()), true); + assertEquals(true, ex.getMessage().contains(DAY_OF_MONTH.toString())); } } - @Test(dataProvider="Pad") + @ParameterizedTest + @MethodSource("provider_pad") public void test_pad_ALWAYS(int minPad, int maxPad, long value, String result) throws Exception { try { getFormatter(DAY_OF_MONTH, minPad, maxPad, SignStyle.ALWAYS).formatTo(new MockFieldValue(DAY_OF_MONTH, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), (value < 0 ? "-" + result : "+" + result)); + assertEquals((value < 0 ? "-" + result : "+" + result), buf.toString()); } catch (DateTimeException ex) { if (result != null) { throw ex; } - assertEquals(ex.getMessage().contains(DAY_OF_MONTH.toString()), true); + assertEquals(true, ex.getMessage().contains(DAY_OF_MONTH.toString())); } } - @Test(dataProvider="Pad") + @ParameterizedTest + @MethodSource("provider_pad") public void test_pad_EXCEEDS_PAD(int minPad, int maxPad, long value, String result) throws Exception { try { getFormatter(DAY_OF_MONTH, minPad, maxPad, SignStyle.EXCEEDS_PAD).formatTo(new MockFieldValue(DAY_OF_MONTH, value), buf); @@ -257,26 +267,29 @@ public class TestNumberPrinter extends AbstractTestPrinterParser { if (result.length() > minPad || value < 0) { result = (value < 0 ? "-" + result : "+" + result); } - assertEquals(buf.toString(), result); + assertEquals(result, buf.toString()); } catch (DateTimeException ex) { if (result != null) { throw ex; } - assertEquals(ex.getMessage().contains(DAY_OF_MONTH.toString()), true); + assertEquals(true, ex.getMessage().contains(DAY_OF_MONTH.toString())); } } //----------------------------------------------------------------------- + @Test public void test_toString1() throws Exception { - assertEquals(getFormatter(HOUR_OF_DAY, 1, 19, SignStyle.NORMAL).toString(), "Value(HourOfDay)"); + assertEquals("Value(HourOfDay)", getFormatter(HOUR_OF_DAY, 1, 19, SignStyle.NORMAL).toString()); } + @Test public void test_toString2() throws Exception { - assertEquals(getFormatter(HOUR_OF_DAY, 2, 2, SignStyle.NOT_NEGATIVE).toString(), "Value(HourOfDay,2)"); + assertEquals("Value(HourOfDay,2)", getFormatter(HOUR_OF_DAY, 2, 2, SignStyle.NOT_NEGATIVE).toString()); } + @Test public void test_toString3() throws Exception { - assertEquals(getFormatter(HOUR_OF_DAY, 1, 2, SignStyle.NOT_NEGATIVE).toString(), "Value(HourOfDay,1,2,NOT_NEGATIVE)"); + assertEquals("Value(HourOfDay,1,2,NOT_NEGATIVE)", getFormatter(HOUR_OF_DAY, 1, 2, SignStyle.NOT_NEGATIVE).toString()); } } diff --git a/test/jdk/java/time/test/java/time/format/TestPadPrinterDecorator.java b/test/jdk/java/time/test/java/time/format/TestPadPrinterDecorator.java index adb7677556a..48721e470c3 100644 --- a/test/jdk/java/time/test/java/time/format/TestPadPrinterDecorator.java +++ b/test/jdk/java/time/test/java/time/format/TestPadPrinterDecorator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,79 +59,90 @@ */ package test.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DateTimeException; import java.time.LocalDate; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Test PadPrinterDecorator. */ -@Test public class TestPadPrinterDecorator extends AbstractTestPrinterParser { //----------------------------------------------------------------------- + @Test public void test_print_emptyCalendrical() throws Exception { builder.padNext(3, '-').appendLiteral('Z'); getFormatter().formatTo(EMPTY_DTA, buf); - assertEquals(buf.toString(), "--Z"); + assertEquals("--Z", buf.toString()); } + @Test public void test_print_fullDateTime() throws Exception { builder.padNext(3, '-').appendLiteral('Z'); getFormatter().formatTo(LocalDate.of(2008, 12, 3), buf); - assertEquals(buf.toString(), "--Z"); + assertEquals("--Z", buf.toString()); } + @Test public void test_print_append() throws Exception { buf.append("EXISTING"); builder.padNext(3, '-').appendLiteral('Z'); getFormatter().formatTo(EMPTY_DTA, buf); - assertEquals(buf.toString(), "EXISTING--Z"); + assertEquals("EXISTING--Z", buf.toString()); } //----------------------------------------------------------------------- + @Test public void test_print_noPadRequiredSingle() throws Exception { builder.padNext(1, '-').appendLiteral('Z'); getFormatter().formatTo(EMPTY_DTA, buf); - assertEquals(buf.toString(), "Z"); + assertEquals("Z", buf.toString()); } + @Test public void test_print_padRequiredSingle() throws Exception { builder.padNext(5, '-').appendLiteral('Z'); getFormatter().formatTo(EMPTY_DTA, buf); - assertEquals(buf.toString(), "----Z"); + assertEquals("----Z", buf.toString()); } + @Test public void test_print_noPadRequiredMultiple() throws Exception { builder.padNext(4, '-').appendLiteral("WXYZ"); getFormatter().formatTo(EMPTY_DTA, buf); - assertEquals(buf.toString(), "WXYZ"); + assertEquals("WXYZ", buf.toString()); } + @Test public void test_print_padRequiredMultiple() throws Exception { builder.padNext(5, '-').appendLiteral("WXYZ"); getFormatter().formatTo(EMPTY_DTA, buf); - assertEquals(buf.toString(), "-WXYZ"); + assertEquals("-WXYZ", buf.toString()); } - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_overPad() throws Exception { - builder.padNext(3, '-').appendLiteral("WXYZ"); - getFormatter().formatTo(EMPTY_DTA, buf); + Assertions.assertThrows(DateTimeException.class, () -> { + builder.padNext(3, '-').appendLiteral("WXYZ"); + getFormatter().formatTo(EMPTY_DTA, buf); + }); } //----------------------------------------------------------------------- + @Test public void test_toString1() throws Exception { builder.padNext(5, ' ').appendLiteral('Y'); - assertEquals(getFormatter().toString(), "Pad('Y',5)"); + assertEquals("Pad('Y',5)", getFormatter().toString()); } + @Test public void test_toString2() throws Exception { builder.padNext(5, '-').appendLiteral('Y'); - assertEquals(getFormatter().toString(), "Pad('Y',5,'-')"); + assertEquals("Pad('Y',5,'-')", getFormatter().toString()); } } diff --git a/test/jdk/java/time/test/java/time/format/TestReducedParser.java b/test/jdk/java/time/test/java/time/format/TestReducedParser.java index 3bf806563e8..2d9df7c11da 100644 --- a/test/jdk/java/time/test/java/time/format/TestReducedParser.java +++ b/test/jdk/java/time/test/java/time/format/TestReducedParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -65,9 +65,10 @@ import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoField.YEAR_OF_ERA; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.assertNotNull; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.text.ParsePosition; import java.time.LocalDate; @@ -85,13 +86,15 @@ import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalField; import java.time.temporal.TemporalQueries; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test ReducedPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestReducedParser extends AbstractTestPrinterParser { private static final boolean STRICT = true; private static final boolean LENIENT = false; @@ -109,7 +112,6 @@ public class TestReducedParser extends AbstractTestPrinterParser { } //----------------------------------------------------------------------- - @DataProvider(name="error") Object[][] data_error() { return new Object[][] { {YEAR, 2, 2010, "12", -1, IndexOutOfBoundsException.class}, @@ -117,7 +119,8 @@ public class TestReducedParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="error") + @ParameterizedTest + @MethodSource("data_error") public void test_parse_error(TemporalField field, int width, int baseValue, String text, int pos, Class expected) { try { getFormatter0(field, width, baseValue).parseUnresolved(text, new ParsePosition(pos)); @@ -127,10 +130,11 @@ public class TestReducedParser extends AbstractTestPrinterParser { } //----------------------------------------------------------------------- + @Test public void test_parse_fieldRangeIgnored() throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter0(DAY_OF_YEAR, 3, 10).parseUnresolved("456", pos); - assertEquals(pos.getIndex(), 3); + assertEquals(3, pos.getIndex()); assertParsed(parsed, DAY_OF_YEAR, 456L); // parsed dayOfYear=456 } @@ -138,7 +142,6 @@ public class TestReducedParser extends AbstractTestPrinterParser { // Parse data and values that are consistent whether strict or lenient // The data is the ChronoField, width, baseValue, text, startPos, endPos, value //----------------------------------------------------------------------- - @DataProvider(name="ParseAll") Object[][] provider_parseAll() { return new Object[][] { // negative zero @@ -182,30 +185,32 @@ public class TestReducedParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="ParseAll") + @ParameterizedTest + @MethodSource("provider_parseAll") public void test_parseAllStrict(TemporalField field, int width, int baseValue, String input, int pos, int parseLen, Integer parseVal) { ParsePosition ppos = new ParsePosition(pos); setStrict(true); TemporalAccessor parsed = getFormatter0(field, width, baseValue).parseUnresolved(input, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), parseLen, "error case parse position"); - assertEquals(parsed, parseVal, "unexpected parse result"); + assertEquals(parseLen, ppos.getErrorIndex(), "error case parse position"); + assertEquals(parseVal, parsed, "unexpected parse result"); } else { - assertEquals(ppos.getIndex(), parseLen, "parse position"); + assertEquals(parseLen, ppos.getIndex(), "parse position"); assertParsed(parsed, YEAR, parseVal != null ? (long) parseVal : null); } } - @Test(dataProvider="ParseAll") + @ParameterizedTest + @MethodSource("provider_parseAll") public void test_parseAllLenient(TemporalField field, int width, int baseValue, String input, int pos, int parseLen, Integer parseVal) { ParsePosition ppos = new ParsePosition(pos); setStrict(false); TemporalAccessor parsed = getFormatter0(field, width, baseValue).parseUnresolved(input, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), parseLen, "error case parse position"); - assertEquals(parsed, parseVal, "unexpected parse result"); + assertEquals(parseLen, ppos.getErrorIndex(), "error case parse position"); + assertEquals(parseVal, parsed, "unexpected parse result"); } else { - assertEquals(ppos.getIndex(), parseLen, "parse position"); + assertEquals(parseLen, ppos.getIndex(), "parse position"); assertParsed(parsed, YEAR, parseVal != null ? (long) parseVal : null); } } @@ -215,7 +220,6 @@ public class TestReducedParser extends AbstractTestPrinterParser { // The data is the ChronoField, minWidth, maxWidth, baseValue, text, startPos, // Strict Pair(endPos, value), Lenient Pair(endPos, value) //----------------------------------------------------------------------- - @DataProvider(name="ParseLenientSensitive") Object[][] provider_parseLenientSensitive() { return new Object[][] { // few digits supplied @@ -268,32 +272,34 @@ public class TestReducedParser extends AbstractTestPrinterParser { //----------------------------------------------------------------------- // Parsing tests for strict mode //----------------------------------------------------------------------- - @Test(dataProvider="ParseLenientSensitive") + @ParameterizedTest + @MethodSource("provider_parseLenientSensitive") public void test_parseStrict(TemporalField field, int minWidth, int maxWidth, int baseValue, String input, int pos, Pair strict, Pair lenient) { ParsePosition ppos = new ParsePosition(pos); setStrict(true); TemporalAccessor parsed = getFormatter0(field, minWidth, maxWidth, baseValue).parseUnresolved(input, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), strict.parseLen, "error case parse position"); - assertEquals(parsed, strict.parseVal, "unexpected parse result"); + assertEquals(strict.parseLen, ppos.getErrorIndex(), "error case parse position"); + assertEquals(strict.parseVal, parsed, "unexpected parse result"); } else { - assertEquals(ppos.getIndex(), strict.parseLen, "parse position"); + assertEquals(strict.parseLen, ppos.getIndex(), "parse position"); assertParsed(parsed, YEAR, strict.parseVal != null ? (long) strict.parseVal : null); } } - @Test(dataProvider="ParseLenientSensitive") + @ParameterizedTest + @MethodSource("provider_parseLenientSensitive") public void test_parseStrict_baseDate(TemporalField field, int minWidth, int maxWidth, int baseValue, String input, int pos, Pair strict, Pair lenient) { ParsePosition ppos = new ParsePosition(pos); setStrict(true); TemporalAccessor parsed = getFormatterBaseDate(field, minWidth, maxWidth, baseValue).parseUnresolved(input, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), strict.parseLen, "error case parse position"); - assertEquals(parsed, strict.parseVal, "unexpected parse result"); + assertEquals(strict.parseLen, ppos.getErrorIndex(), "error case parse position"); + assertEquals(strict.parseVal, parsed, "unexpected parse result"); } else { - assertEquals(ppos.getIndex(), strict.parseLen, "parse position"); + assertEquals(strict.parseLen, ppos.getIndex(), "parse position"); assertParsed(parsed, YEAR, strict.parseVal != null ? (long) strict.parseVal : null); } } @@ -301,42 +307,44 @@ public class TestReducedParser extends AbstractTestPrinterParser { //----------------------------------------------------------------------- // Parsing tests for lenient mode //----------------------------------------------------------------------- - @Test(dataProvider="ParseLenientSensitive") + @ParameterizedTest + @MethodSource("provider_parseLenientSensitive") public void test_parseLenient(TemporalField field, int minWidth, int maxWidth, int baseValue, String input, int pos, Pair strict, Pair lenient) { ParsePosition ppos = new ParsePosition(pos); setStrict(false); TemporalAccessor parsed = getFormatter0(field, minWidth, maxWidth, baseValue).parseUnresolved(input, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), lenient.parseLen, "error case parse position"); - assertEquals(parsed, lenient.parseVal, "unexpected parse result"); + assertEquals(lenient.parseLen, ppos.getErrorIndex(), "error case parse position"); + assertEquals(lenient.parseVal, parsed, "unexpected parse result"); } else { - assertEquals(ppos.getIndex(), lenient.parseLen, "parse position"); + assertEquals(lenient.parseLen, ppos.getIndex(), "parse position"); assertParsed(parsed, YEAR, lenient.parseVal != null ? (long) lenient.parseVal : null); } } - @Test(dataProvider="ParseLenientSensitive") + @ParameterizedTest + @MethodSource("provider_parseLenientSensitive") public void test_parseLenient_baseDate(TemporalField field, int minWidth, int maxWidth, int baseValue, String input, int pos, Pair strict, Pair lenient) { ParsePosition ppos = new ParsePosition(pos); setStrict(false); TemporalAccessor parsed = getFormatterBaseDate(field, minWidth, maxWidth, baseValue).parseUnresolved(input, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), lenient.parseLen, "error case parse position"); - assertEquals(parsed, lenient.parseVal, "unexpected parse result"); + assertEquals(lenient.parseLen, ppos.getErrorIndex(), "error case parse position"); + assertEquals(lenient.parseVal, parsed, "unexpected parse result"); } else { - assertEquals(ppos.getIndex(), lenient.parseLen, "parse position"); + assertEquals(lenient.parseLen, ppos.getIndex(), "parse position"); assertParsed(parsed, YEAR, lenient.parseVal != null ? (long) lenient.parseVal : null); } } private void assertParsed(TemporalAccessor parsed, TemporalField field, Long value) { if (value == null) { - assertEquals(parsed, null, "Parsed Value"); + assertEquals(null, parsed, "Parsed Value"); } else { - assertEquals(parsed.isSupported(field), true, "isSupported: " + field); - assertEquals(parsed.getLong(field), (long) value, "Temporal.getLong: " + field); + assertEquals(true, parsed.isSupported(field), "isSupported: " + field); + assertEquals((long) value, parsed.getLong(field), "Temporal.getLong: " + field); } } @@ -344,7 +352,6 @@ public class TestReducedParser extends AbstractTestPrinterParser { //----------------------------------------------------------------------- // Cases and values in adjacent parsing mode //----------------------------------------------------------------------- - @DataProvider(name="ParseAdjacent") Object[][] provider_parseAdjacent() { return new Object[][] { // general @@ -363,7 +370,8 @@ public class TestReducedParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="ParseAdjacent") + @ParameterizedTest + @MethodSource("provider_parseAdjacent") public void test_parseAdjacent(String pattern, String input, boolean strict, int pos, int parseLen, int year, int month, int day) { ParsePosition ppos = new ParsePosition(0); builder = new DateTimeFormatterBuilder(); @@ -374,9 +382,9 @@ public class TestReducedParser extends AbstractTestPrinterParser { TemporalAccessor parsed = dtf.parseUnresolved(input, ppos); assertNotNull(parsed, String.format("parse failed: ppos: %s, formatter: %s%n", ppos.toString(), dtf)); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getErrorIndex(), parseLen, "error case parse position"); + assertEquals(parseLen, ppos.getErrorIndex(), "error case parse position"); } else { - assertEquals(ppos.getIndex(), parseLen, "parse position"); + assertEquals(parseLen, ppos.getIndex(), "parse position"); assertParsed(parsed, YEAR_OF_ERA, Long.valueOf(year)); assertParsed(parsed, MONTH_OF_YEAR, Long.valueOf(month)); assertParsed(parsed, DAY_OF_MONTH, Long.valueOf(day)); @@ -386,7 +394,6 @@ public class TestReducedParser extends AbstractTestPrinterParser { //----------------------------------------------------------------------- // Cases and values in reduced value parsing mode //----------------------------------------------------------------------- - @DataProvider(name="ReducedWithChrono") Object[][] provider_reducedWithChrono() { LocalDate baseYear = LocalDate.of(2000, 1, 1); return new Object[][] { @@ -408,7 +415,8 @@ public class TestReducedParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="ReducedWithChrono") + @ParameterizedTest + @MethodSource("provider_reducedWithChrono") public void test_reducedWithChronoYear(ChronoLocalDate date) { Chronology chrono = date.getChronology(); DateTimeFormatter df @@ -421,12 +429,13 @@ public class TestReducedParser extends AbstractTestPrinterParser { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(input, pos); int actual = parsed.get(YEAR); - assertEquals(actual, expected, + assertEquals(expected, actual, String.format("Wrong date parsed, chrono: %s, input: %s", chrono, input)); } - @Test(dataProvider="ReducedWithChrono") + @ParameterizedTest + @MethodSource("provider_reducedWithChrono") public void test_reducedWithChronoYearOfEra(ChronoLocalDate date) { Chronology chrono = date.getChronology(); DateTimeFormatter df @@ -439,7 +448,7 @@ public class TestReducedParser extends AbstractTestPrinterParser { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(input, pos); int actual = parsed.get(YEAR_OF_ERA); - assertEquals(actual, expected, + assertEquals(expected, actual, String.format("Wrong date parsed, chrono: %s, input: %s", chrono, input)); @@ -459,10 +468,10 @@ public class TestReducedParser extends AbstractTestPrinterParser { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(input, pos); - assertEquals(pos.getIndex(), input.length(), "Input not parsed completely"); - assertEquals(pos.getErrorIndex(), -1, "Error index should be -1 (no-error)"); + assertEquals(input.length(), pos.getIndex(), "Input not parsed completely"); + assertEquals(-1, pos.getErrorIndex(), "Error index should be -1 (no-error)"); int actual = parsed.get(YEAR); - assertEquals(actual, expected, + assertEquals(expected, actual, String.format("Wrong date parsed, chrono: %s, input: %s", parsed.query(TemporalQueries.chronology()), input)); @@ -482,10 +491,10 @@ public class TestReducedParser extends AbstractTestPrinterParser { String input = "44 ThaiBuddhist ISO"; ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = df.parseUnresolved(input, pos); - assertEquals(pos.getIndex(), input.length(), "Input not parsed completely: " + pos); - assertEquals(pos.getErrorIndex(), -1, "Error index should be -1 (no-error)"); + assertEquals(input.length(), pos.getIndex(), "Input not parsed completely: " + pos); + assertEquals(-1, pos.getErrorIndex(), "Error index should be -1 (no-error)"); int actual = parsed.get(YEAR); - assertEquals(actual, expected, + assertEquals(expected, actual, String.format("Wrong date parsed, chrono: %s, input: %s", parsed.query(TemporalQueries.chronology()), input)); diff --git a/test/jdk/java/time/test/java/time/format/TestReducedPrinter.java b/test/jdk/java/time/test/java/time/format/TestReducedPrinter.java index c4b6cf4dc39..94c45662666 100644 --- a/test/jdk/java/time/test/java/time/format/TestReducedPrinter.java +++ b/test/jdk/java/time/test/java/time/format/TestReducedPrinter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -60,8 +60,9 @@ package test.java.time.format; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.time.DateTimeException; import java.time.LocalDate; @@ -70,14 +71,18 @@ import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.TemporalField; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.temporal.MockFieldValue; /** * Test ReducedPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestReducedPrinter extends AbstractTestPrinterParser { private DateTimeFormatter getFormatter0(TemporalField field, int width, int baseValue) { @@ -93,20 +98,20 @@ public class TestReducedPrinter extends AbstractTestPrinterParser { } //----------------------------------------------------------------------- - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_emptyCalendrical() throws Exception { - getFormatter0(YEAR, 2, 2010).formatTo(EMPTY_DTA, buf); + Assertions.assertThrows(DateTimeException.class, () -> getFormatter0(YEAR, 2, 2010).formatTo(EMPTY_DTA, buf)); } //----------------------------------------------------------------------- + @Test public void test_print_append() throws Exception { buf.append("EXISTING"); getFormatter0(YEAR, 2, 2010).formatTo(LocalDate.of(2012, 1, 1), buf); - assertEquals(buf.toString(), "EXISTING12"); + assertEquals("EXISTING12", buf.toString()); } //----------------------------------------------------------------------- - @DataProvider(name="Pivot") Object[][] provider_pivot() { return new Object[][] { {1, 1, 2010, 2010, "0"}, @@ -175,34 +180,36 @@ public class TestReducedPrinter extends AbstractTestPrinterParser { }; } - @Test(dataProvider="Pivot") + @ParameterizedTest + @MethodSource("provider_pivot") public void test_pivot(int minWidth, int maxWidth, int baseValue, int value, String result) throws Exception { try { getFormatter0(YEAR, minWidth, maxWidth, baseValue).formatTo(new MockFieldValue(YEAR, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), result); + assertEquals(result, buf.toString()); } catch (DateTimeException ex) { if (result == null || value < 0) { - assertEquals(ex.getMessage().contains(YEAR.toString()), true); + assertEquals(true, ex.getMessage().contains(YEAR.toString())); } else { throw ex; } } } - @Test(dataProvider="Pivot") + @ParameterizedTest + @MethodSource("provider_pivot") public void test_pivot_baseDate(int minWidth, int maxWidth, int baseValue, int value, String result) throws Exception { try { getFormatterBaseDate(YEAR, minWidth, maxWidth, baseValue).formatTo(new MockFieldValue(YEAR, value), buf); if (result == null) { fail("Expected exception"); } - assertEquals(buf.toString(), result); + assertEquals(result, buf.toString()); } catch (DateTimeException ex) { if (result == null || value < 0) { - assertEquals(ex.getMessage().contains(YEAR.toString()), true); + assertEquals(true, ex.getMessage().contains(YEAR.toString())); } else { throw ex; } @@ -210,49 +217,51 @@ public class TestReducedPrinter extends AbstractTestPrinterParser { } //----------------------------------------------------------------------- + @Test public void test_minguoChrono_fixedWidth() throws Exception { // ISO 2021 is Minguo 110 DateTimeFormatter f = getFormatterBaseDate(YEAR, 2, 2, 2021); MinguoDate date = MinguoDate.of(109, 6, 30); - assertEquals(f.format(date), "09"); + assertEquals("09", f.format(date)); date = MinguoDate.of(110, 6, 30); - assertEquals(f.format(date), "10"); + assertEquals("10", f.format(date)); date = MinguoDate.of(199, 6, 30); - assertEquals(f.format(date), "99"); + assertEquals("99", f.format(date)); date = MinguoDate.of(200, 6, 30); - assertEquals(f.format(date), "00"); + assertEquals("00", f.format(date)); date = MinguoDate.of(209, 6, 30); - assertEquals(f.format(date), "09"); + assertEquals("09", f.format(date)); date = MinguoDate.of(210, 6, 30); - assertEquals(f.format(date), "10"); + assertEquals("10", f.format(date)); } + @Test public void test_minguoChrono_extendedWidth() throws Exception { // ISO 2021 is Minguo 110 DateTimeFormatter f = getFormatterBaseDate(YEAR, 2, 4, 2021); MinguoDate date = MinguoDate.of(109, 6, 30); - assertEquals(f.format(date), "109"); + assertEquals("109", f.format(date)); date = MinguoDate.of(110, 6, 30); - assertEquals(f.format(date), "10"); + assertEquals("10", f.format(date)); date = MinguoDate.of(199, 6, 30); - assertEquals(f.format(date), "99"); + assertEquals("99", f.format(date)); date = MinguoDate.of(200, 6, 30); - assertEquals(f.format(date), "00"); + assertEquals("00", f.format(date)); date = MinguoDate.of(209, 6, 30); - assertEquals(f.format(date), "09"); + assertEquals("09", f.format(date)); date = MinguoDate.of(210, 6, 30); - assertEquals(f.format(date), "210"); + assertEquals("210", f.format(date)); } //----------------------------------------------------------------------- + @Test public void test_toString() throws Exception { - assertEquals(getFormatter0(YEAR, 2, 2, 2005).toString(), "ReducedValue(Year,2,2,2005)"); + assertEquals("ReducedValue(Year,2,2,2005)", getFormatter0(YEAR, 2, 2, 2005).toString()); } //----------------------------------------------------------------------- // Cases and values in adjacent parsing mode //----------------------------------------------------------------------- - @DataProvider(name="PrintAdjacent") Object[][] provider_printAdjacent() { return new Object[][] { // general @@ -265,7 +274,8 @@ public class TestReducedPrinter extends AbstractTestPrinterParser { }; } - @Test(dataProvider="PrintAdjacent") + @ParameterizedTest + @MethodSource("provider_printAdjacent") public void test_printAdjacent(String pattern, String text, int year, int month, int day) { builder = new DateTimeFormatterBuilder(); builder.appendPattern(pattern); @@ -273,7 +283,7 @@ public class TestReducedPrinter extends AbstractTestPrinterParser { LocalDate ld = LocalDate.of(year, month, day); String actual = dtf.format(ld); - assertEquals(actual, text, "formatter output: " + dtf); + assertEquals(text, actual, "formatter output: " + dtf); } } diff --git a/test/jdk/java/time/test/java/time/format/TestSettingsParser.java b/test/jdk/java/time/test/java/time/format/TestSettingsParser.java index ce7b2d7f187..1f71a37a007 100644 --- a/test/jdk/java/time/test/java/time/format/TestSettingsParser.java +++ b/test/jdk/java/time/test/java/time/format/TestSettingsParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,29 +59,30 @@ */ package test.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.ParsePosition; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test SettingsParser. */ -@Test public class TestSettingsParser extends AbstractTestPrinterParser { //----------------------------------------------------------------------- + @Test public void test_print_sensitive() throws Exception { setCaseSensitive(true); getFormatter().formatTo(dta, buf); - assertEquals(buf.toString(), ""); + assertEquals("", buf.toString()); } + @Test public void test_print_strict() throws Exception { setStrict(true); getFormatter().formatTo(dta, buf); - assertEquals(buf.toString(), ""); + assertEquals("", buf.toString()); } /* @@ -92,53 +93,61 @@ public class TestSettingsParser extends AbstractTestPrinterParser { */ //----------------------------------------------------------------------- + @Test public void test_parse_changeStyle_sensitive() throws Exception { setCaseSensitive(true); ParsePosition pos = new ParsePosition(0); getFormatter().parseUnresolved("a", pos); - assertEquals(pos.getIndex(), 0); + assertEquals(0, pos.getIndex()); } + @Test public void test_parse_changeStyle_insensitive() throws Exception { setCaseSensitive(false); ParsePosition pos = new ParsePosition(0); getFormatter().parseUnresolved("a", pos); - assertEquals(pos.getIndex(), 0); + assertEquals(0, pos.getIndex()); } + @Test public void test_parse_changeStyle_strict() throws Exception { setStrict(true); ParsePosition pos = new ParsePosition(0); getFormatter().parseUnresolved("a", pos); - assertEquals(pos.getIndex(), 0); + assertEquals(0, pos.getIndex()); } + @Test public void test_parse_changeStyle_lenient() throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); getFormatter().parseUnresolved("a", pos); - assertEquals(pos.getIndex(), 0); + assertEquals(0, pos.getIndex()); } //----------------------------------------------------------------------- + @Test public void test_toString_sensitive() throws Exception { setCaseSensitive(true); - assertEquals(getFormatter().toString(), "ParseCaseSensitive(true)"); + assertEquals("ParseCaseSensitive(true)", getFormatter().toString()); } + @Test public void test_toString_insensitive() throws Exception { setCaseSensitive(false); - assertEquals(getFormatter().toString(), "ParseCaseSensitive(false)"); + assertEquals("ParseCaseSensitive(false)", getFormatter().toString()); } + @Test public void test_toString_strict() throws Exception { setStrict(true); - assertEquals(getFormatter().toString(), "ParseStrict(true)"); + assertEquals("ParseStrict(true)", getFormatter().toString()); } + @Test public void test_toString_lenient() throws Exception { setStrict(false); - assertEquals(getFormatter().toString(), "ParseStrict(false)"); + assertEquals("ParseStrict(false)", getFormatter().toString()); } } diff --git a/test/jdk/java/time/test/java/time/format/TestStringLiteralParser.java b/test/jdk/java/time/test/java/time/format/TestStringLiteralParser.java index f8f5147f921..c442621ce34 100644 --- a/test/jdk/java/time/test/java/time/format/TestStringLiteralParser.java +++ b/test/jdk/java/time/test/java/time/format/TestStringLiteralParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -60,24 +60,25 @@ package test.java.time.format; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.text.ParsePosition; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalQueries; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test StringLiteralPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestStringLiteralParser extends AbstractTestPrinterParser { - @DataProvider(name="success") Object[][] data_success() { return new Object[][] { // match @@ -104,23 +105,23 @@ public class TestStringLiteralParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="success") + @ParameterizedTest + @MethodSource("data_success") public void test_parse_success(String s, boolean caseSensitive, String text, int pos, int expectedPos) { setCaseSensitive(caseSensitive); ParsePosition ppos = new ParsePosition(pos); TemporalAccessor parsed = getFormatter(s).parseUnresolved(text, ppos); if (ppos.getErrorIndex() != -1) { - assertEquals(ppos.getIndex(), expectedPos); + assertEquals(expectedPos, ppos.getIndex()); } else { - assertEquals(ppos.getIndex(), expectedPos); - assertEquals(parsed.isSupported(YEAR), false); - assertEquals(parsed.query(TemporalQueries.chronology()), null); - assertEquals(parsed.query(TemporalQueries.zoneId()), null); + assertEquals(expectedPos, ppos.getIndex()); + assertEquals(false, parsed.isSupported(YEAR)); + assertEquals(null, parsed.query(TemporalQueries.chronology())); + assertEquals(null, parsed.query(TemporalQueries.zoneId())); } } //----------------------------------------------------------------------- - @DataProvider(name="error") Object[][] data_error() { return new Object[][] { {"hello", "hello", -1, IndexOutOfBoundsException.class}, @@ -128,7 +129,8 @@ public class TestStringLiteralParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="error") + @ParameterizedTest + @MethodSource("data_error") public void test_parse_error(String s, String text, int pos, Class expected) { try { ParsePosition ppos = new ParsePosition(pos); diff --git a/test/jdk/java/time/test/java/time/format/TestStringLiteralPrinter.java b/test/jdk/java/time/test/java/time/format/TestStringLiteralPrinter.java index 6733af164a4..ed8717d8bdb 100644 --- a/test/jdk/java/time/test/java/time/format/TestStringLiteralPrinter.java +++ b/test/jdk/java/time/test/java/time/format/TestStringLiteralPrinter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,44 +59,47 @@ */ package test.java.time.format; -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * Test StringLiteralPrinterParser. */ -@Test public class TestStringLiteralPrinter extends AbstractTestPrinterParser { //----------------------------------------------------------------------- + @Test public void test_print_emptyCalendrical() throws Exception { buf.append("EXISTING"); getFormatter("hello").formatTo(EMPTY_DTA, buf); - assertEquals(buf.toString(), "EXISTINGhello"); + assertEquals("EXISTINGhello", buf.toString()); } + @Test public void test_print_dateTime() throws Exception { buf.append("EXISTING"); getFormatter("hello").formatTo(dta, buf); - assertEquals(buf.toString(), "EXISTINGhello"); + assertEquals("EXISTINGhello", buf.toString()); } + @Test public void test_print_emptyAppendable() throws Exception { getFormatter("hello").formatTo(dta, buf); - assertEquals(buf.toString(), "hello"); + assertEquals("hello", buf.toString()); } //----------------------------------------------------------------------- + @Test public void test_toString() throws Exception { - assertEquals(getFormatter("hello").toString(), "'hello'"); + assertEquals("'hello'", getFormatter("hello").toString()); } + @Test public void test_toString_apos() throws Exception { - assertEquals(getFormatter("o'clock").toString(), "'o''clock'"); + assertEquals("'o''clock'", getFormatter("o'clock").toString()); } } diff --git a/test/jdk/java/time/test/java/time/format/TestTextParser.java b/test/jdk/java/time/test/java/time/format/TestTextParser.java index b6126a6b407..2482cbc5a6e 100644 --- a/test/jdk/java/time/test/java/time/format/TestTextParser.java +++ b/test/jdk/java/time/test/java/time/format/TestTextParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -63,8 +63,9 @@ import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.IsoFields.QUARTER_OF_YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.text.ParsePosition; import java.time.DayOfWeek; @@ -77,17 +78,18 @@ import java.time.temporal.TemporalQueries; import java.time.temporal.ChronoField; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test TextPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestTextParser extends AbstractTestPrinterParser { //----------------------------------------------------------------------- - @DataProvider(name="error") Object[][] data_error() { return new Object[][] { {DAY_OF_WEEK, TextStyle.FULL, "Monday", -1, IndexOutOfBoundsException.class}, @@ -95,7 +97,8 @@ public class TestTextParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="error") + @ParameterizedTest + @MethodSource("data_error") public void test_parse_error(TemporalField field, TextStyle style, String text, int pos, Class expected) { try { getFormatter(field, style).parseUnresolved(text, new ParsePosition(pos)); @@ -105,49 +108,53 @@ public class TestTextParser extends AbstractTestPrinterParser { } //----------------------------------------------------------------------- + @Test public void test_parse_midStr() throws Exception { ParsePosition pos = new ParsePosition(3); - assertEquals(getFormatter(DAY_OF_WEEK, TextStyle.FULL) - .parseUnresolved("XxxMondayXxx", pos) - .getLong(DAY_OF_WEEK), 1L); - assertEquals(pos.getIndex(), 9); + assertEquals(1L, getFormatter(DAY_OF_WEEK, TextStyle.FULL) + .parseUnresolved("XxxMondayXxx", pos) + .getLong(DAY_OF_WEEK)); + assertEquals(9, pos.getIndex()); } + @Test public void test_parse_remainderIgnored() throws Exception { ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(DAY_OF_WEEK, TextStyle.SHORT) - .parseUnresolved("Wednesday", pos) - .getLong(DAY_OF_WEEK), 3L); - assertEquals(pos.getIndex(), 3); + assertEquals(3L, getFormatter(DAY_OF_WEEK, TextStyle.SHORT) + .parseUnresolved("Wednesday", pos) + .getLong(DAY_OF_WEEK)); + assertEquals(3, pos.getIndex()); } //----------------------------------------------------------------------- + @Test public void test_parse_noMatch1() throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(DAY_OF_WEEK, TextStyle.FULL).parseUnresolved("Munday", pos); - assertEquals(pos.getErrorIndex(), 0); - assertEquals(parsed, null); + assertEquals(0, pos.getErrorIndex()); + assertEquals(null, parsed); } + @Test public void test_parse_noMatch2() throws Exception { ParsePosition pos = new ParsePosition(3); TemporalAccessor parsed = getFormatter(DAY_OF_WEEK, TextStyle.FULL).parseUnresolved("Monday", pos); - assertEquals(pos.getErrorIndex(), 3); - assertEquals(parsed, null); + assertEquals(3, pos.getErrorIndex()); + assertEquals(null, parsed); } + @Test public void test_parse_noMatch_atEnd() throws Exception { ParsePosition pos = new ParsePosition(6); TemporalAccessor parsed = getFormatter(DAY_OF_WEEK, TextStyle.FULL).parseUnresolved("Monday", pos); - assertEquals(pos.getErrorIndex(), 6); - assertEquals(parsed, null); + assertEquals(6, pos.getErrorIndex()); + assertEquals(null, parsed); } //----------------------------------------------------------------------- - @DataProvider(name="parseText") Object[][] provider_text() { return new Object[][] { {DAY_OF_WEEK, TextStyle.FULL, 1, "Monday"}, @@ -189,7 +196,6 @@ public class TestTextParser extends AbstractTestPrinterParser { }; } - @DataProvider(name="parseNumber") Object[][] provider_number() { return new Object[][] { {DAY_OF_MONTH, TextStyle.FULL, 1, "1"}, @@ -204,7 +210,6 @@ public class TestTextParser extends AbstractTestPrinterParser { }; } - @DataProvider(name="parseDayOfWeekText") Object[][] providerDayOfWeekData() { return new Object[][] { // Locale, pattern, input text, expected DayOfWeek @@ -215,30 +220,34 @@ public class TestTextParser extends AbstractTestPrinterParser { } - @Test(dataProvider="parseText") + @ParameterizedTest + @MethodSource("provider_text") public void test_parseText(TemporalField field, TextStyle style, int value, String input) throws Exception { ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(field, style).parseUnresolved(input, pos).getLong(field), (long) value); - assertEquals(pos.getIndex(), input.length()); + assertEquals((long) value, getFormatter(field, style).parseUnresolved(input, pos).getLong(field)); + assertEquals(input.length(), pos.getIndex()); } - @Test(dataProvider="parseNumber") + @ParameterizedTest + @MethodSource("provider_number") public void test_parseNumber(TemporalField field, TextStyle style, int value, String input) throws Exception { ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(field, style).parseUnresolved(input, pos).getLong(field), (long) value); - assertEquals(pos.getIndex(), input.length()); + assertEquals((long) value, getFormatter(field, style).parseUnresolved(input, pos).getLong(field)); + assertEquals(input.length(), pos.getIndex()); } - @Test(dataProvider="parseDayOfWeekText") + @ParameterizedTest + @MethodSource("providerDayOfWeekData") public void test_parseDayOfWeekText(Locale locale, String pattern, String input, DayOfWeek expected) { DateTimeFormatter formatter = getPatternFormatter(pattern).withLocale(locale); ParsePosition pos = new ParsePosition(0); - assertEquals(DayOfWeek.from(formatter.parse(input, pos)), expected); - assertEquals(pos.getIndex(), input.length()); + assertEquals(expected, DayOfWeek.from(formatter.parse(input, pos))); + assertEquals(input.length(), pos.getIndex()); } //----------------------------------------------------------------------- - @Test(dataProvider="parseText") + @ParameterizedTest + @MethodSource("provider_text") public void test_parse_strict_caseSensitive_parseUpper(TemporalField field, TextStyle style, int value, String input) throws Exception { if (input.equals(input.toUpperCase(Locale.ROOT))) { // Skip if the given input is all upper case (e.g., "Q1") @@ -247,19 +256,21 @@ public class TestTextParser extends AbstractTestPrinterParser { setCaseSensitive(true); ParsePosition pos = new ParsePosition(0); getFormatter(field, style).parseUnresolved(input.toUpperCase(Locale.ROOT), pos); - assertEquals(pos.getErrorIndex(), 0); + assertEquals(0, pos.getErrorIndex()); } - @Test(dataProvider="parseText") + @ParameterizedTest + @MethodSource("provider_text") public void test_parse_strict_caseInsensitive_parseUpper(TemporalField field, TextStyle style, int value, String input) throws Exception { setCaseSensitive(false); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(field, style).parseUnresolved(input.toUpperCase(Locale.ROOT), pos).getLong(field), (long) value); - assertEquals(pos.getIndex(), input.length()); + assertEquals((long) value, getFormatter(field, style).parseUnresolved(input.toUpperCase(Locale.ROOT), pos).getLong(field)); + assertEquals(input.length(), pos.getIndex()); } //----------------------------------------------------------------------- - @Test(dataProvider="parseText") + @ParameterizedTest + @MethodSource("provider_text") public void test_parse_strict_caseSensitive_parseLower(TemporalField field, TextStyle style, int value, String input) throws Exception { if (input.equals(input.toLowerCase(Locale.ROOT))) { // Skip if the given input is all lower case (e.g., "1st quarter") @@ -268,105 +279,118 @@ public class TestTextParser extends AbstractTestPrinterParser { setCaseSensitive(true); ParsePosition pos = new ParsePosition(0); getFormatter(field, style).parseUnresolved(input.toLowerCase(Locale.ROOT), pos); - assertEquals(pos.getErrorIndex(), 0); + assertEquals(0, pos.getErrorIndex()); } - @Test(dataProvider="parseText") + @ParameterizedTest + @MethodSource("provider_text") public void test_parse_strict_caseInsensitive_parseLower(TemporalField field, TextStyle style, int value, String input) throws Exception { setCaseSensitive(false); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(field, style).parseUnresolved(input.toLowerCase(Locale.ROOT), pos).getLong(field), (long) value); - assertEquals(pos.getIndex(), input.length()); + assertEquals((long) value, getFormatter(field, style).parseUnresolved(input.toLowerCase(Locale.ROOT), pos).getLong(field)); + assertEquals(input.length(), pos.getIndex()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- + @Test public void test_parse_full_strict_full_match() throws Exception { setStrict(true); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.FULL).parseUnresolved("January", pos).getLong(MONTH_OF_YEAR), 1L); - assertEquals(pos.getIndex(), 7); + assertEquals(1L, getFormatter(MONTH_OF_YEAR, TextStyle.FULL).parseUnresolved("January", pos).getLong(MONTH_OF_YEAR)); + assertEquals(7, pos.getIndex()); } + @Test public void test_parse_full_strict_short_noMatch() throws Exception { setStrict(true); ParsePosition pos = new ParsePosition(0); getFormatter(MONTH_OF_YEAR, TextStyle.FULL).parseUnresolved("Janua", pos); - assertEquals(pos.getErrorIndex(), 0); + assertEquals(0, pos.getErrorIndex()); } + @Test public void test_parse_full_strict_number_noMatch() throws Exception { setStrict(true); ParsePosition pos = new ParsePosition(0); getFormatter(MONTH_OF_YEAR, TextStyle.FULL).parseUnresolved("1", pos); - assertEquals(pos.getErrorIndex(), 0); + assertEquals(0, pos.getErrorIndex()); } //----------------------------------------------------------------------- + @Test public void test_parse_short_strict_full_match() throws Exception { setStrict(true); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("January", pos).getLong(MONTH_OF_YEAR), 1L); - assertEquals(pos.getIndex(), 3); + assertEquals(1L, getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("January", pos).getLong(MONTH_OF_YEAR)); + assertEquals(3, pos.getIndex()); } + @Test public void test_parse_short_strict_short_match() throws Exception { setStrict(true); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("Janua", pos).getLong(MONTH_OF_YEAR), 1L); - assertEquals(pos.getIndex(), 3); + assertEquals(1L, getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("Janua", pos).getLong(MONTH_OF_YEAR)); + assertEquals(3, pos.getIndex()); } + @Test public void test_parse_short_strict_number_noMatch() throws Exception { setStrict(true); ParsePosition pos = new ParsePosition(0); getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("1", pos); - assertEquals(pos.getErrorIndex(), 0); + assertEquals(0, pos.getErrorIndex()); } //----------------------------------------------------------------------- + @Test public void test_parse_full_lenient_full_match() throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.FULL).parseUnresolved("January.", pos).getLong(MONTH_OF_YEAR), 1L); - assertEquals(pos.getIndex(), 7); + assertEquals(1L, getFormatter(MONTH_OF_YEAR, TextStyle.FULL).parseUnresolved("January.", pos).getLong(MONTH_OF_YEAR)); + assertEquals(7, pos.getIndex()); } + @Test public void test_parse_full_lenient_short_match() throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.FULL).parseUnresolved("Janua", pos).getLong(MONTH_OF_YEAR), 1L); - assertEquals(pos.getIndex(), 3); + assertEquals(1L, getFormatter(MONTH_OF_YEAR, TextStyle.FULL).parseUnresolved("Janua", pos).getLong(MONTH_OF_YEAR)); + assertEquals(3, pos.getIndex()); } + @Test public void test_parse_full_lenient_number_match() throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.FULL).parseUnresolved("1", pos).getLong(MONTH_OF_YEAR), 1L); - assertEquals(pos.getIndex(), 1); + assertEquals(1L, getFormatter(MONTH_OF_YEAR, TextStyle.FULL).parseUnresolved("1", pos).getLong(MONTH_OF_YEAR)); + assertEquals(1, pos.getIndex()); } //----------------------------------------------------------------------- + @Test public void test_parse_short_lenient_full_match() throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("January", pos).getLong(MONTH_OF_YEAR), 1L); - assertEquals(pos.getIndex(), 7); + assertEquals(1L, getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("January", pos).getLong(MONTH_OF_YEAR)); + assertEquals(7, pos.getIndex()); } + @Test public void test_parse_short_lenient_short_match() throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("Janua", pos).getLong(MONTH_OF_YEAR), 1L); - assertEquals(pos.getIndex(), 3); + assertEquals(1L, getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("Janua", pos).getLong(MONTH_OF_YEAR)); + assertEquals(3, pos.getIndex()); } + @Test public void test_parse_short_lenient_number_match() throws Exception { setStrict(false); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("1", pos).getLong(MONTH_OF_YEAR), 1L); - assertEquals(pos.getIndex(), 1); + assertEquals(1L, getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).parseUnresolved("1", pos).getLong(MONTH_OF_YEAR)); + assertEquals(1, pos.getIndex()); } } diff --git a/test/jdk/java/time/test/java/time/format/TestTextParserWithLocale.java b/test/jdk/java/time/test/java/time/format/TestTextParserWithLocale.java index 371c5180832..35d458d6b45 100644 --- a/test/jdk/java/time/test/java/time/format/TestTextParserWithLocale.java +++ b/test/jdk/java/time/test/java/time/format/TestTextParserWithLocale.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -81,24 +81,26 @@ import java.time.temporal.ChronoField; import java.time.temporal.TemporalField; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test TextPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestTextParserWithLocale extends AbstractTestPrinterParser { static final Locale RUSSIAN = Locale.of("ru"); static final Locale FINNISH = Locale.of("fi"); - @DataProvider(name="parseDayOfWeekText") Object[][] providerDayOfWeekData() { return new Object[][] { // Locale, pattern, input text, expected DayOfWeek @@ -112,17 +114,17 @@ public class TestTextParserWithLocale extends AbstractTestPrinterParser { }; } - @Test(dataProvider="parseDayOfWeekText") + @ParameterizedTest + @MethodSource("providerDayOfWeekData") public void test_parseDayOfWeekText(Locale locale, String pattern, String input, DayOfWeek expected) { DateTimeFormatter formatter = getPatternFormatter(pattern).withLocale(locale); ParsePosition pos = new ParsePosition(0); - assertEquals(DayOfWeek.from(formatter.parse(input, pos)), expected); - assertEquals(pos.getIndex(), input.length()); + assertEquals(expected, DayOfWeek.from(formatter.parse(input, pos))); + assertEquals(input.length(), pos.getIndex()); } //-------------------------------------------------------------------- // Test data is dependent on localized resources. - @DataProvider(name="parseStandaloneText") Object[][] providerStandaloneText() { // Locale, TemporalField, TextStyle, expected value, input text return new Object[][] { @@ -136,7 +138,6 @@ public class TestTextParserWithLocale extends AbstractTestPrinterParser { } // Test data is dependent on localized resources. - @DataProvider(name="parseLenientText") Object[][] providerLenientText() { // Locale, TemporalField, expected value, input text return new Object[][] { @@ -147,47 +148,49 @@ public class TestTextParserWithLocale extends AbstractTestPrinterParser { }; } - @Test(dataProvider="parseStandaloneText") + @ParameterizedTest + @MethodSource("providerStandaloneText") public void test_parseStandaloneText(Locale locale, TemporalField field, TextStyle style, int expectedValue, String input) { DateTimeFormatter formatter = getFormatter(field, style).withLocale(locale); ParsePosition pos = new ParsePosition(0); - assertEquals(formatter.parseUnresolved(input, pos).getLong(field), (long) expectedValue); - assertEquals(pos.getIndex(), input.length()); + assertEquals((long) expectedValue, formatter.parseUnresolved(input, pos).getLong(field)); + assertEquals(input.length(), pos.getIndex()); } //----------------------------------------------------------------------- + @Test public void test_parse_french_short_strict_full_noMatch() throws Exception { setStrict(true); ParsePosition pos = new ParsePosition(0); getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).withLocale(Locale.FRENCH) .parseUnresolved("janvier", pos); - assertEquals(pos.getErrorIndex(), 0); + assertEquals(0, pos.getErrorIndex()); } + @Test public void test_parse_french_short_strict_short_match() throws Exception { setStrict(true); ParsePosition pos = new ParsePosition(0); - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).withLocale(Locale.FRENCH) - .parseUnresolved("janv.", pos) - .getLong(MONTH_OF_YEAR), - 1L); - assertEquals(pos.getIndex(), 5); + assertEquals(1L, getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).withLocale(Locale.FRENCH) + .parseUnresolved("janv.", pos) + .getLong(MONTH_OF_YEAR)); + assertEquals(5, pos.getIndex()); } //----------------------------------------------------------------------- - @Test(dataProvider="parseLenientText") + @ParameterizedTest + @MethodSource("providerLenientText") public void test_parseLenientText(Locale locale, TemporalField field, int expectedValue, String input) { setStrict(false); ParsePosition pos = new ParsePosition(0); DateTimeFormatter formatter = getFormatter(field).withLocale(locale); - assertEquals(formatter.parseUnresolved(input, pos).getLong(field), (long) expectedValue); - assertEquals(pos.getIndex(), input.length()); + assertEquals((long) expectedValue, formatter.parseUnresolved(input, pos).getLong(field)); + assertEquals(input.length(), pos.getIndex()); } //----------------------------------------------------------------------- - @DataProvider(name="parseChronoLocalDate") Object[][] provider_chronoLocalDate() { return new Object[][] { { HijrahDate.now() }, @@ -213,14 +216,15 @@ public class TestTextParserWithLocale extends AbstractTestPrinterParser { .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NEVER) .toFormatter(); - @Test(dataProvider="parseChronoLocalDate") + @ParameterizedTest + @MethodSource("provider_chronoLocalDate") public void test_chronoLocalDate(ChronoLocalDate date) throws Exception { System.out.printf(" %s, [fmt=%s]%n", date, fmt_chrono.format(date)); - assertEquals(date, fmt_chrono.parse(fmt_chrono.format(date), ChronoLocalDate::from)); + assertEquals(fmt_chrono.parse(fmt_chrono.format(date), ChronoLocalDate::from), date); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("[GGG ]yyy-MM-dd") .withChronology(date.getChronology()); System.out.printf(" %s, [fmt=%s]%n", date.toString(), fmt.format(date)); - assertEquals(date, fmt.parse(fmt.format(date), ChronoLocalDate::from)); + assertEquals(fmt.parse(fmt.format(date), ChronoLocalDate::from), date); } } diff --git a/test/jdk/java/time/test/java/time/format/TestTextPrinter.java b/test/jdk/java/time/test/java/time/format/TestTextPrinter.java index 379d6a23bb0..f07c935b025 100644 --- a/test/jdk/java/time/test/java/time/format/TestTextPrinter.java +++ b/test/jdk/java/time/test/java/time/format/TestTextPrinter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -64,7 +64,8 @@ import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.ERA; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.IsoFields.QUARTER_OF_YEAR; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DateTimeException; import java.time.DayOfWeek; @@ -75,30 +76,34 @@ import java.time.format.TextStyle; import java.time.temporal.TemporalField; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.temporal.MockFieldValue; /** * Test TextPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestTextPrinter extends AbstractTestPrinterParser { //----------------------------------------------------------------------- - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_emptyCalendrical() throws Exception { - getFormatter(DAY_OF_WEEK, TextStyle.FULL).formatTo(EMPTY_DTA, buf); + Assertions.assertThrows(DateTimeException.class, () -> getFormatter(DAY_OF_WEEK, TextStyle.FULL).formatTo(EMPTY_DTA, buf)); } + @Test public void test_print_append() throws Exception { buf.append("EXISTING"); getFormatter(DAY_OF_WEEK, TextStyle.FULL).formatTo(LocalDate.of(2012, 4, 18), buf); - assertEquals(buf.toString(), "EXISTINGWednesday"); + assertEquals("EXISTINGWednesday", buf.toString()); } //----------------------------------------------------------------------- - @DataProvider(name="print") Object[][] provider_dow() { return new Object[][] { {DAY_OF_WEEK, TextStyle.FULL, 1, "Monday"}, @@ -204,7 +209,6 @@ public class TestTextPrinter extends AbstractTestPrinterParser { }; } - @DataProvider(name="print_DayOfWeekData") Object[][] providerDayOfWeekData() { return new Object[][] { // Locale, pattern, expected text, input DayOfWeek @@ -214,26 +218,30 @@ public class TestTextPrinter extends AbstractTestPrinterParser { }; } - @Test(dataProvider="print") + @ParameterizedTest + @MethodSource("provider_dow") public void test_format(TemporalField field, TextStyle style, int value, String expected) throws Exception { getFormatter(field, style).formatTo(new MockFieldValue(field, value), buf); - assertEquals(buf.toString(), expected); + assertEquals(expected, buf.toString()); } - @Test(dataProvider="print_DayOfWeekData") + @ParameterizedTest + @MethodSource("providerDayOfWeekData") public void test_formatDayOfWeek(Locale locale, String pattern, String expected, DayOfWeek dayOfWeek) { DateTimeFormatter formatter = getPatternFormatter(pattern).withLocale(locale); String text = formatter.format(dayOfWeek); - assertEquals(text, expected); + assertEquals(expected, text); } //----------------------------------------------------------------------- + @Test public void test_toString1() throws Exception { - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.FULL).toString(), "Text(MonthOfYear)"); + assertEquals("Text(MonthOfYear)", getFormatter(MONTH_OF_YEAR, TextStyle.FULL).toString()); } + @Test public void test_toString2() throws Exception { - assertEquals(getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).toString(), "Text(MonthOfYear,SHORT)"); + assertEquals("Text(MonthOfYear,SHORT)", getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).toString()); } } diff --git a/test/jdk/java/time/test/java/time/format/TestTextPrinterWithLocale.java b/test/jdk/java/time/test/java/time/format/TestTextPrinterWithLocale.java index abbe4302f99..9b85de777b1 100644 --- a/test/jdk/java/time/test/java/time/format/TestTextPrinterWithLocale.java +++ b/test/jdk/java/time/test/java/time/format/TestTextPrinterWithLocale.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -70,7 +70,8 @@ import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.ERA; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.IsoFields.QUARTER_OF_YEAR; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DateTimeException; import java.time.DayOfWeek; @@ -81,20 +82,22 @@ import java.time.format.TextStyle; import java.time.temporal.TemporalField; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.temporal.MockFieldValue; /** * Test TextPrinterParserWithLocale. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestTextPrinterWithLocale extends AbstractTestPrinterParser { static final Locale RUSSIAN = Locale.of("ru"); static final Locale FINNISH = Locale.of("fi"); //----------------------------------------------------------------------- - @DataProvider(name="print_DayOfWeekData") Object[][] providerDayOfWeekData() { return new Object[][] { // Locale, pattern, expected text, input DayOfWeek @@ -109,7 +112,6 @@ public class TestTextPrinterWithLocale extends AbstractTestPrinterParser { } // Test data is dependent on localized resources. - @DataProvider(name="print_standalone") Object[][] provider_StandaloneNames() { return new Object[][] { // standalone names for 2013-01-01 (Tue) @@ -121,31 +123,34 @@ public class TestTextPrinterWithLocale extends AbstractTestPrinterParser { }; } - @Test(dataProvider="print_DayOfWeekData") + @ParameterizedTest + @MethodSource("providerDayOfWeekData") public void test_formatDayOfWeek(Locale locale, String pattern, String expected, DayOfWeek dayOfWeek) { DateTimeFormatter formatter = getPatternFormatter(pattern).withLocale(locale); String text = formatter.format(dayOfWeek); - assertEquals(text, expected); + assertEquals(expected, text); } - @Test(dataProvider="print_standalone") + @ParameterizedTest + @MethodSource("provider_StandaloneNames") public void test_standaloneNames(Locale locale, TemporalField field, TextStyle style, String expected) { getFormatter(field, style).withLocale(locale).formatTo(LocalDate.of(2013, 1, 1), buf); - assertEquals(buf.toString(), expected); + assertEquals(expected, buf.toString()); } //----------------------------------------------------------------------- + @Test public void test_print_french_long() throws Exception { getFormatter(MONTH_OF_YEAR, TextStyle.FULL).withLocale(Locale.FRENCH).formatTo(LocalDate.of(2012, 1, 1), buf); - assertEquals(buf.toString(), "janvier"); + assertEquals("janvier", buf.toString()); } + @Test public void test_print_french_short() throws Exception { getFormatter(MONTH_OF_YEAR, TextStyle.SHORT).withLocale(Locale.FRENCH).formatTo(LocalDate.of(2012, 1, 1), buf); - assertEquals(buf.toString(), "janv."); + assertEquals("janv.", buf.toString()); } - @DataProvider(name="print_JapaneseChronology") Object[][] provider_japaneseEra() { return new Object[][] { {ERA, TextStyle.FULL, 2, "Heisei"}, // Note: CLDR doesn't define "wide" Japanese era names. @@ -154,10 +159,11 @@ public class TestTextPrinterWithLocale extends AbstractTestPrinterParser { }; }; - @Test(dataProvider="print_JapaneseChronology") + @ParameterizedTest + @MethodSource("provider_japaneseEra") public void test_formatJapaneseEra(TemporalField field, TextStyle style, int value, String expected) throws Exception { LocalDate ld = LocalDate.of(2013, 1, 31); getFormatter(field, style).withChronology(JapaneseChronology.INSTANCE).formatTo(ld, buf); - assertEquals(buf.toString(), expected); + assertEquals(expected, buf.toString()); } } diff --git a/test/jdk/java/time/test/java/time/format/TestUTCParse.java b/test/jdk/java/time/test/java/time/format/TestUTCParse.java index 2c41af68281..551f660e368 100644 --- a/test/jdk/java/time/test/java/time/format/TestUTCParse.java +++ b/test/jdk/java/time/test/java/time/format/TestUTCParse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -33,13 +33,14 @@ import java.time.format.DateTimeFormatterBuilder; import java.time.format.TextStyle; import java.time.temporal.TemporalQueries; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestUTCParse { - @DataProvider public Object[][] utcZoneIdStrings() { return new Object[][] { {"UTC"}, @@ -48,12 +49,13 @@ public class TestUTCParse { }; } - @Test(dataProvider = "utcZoneIdStrings") + @ParameterizedTest + @MethodSource("utcZoneIdStrings") public void testUTCOffsetRoundTrip(String zidString) { var fmt = new DateTimeFormatterBuilder() .appendZoneText(TextStyle.NARROW) .toFormatter(); var zid = ZoneId.of(zidString); - assertEquals(fmt.parse(zidString).query(TemporalQueries.zoneId()), zid); + assertEquals(zid, fmt.parse(zidString).query(TemporalQueries.zoneId())); } } diff --git a/test/jdk/java/time/test/java/time/format/TestUnicodeExtension.java b/test/jdk/java/time/test/java/time/format/TestUnicodeExtension.java index 6b99fea5c7c..80460fad007 100644 --- a/test/jdk/java/time/test/java/time/format/TestUnicodeExtension.java +++ b/test/jdk/java/time/test/java/time/format/TestUnicodeExtension.java @@ -31,7 +31,7 @@ */ package test.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DayOfWeek; import java.time.ZonedDateTime; @@ -50,15 +50,16 @@ import java.util.Locale; import java.util.TimeZone; import java.util.stream.Stream; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test JavaTime with BCP47 U extensions */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestUnicodeExtension { private static TimeZone defaultTZ; @@ -87,18 +88,17 @@ public class TestUnicodeExtension { private static final String PATTERN = "GGGG MMMM-dd-uu HH:mm:ss zzzz"; - @BeforeTest + @BeforeAll public void beforeTest() { defaultTZ = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone(AMLA)); } - @AfterTest + @AfterAll public void afterTest() { TimeZone.setDefault(defaultTZ); } - @DataProvider(name="localizedBy") Object[][] localizedBy() { return new Object[][] { // Locale, Chrono override, Zone override, Expected Chrono, Expected Zone, @@ -188,7 +188,6 @@ public class TestUnicodeExtension { }; } - @DataProvider(name="withLocale") Object[][] withLocale() { return new Object[][] { // Locale, Chrono override, Zone override, Expected Chrono, Expected Zone, @@ -277,7 +276,6 @@ public class TestUnicodeExtension { }; } - @DataProvider(name="firstDayOfWeek") Object[][] firstDayOfWeek () { return new Object[][] { // Locale, Expected DayOfWeek, @@ -304,7 +302,6 @@ public class TestUnicodeExtension { }; } - @DataProvider(name="minDaysInFirstWeek") Object[][] minDaysInFrstWeek () { return new Object[][] { // Locale, Expected minDay, @@ -316,7 +313,6 @@ public class TestUnicodeExtension { }; } - @DataProvider(name="ofPattern") Object[][] ofPattern() { return new Object[][] { // Locale, Expected Chrono, Expected Zone, @@ -342,7 +338,6 @@ public class TestUnicodeExtension { }; } - @DataProvider(name="shortTZID") Object[][] shortTZID() { return new Object[][] { // LDML's short ID, Expected Zone, @@ -817,7 +812,6 @@ public class TestUnicodeExtension { }; } - @DataProvider(name="getLocalizedDateTimePattern") Object[][] getLocalizedDateTimePattern() { return new Object[][] { // Locale, Expected pattern, @@ -832,7 +826,6 @@ public class TestUnicodeExtension { }; } - @DataProvider(name="getDisplayName") Object[][] getDisplayName() { return new Object[][] { // Locale, field, Expected name, @@ -841,7 +834,8 @@ public class TestUnicodeExtension { }; } - @Test(dataProvider="localizedBy") + @ParameterizedTest + @MethodSource("localizedBy") public void test_localizedBy(Locale locale, Chronology chrono, ZoneId zone, Chronology chronoExpected, ZoneId zoneExpected, String formatExpected) { @@ -855,91 +849,94 @@ public class TestUnicodeExtension { DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.FULL) .withChronology(chrono).withZone(zone).localizedBy(locale); - assertEquals(dtf.getChronology(), chronoExpected); - assertEquals(dtf.getZone(), zoneExpected); + assertEquals(chronoExpected, dtf.getChronology()); + assertEquals(zoneExpected, dtf.getZone()); String formatted = dtf.format(ZDT); - assertEquals(formatted, formatExpected); - assertEquals(dtf.parse(formatted, ZonedDateTime::from), - zoneExpected != null ? ZDT.withZoneSameInstant(zoneExpected) : ZDT); + assertEquals(formatExpected, formatted); + assertEquals(zoneExpected != null ? ZDT.withZoneSameInstant(zoneExpected) : ZDT, dtf.parse(formatted, ZonedDateTime::from)); }); } finally { Locale.setDefault(def); } } - @Test(dataProvider="withLocale") + @ParameterizedTest + @MethodSource("withLocale") public void test_withLocale(Locale locale, Chronology chrono, ZoneId zone, Chronology chronoExpected, ZoneId zoneExpected, String formatExpected) { DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.FULL) .withChronology(chrono).withZone(zone).withLocale(locale); - assertEquals(dtf.getChronology(), chronoExpected); - assertEquals(dtf.getZone(), zoneExpected); + assertEquals(chronoExpected, dtf.getChronology()); + assertEquals(zoneExpected, dtf.getZone()); String formatted = dtf.format(ZDT); - assertEquals(formatted, formatExpected); - assertEquals(dtf.parse(formatted, ZonedDateTime::from), - zoneExpected != null ? ZDT.withZoneSameInstant(zoneExpected) : ZDT); + assertEquals(formatExpected, formatted); + assertEquals(zoneExpected != null ? ZDT.withZoneSameInstant(zoneExpected) : ZDT, dtf.parse(formatted, ZonedDateTime::from)); } - @Test(dataProvider="firstDayOfWeek") + @ParameterizedTest + @MethodSource("firstDayOfWeek") public void test_firstDayOfWeek(Locale locale, DayOfWeek dowExpected) { DayOfWeek dow = WeekFields.of(locale).getFirstDayOfWeek(); - assertEquals(dow, dowExpected); + assertEquals(dowExpected, dow); } - @Test(dataProvider="minDaysInFirstWeek") + @ParameterizedTest + @MethodSource("minDaysInFrstWeek") public void test_minDaysInFirstWeek(Locale locale, int minDaysExpected) { int minDays = WeekFields.of(locale).getMinimalDaysInFirstWeek(); - assertEquals(minDays, minDaysExpected); + assertEquals(minDaysExpected, minDays); } - @Test(dataProvider="ofPattern") + @ParameterizedTest + @MethodSource("ofPattern") public void test_ofPattern(Locale locale, Chronology chronoExpected, ZoneId zoneExpected, String formatExpected) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(PATTERN, locale); - assertEquals(dtf.getChronology(), chronoExpected); - assertEquals(dtf.getZone(), zoneExpected); + assertEquals(chronoExpected, dtf.getChronology()); + assertEquals(zoneExpected, dtf.getZone()); String formatted = dtf.format(ZDT); - assertEquals(formatted, formatExpected); - assertEquals(dtf.parse(formatted, ZonedDateTime::from), - zoneExpected != null ? ZDT.withZoneSameInstant(zoneExpected) : ZDT); + assertEquals(formatExpected, formatted); + assertEquals(zoneExpected != null ? ZDT.withZoneSameInstant(zoneExpected) : ZDT, dtf.parse(formatted, ZonedDateTime::from)); } - @Test(dataProvider="ofPattern") + @ParameterizedTest + @MethodSource("ofPattern") public void test_toFormatter(Locale locale, Chronology chronoExpected, ZoneId zoneExpected, String formatExpected) { DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern(PATTERN).toFormatter(locale); - assertEquals(dtf.getChronology(), chronoExpected); - assertEquals(dtf.getZone(), zoneExpected); + assertEquals(chronoExpected, dtf.getChronology()); + assertEquals(zoneExpected, dtf.getZone()); String formatted = dtf.format(ZDT); - assertEquals(formatted, formatExpected); - assertEquals(dtf.parse(formatted, ZonedDateTime::from), - zoneExpected != null ? ZDT.withZoneSameInstant(zoneExpected) : ZDT); + assertEquals(formatExpected, formatted); + assertEquals(zoneExpected != null ? ZDT.withZoneSameInstant(zoneExpected) : ZDT, dtf.parse(formatted, ZonedDateTime::from)); } - @Test(dataProvider="shortTZID") + @ParameterizedTest + @MethodSource("shortTZID") public void test_shortTZID(String shortID, String expectedZone) { Locale l = Locale.forLanguageTag("en-US-u-tz-" + shortID); DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.FULL) .localizedBy(l); - assertEquals(dtf.getZone(), ZoneId.of(expectedZone)); + assertEquals(ZoneId.of(expectedZone), dtf.getZone()); } - @Test(dataProvider="getLocalizedDateTimePattern") + @ParameterizedTest + @MethodSource("getLocalizedDateTimePattern") public void test_getLocalizedDateTimePattern(Locale l, FormatStyle s, String expectedPattern) { DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder(); - assertEquals(dtfb.getLocalizedDateTimePattern(s, s, IsoChronology.INSTANCE, l), - expectedPattern); + assertEquals(expectedPattern, dtfb.getLocalizedDateTimePattern(s, s, IsoChronology.INSTANCE, l)); } - @Test(dataProvider="getDisplayName") + @ParameterizedTest + @MethodSource("getDisplayName") public void test_getDisplayName(Locale l, TemporalField f, String expectedName) { - assertEquals(f.getDisplayName(l), expectedName); + assertEquals(expectedName, f.getDisplayName(l)); } } diff --git a/test/jdk/java/time/test/java/time/format/TestZoneOffsetParser.java b/test/jdk/java/time/test/java/time/format/TestZoneOffsetParser.java index 32425549834..b5807e3cb2d 100644 --- a/test/jdk/java/time/test/java/time/format/TestZoneOffsetParser.java +++ b/test/jdk/java/time/test/java/time/format/TestZoneOffsetParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -60,24 +60,26 @@ package test.java.time.format; import static java.time.temporal.ChronoField.OFFSET_SECONDS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.text.ParsePosition; import java.time.ZoneOffset; import java.time.temporal.TemporalAccessor; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test ZoneOffsetPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestZoneOffsetParser extends AbstractTestPrinterParser { //----------------------------------------------------------------------- - @DataProvider(name="error") Object[][] data_error() { return new Object[][] { {"+HH:MM:ss", "Z", "hello", -1, IndexOutOfBoundsException.class}, @@ -85,7 +87,8 @@ public class TestZoneOffsetParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="error") + @ParameterizedTest + @MethodSource("data_error") public void test_parse_error(String pattern, String noOffsetText, String text, int pos, Class expected) { try { getFormatter(pattern, noOffsetText).parseUnresolved(text, new ParsePosition(pos)); @@ -95,65 +98,72 @@ public class TestZoneOffsetParser extends AbstractTestPrinterParser { } //----------------------------------------------------------------------- + @Test public void test_parse_exactMatch_UTC() throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("Z", pos); - assertEquals(pos.getIndex(), 1); + assertEquals(1, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } + @Test public void test_parse_startStringMatch_UTC() throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("ZOTHER", pos); - assertEquals(pos.getIndex(), 1); + assertEquals(1, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } + @Test public void test_parse_midStringMatch_UTC() throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("OTHERZOTHER", pos); - assertEquals(pos.getIndex(), 6); + assertEquals(6, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } + @Test public void test_parse_endStringMatch_UTC() throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("OTHERZ", pos); - assertEquals(pos.getIndex(), 6); + assertEquals(6, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } //----------------------------------------------------------------------- + @Test public void test_parse_exactMatch_UTC_EmptyUTC() throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "").parseUnresolved("", pos); - assertEquals(pos.getIndex(), 0); + assertEquals(0, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } + @Test public void test_parse_startStringMatch_UTC_EmptyUTC() throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "").parseUnresolved("OTHER", pos); - assertEquals(pos.getIndex(), 0); + assertEquals(0, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } + @Test public void test_parse_midStringMatch_UTC_EmptyUTC() throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "").parseUnresolved("OTHEROTHER", pos); - assertEquals(pos.getIndex(), 5); + assertEquals(5, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } + @Test public void test_parse_endStringMatch_UTC_EmptyUTC() throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "").parseUnresolved("OTHER", pos); - assertEquals(pos.getIndex(), 5); + assertEquals(5, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } //----------------------------------------------------------------------- - @DataProvider(name="offsets") Object[][] provider_offsets() { return new Object[][] { {"+HH", "+00", ZoneOffset.UTC}, @@ -228,72 +238,79 @@ public class TestZoneOffsetParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="offsets") + @ParameterizedTest + @MethodSource("provider_offsets") public void test_parse_exactMatch(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(pattern, "Z").parseUnresolved(parse, pos); - assertEquals(pos.getIndex(), parse.length()); + assertEquals(parse.length(), pos.getIndex()); assertParsed(parsed, expected); } - @Test(dataProvider="offsets") + @ParameterizedTest + @MethodSource("provider_offsets") public void test_parse_startStringMatch(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(pattern, "Z").parseUnresolved(parse + ":OTHER", pos); - assertEquals(pos.getIndex(), parse.length()); + assertEquals(parse.length(), pos.getIndex()); assertParsed(parsed, expected); } - @Test(dataProvider="offsets") + @ParameterizedTest + @MethodSource("provider_offsets") public void test_parse_midStringMatch(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter(pattern, "Z").parseUnresolved("OTHER" + parse + ":OTHER", pos); - assertEquals(pos.getIndex(), parse.length() + 5); + assertEquals(parse.length() + 5, pos.getIndex()); assertParsed(parsed, expected); } - @Test(dataProvider="offsets") + @ParameterizedTest + @MethodSource("provider_offsets") public void test_parse_endStringMatch(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter(pattern, "Z").parseUnresolved("OTHER" + parse, pos); - assertEquals(pos.getIndex(), parse.length() + 5); + assertEquals(parse.length() + 5, pos.getIndex()); assertParsed(parsed, expected); } - @Test(dataProvider="offsets") + @ParameterizedTest + @MethodSource("provider_offsets") public void test_parse_exactMatch_EmptyUTC(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(pattern, "").parseUnresolved(parse, pos); - assertEquals(pos.getIndex(), parse.length()); + assertEquals(parse.length(), pos.getIndex()); assertParsed(parsed, expected); } - @Test(dataProvider="offsets") + @ParameterizedTest + @MethodSource("provider_offsets") public void test_parse_startStringMatch_EmptyUTC(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(pattern, "").parseUnresolved(parse + ":OTHER", pos); - assertEquals(pos.getIndex(), parse.length()); + assertEquals(parse.length(), pos.getIndex()); assertParsed(parsed, expected); } - @Test(dataProvider="offsets") + @ParameterizedTest + @MethodSource("provider_offsets") public void test_parse_midStringMatch_EmptyUTC(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter(pattern, "").parseUnresolved("OTHER" + parse + ":OTHER", pos); - assertEquals(pos.getIndex(), parse.length() + 5); + assertEquals(parse.length() + 5, pos.getIndex()); assertParsed(parsed, expected); } - @Test(dataProvider="offsets") + @ParameterizedTest + @MethodSource("provider_offsets") public void test_parse_endStringMatch_EmptyUTC(String pattern, String parse, ZoneOffset expected) throws Exception { ParsePosition pos = new ParsePosition(5); TemporalAccessor parsed = getFormatter(pattern, "").parseUnresolved("OTHER" + parse, pos); - assertEquals(pos.getIndex(), parse.length() + 5); + assertEquals(parse.length() + 5, pos.getIndex()); assertParsed(parsed, expected); } //----------------------------------------------------------------------- - @DataProvider(name="bigOffsets") Object[][] provider_bigOffsets() { return new Object[][] { {"+HH", "+19", 19 * 3600}, @@ -319,16 +336,16 @@ public class TestZoneOffsetParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="bigOffsets") + @ParameterizedTest + @MethodSource("provider_bigOffsets") public void test_parse_bigOffsets(String pattern, String parse, long offsetSecs) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(pattern, "").parseUnresolved(parse, pos); - assertEquals(pos.getIndex(), parse.length()); - assertEquals(parsed.getLong(OFFSET_SECONDS), offsetSecs); + assertEquals(parse.length(), pos.getIndex()); + assertEquals(offsetSecs, parsed.getLong(OFFSET_SECONDS)); } //----------------------------------------------------------------------- - @DataProvider(name="badOffsets") Object[][] provider_badOffsets() { return new Object[][] { {"+HH", "+1", 0}, @@ -390,55 +407,60 @@ public class TestZoneOffsetParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="badOffsets") + @ParameterizedTest + @MethodSource("provider_badOffsets") public void test_parse_invalid(String pattern, String parse, int expectedPosition) throws Exception { ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter(pattern, "Z").parseUnresolved(parse, pos); - assertEquals(pos.getErrorIndex(), expectedPosition); - assertEquals(parsed, null); + assertEquals(expectedPosition, pos.getErrorIndex()); + assertEquals(null, parsed); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- + @Test public void test_parse_caseSensitiveUTC_matchedCase() throws Exception { setCaseSensitive(true); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("Z", pos); - assertEquals(pos.getIndex(), 1); + assertEquals(1, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } + @Test public void test_parse_caseSensitiveUTC_unmatchedCase() throws Exception { setCaseSensitive(true); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("z", pos); - assertEquals(pos.getErrorIndex(), 0); - assertEquals(parsed, null); + assertEquals(0, pos.getErrorIndex()); + assertEquals(null, parsed); } + @Test public void test_parse_caseInsensitiveUTC_matchedCase() throws Exception { setCaseSensitive(false); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("Z", pos); - assertEquals(pos.getIndex(), 1); + assertEquals(1, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } + @Test public void test_parse_caseInsensitiveUTC_unmatchedCase() throws Exception { setCaseSensitive(false); ParsePosition pos = new ParsePosition(0); TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("z", pos); - assertEquals(pos.getIndex(), 1); + assertEquals(1, pos.getIndex()); assertParsed(parsed, ZoneOffset.UTC); } private void assertParsed(TemporalAccessor parsed, ZoneOffset expectedOffset) { if (expectedOffset == null) { - assertEquals(parsed, null); + assertEquals(null, parsed); } else { - assertEquals(parsed.isSupported(OFFSET_SECONDS), true); - assertEquals(parsed.getLong(OFFSET_SECONDS), (long) expectedOffset.getTotalSeconds()); + assertEquals(true, parsed.isSupported(OFFSET_SECONDS)); + assertEquals((long) expectedOffset.getTotalSeconds(), parsed.getLong(OFFSET_SECONDS)); } } diff --git a/test/jdk/java/time/test/java/time/format/TestZoneOffsetPrinter.java b/test/jdk/java/time/test/java/time/format/TestZoneOffsetPrinter.java index 4e1b7a402c7..12d54d12200 100644 --- a/test/jdk/java/time/test/java/time/format/TestZoneOffsetPrinter.java +++ b/test/jdk/java/time/test/java/time/format/TestZoneOffsetPrinter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,24 +59,26 @@ */ package test.java.time.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.DateTimeException; import java.time.ZoneOffset; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test ZoneOffsetPrinterParser. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestZoneOffsetPrinter extends AbstractTestPrinterParser { private static final ZoneOffset OFFSET_0130 = ZoneOffset.of("+01:30"); //----------------------------------------------------------------------- - @DataProvider(name="offsets") Object[][] provider_offsets() { return new Object[][] { {"+HH", "NO-OFFSET", ZoneOffset.UTC}, @@ -147,27 +149,30 @@ public class TestZoneOffsetPrinter extends AbstractTestPrinterParser { }; } - @Test(dataProvider="offsets") + @ParameterizedTest + @MethodSource("provider_offsets") public void test_format(String pattern, String expected, ZoneOffset offset) throws Exception { buf.append("EXISTING"); getFormatter(pattern, "NO-OFFSET").formatTo(offset, buf); - assertEquals(buf.toString(), "EXISTING" + expected); + assertEquals("EXISTING" + expected, buf.toString()); } - @Test(dataProvider="offsets") + @ParameterizedTest + @MethodSource("provider_offsets") public void test_toString(String pattern, String expected, ZoneOffset offset) throws Exception { - assertEquals(getFormatter(pattern, "NO-OFFSET").toString(), "Offset(" + pattern + ",'NO-OFFSET')"); + assertEquals("Offset(" + pattern + ",'NO-OFFSET')", getFormatter(pattern, "NO-OFFSET").toString()); } //----------------------------------------------------------------------- - @Test(expectedExceptions=DateTimeException.class) + @Test public void test_print_emptyCalendrical() throws Exception { - getFormatter("+HH:MM:ss", "Z").formatTo(EMPTY_DTA, buf); + Assertions.assertThrows(DateTimeException.class, () -> getFormatter("+HH:MM:ss", "Z").formatTo(EMPTY_DTA, buf)); } + @Test public void test_print_emptyAppendable() throws Exception { getFormatter("+HH:MM:ss", "Z").formatTo(OFFSET_0130, buf); - assertEquals(buf.toString(), "+01:30"); + assertEquals("+01:30", buf.toString()); } } diff --git a/test/jdk/java/time/test/java/time/format/TestZoneTextPrinterParser.java b/test/jdk/java/time/test/java/time/format/TestZoneTextPrinterParser.java index 20861f151e0..abe3cd6b154 100644 --- a/test/jdk/java/time/test/java/time/format/TestZoneTextPrinterParser.java +++ b/test/jdk/java/time/test/java/time/format/TestZoneTextPrinterParser.java @@ -23,8 +23,8 @@ package test.java.time.format; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.text.DateFormatSymbols; import java.time.ZoneId; @@ -46,8 +46,10 @@ import java.util.Set; import java.util.TimeZone; import jdk.test.lib.RandomFactory; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /* * @test @@ -59,7 +61,7 @@ import org.testng.annotations.Test; /** * Test ZoneTextPrinterParser */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestZoneTextPrinterParser extends AbstractTestPrinterParser { private static final Locale[] SAMPLE_LOCALES = { @@ -73,6 +75,7 @@ public class TestZoneTextPrinterParser extends AbstractTestPrinterParser { .withDecimalStyle(DecimalStyle.of(locale)); } + @Test public void test_printText() { Random r = RandomFactory.getRandom(); int N = 8; @@ -123,9 +126,10 @@ public class TestZoneTextPrinterParser extends AbstractTestPrinterParser { System.out.printf("[%-5s, %5s] :[%s]%n", locale.toString(), style.toString(),result); System.out.printf(" %5s, %5s :[%s] %s%n", "", "", expected, zone); } - assertEquals(result, expected); + assertEquals(expected, result); } + @Test public void test_ParseText() { Set zids = ZoneRulesProvider.getAvailableZoneIds(); for (Locale locale : SAMPLE_LOCALES) { @@ -153,7 +157,6 @@ public class TestZoneTextPrinterParser extends AbstractTestPrinterParser { private static Set none = new HashSet<>(); - @DataProvider(name="preferredZones") Object[][] data_preferredZones() { return new Object[][] { {"America/New_York", "Eastern Standard Time", none, Locale.ENGLISH, TextStyle.FULL}, @@ -178,7 +181,8 @@ public class TestZoneTextPrinterParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="preferredZones") + @ParameterizedTest + @MethodSource("data_preferredZones") public void test_ParseText(String expected, String text, Set preferred, Locale locale, TextStyle style) { DateTimeFormatter fmt = new DateTimeFormatterBuilder().appendZoneText(style, preferred) .toFormatter(locale) @@ -191,7 +195,7 @@ public class TestZoneTextPrinterParser extends AbstractTestPrinterParser { style == TextStyle.FULL ? " full" :"short", text, ret, expected); - assertEquals(ret, expected); + assertEquals(expected, ret); } @@ -246,7 +250,6 @@ public class TestZoneTextPrinterParser extends AbstractTestPrinterParser { .withDecimalStyle(DecimalStyle.of(locale)); } - @DataProvider(name="roundTripAtOverlap") Object[][] data_roundTripAtOverlap() { return new Object[][] { {"yyyy-MM-dd HH:mm:ss.SSS z", "2021-10-31 02:30:00.000 CET"}, @@ -265,10 +268,11 @@ public class TestZoneTextPrinterParser extends AbstractTestPrinterParser { }; } - @Test(dataProvider="roundTripAtOverlap") + @ParameterizedTest + @MethodSource("data_roundTripAtOverlap") public void test_roundTripAtOverlap(String pattern, String input) { var dtf = DateTimeFormatter.ofPattern(pattern, Locale.US); - assertEquals(dtf.format(ZonedDateTime.parse(input, dtf)), input); + assertEquals(input, dtf.format(ZonedDateTime.parse(input, dtf))); var lc = input.toLowerCase(Locale.ROOT); try { ZonedDateTime.parse(lc, dtf); @@ -276,7 +280,7 @@ public class TestZoneTextPrinterParser extends AbstractTestPrinterParser { } catch (DateTimeParseException ignore) {} dtf = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern(pattern).toFormatter(Locale.US); - assertEquals(dtf.format(ZonedDateTime.parse(input, dtf)), input); - assertEquals(dtf.format(ZonedDateTime.parse(lc, dtf)), input); + assertEquals(input, dtf.format(ZonedDateTime.parse(input, dtf))); + assertEquals(input, dtf.format(ZonedDateTime.parse(lc, dtf))); } } diff --git a/test/jdk/java/time/test/java/time/temporal/TestChronoField.java b/test/jdk/java/time/test/java/time/temporal/TestChronoField.java index a353a6b247b..716f586ff79 100644 --- a/test/jdk/java/time/test/java/time/temporal/TestChronoField.java +++ b/test/jdk/java/time/test/java/time/temporal/TestChronoField.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -54,8 +54,7 @@ */ package test.java.time.temporal; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.temporal.ChronoField; import java.time.temporal.IsoFields; @@ -64,18 +63,18 @@ import java.time.temporal.WeekFields; import java.util.HashMap; import java.util.Locale; import java.util.Map; -import java.util.ResourceBundle; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestChronoField { Map fieldMap; - @BeforeClass + @BeforeAll public void initClass() { fieldMap = new HashMap<>(); fieldMap.put(ChronoField.ERA, "era"); @@ -91,7 +90,6 @@ public class TestChronoField { fieldMap.put(ChronoField.OFFSET_SECONDS, "zone"); } - @DataProvider(name = "localeList") Locale[] data_localeList() { return new Locale[] { Locale.US, @@ -101,7 +99,6 @@ public class TestChronoField { }; } //----------------------------------------------------------------------- - @DataProvider(name = "localeDisplayNames") Object[][] data_localeDisplayNames() { return new Object[][] { {ChronoField.ERA}, @@ -121,12 +118,14 @@ public class TestChronoField { public void test_IsoFields_week_based_year() { Locale locale = Locale.US; String name = IsoFields.WEEK_OF_WEEK_BASED_YEAR.getDisplayName(locale); - assertEquals(name, "week"); + assertEquals("week", name); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_nullIsoFields_week_based_year() { - String name = IsoFields.WEEK_OF_WEEK_BASED_YEAR.getDisplayName((Locale)null); + Assertions.assertThrows(NullPointerException.class, () -> { + String name = IsoFields.WEEK_OF_WEEK_BASED_YEAR.getDisplayName((Locale)null); + }); } @Test @@ -134,24 +133,28 @@ public class TestChronoField { Locale locale = Locale.US; TemporalField weekOfYearField = WeekFields.SUNDAY_START.weekOfYear(); String name = weekOfYearField.getDisplayName(locale); - assertEquals(name, "week"); + assertEquals("week", name); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_nullWeekFields_week_based_year() { - TemporalField weekOfYearField = WeekFields.SUNDAY_START.weekOfYear(); - String name = weekOfYearField.getDisplayName((Locale)null); + Assertions.assertThrows(NullPointerException.class, () -> { + TemporalField weekOfYearField = WeekFields.SUNDAY_START.weekOfYear(); + String name = weekOfYearField.getDisplayName((Locale)null); + }); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_nullLocaleChronoFieldDisplayName() { - ChronoField.YEAR.getDisplayName((Locale)null); + Assertions.assertThrows(NullPointerException.class, () -> ChronoField.YEAR.getDisplayName((Locale)null)); } - @Test(expectedExceptions=NullPointerException.class) + @Test public void test_nullLocaleTemporalFieldDisplayName() { - // Test the default method in TemporalField using the - // IsoFields.DAY_OF_QUARTER which does not override getDisplayName - IsoFields.DAY_OF_QUARTER.getDisplayName((Locale)null); + Assertions.assertThrows(NullPointerException.class, () -> { + // Test the default method in TemporalField using the + // IsoFields.DAY_OF_QUARTER which does not override getDisplayName + IsoFields.DAY_OF_QUARTER.getDisplayName((Locale)null); + }); } } diff --git a/test/jdk/java/time/test/java/time/temporal/TestChronoUnit.java b/test/jdk/java/time/test/java/time/temporal/TestChronoUnit.java index 95e5f6503ed..11ebcfd13bd 100644 --- a/test/jdk/java/time/test/java/time/temporal/TestChronoUnit.java +++ b/test/jdk/java/time/test/java/time/temporal/TestChronoUnit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -65,23 +65,24 @@ import static java.time.temporal.ChronoUnit.DAYS; import static java.time.temporal.ChronoUnit.MONTHS; import static java.time.temporal.ChronoUnit.WEEKS; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDate; import java.time.Month; import java.time.ZoneOffset; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestChronoUnit { //----------------------------------------------------------------------- - @DataProvider(name = "yearsBetween") Object[][] data_yearsBetween() { return new Object[][] { {date(1939, SEPTEMBER, 2), date(1939, SEPTEMBER, 1), 0}, @@ -102,47 +103,52 @@ public class TestChronoUnit { }; } - @Test(dataProvider = "yearsBetween") + @ParameterizedTest + @MethodSource("data_yearsBetween") public void test_yearsBetween(LocalDate start, LocalDate end, long expected) { - assertEquals(YEARS.between(start, end), expected); + assertEquals(expected, YEARS.between(start, end)); } - @Test(dataProvider = "yearsBetween") + @ParameterizedTest + @MethodSource("data_yearsBetween") public void test_yearsBetweenReversed(LocalDate start, LocalDate end, long expected) { - assertEquals(YEARS.between(end, start), -expected); + assertEquals(-expected, YEARS.between(end, start)); } - @Test(dataProvider = "yearsBetween") + @ParameterizedTest + @MethodSource("data_yearsBetween") public void test_yearsBetween_LocalDateTimeSameTime(LocalDate start, LocalDate end, long expected) { - assertEquals(YEARS.between(start.atTime(12, 30), end.atTime(12, 30)), expected); + assertEquals(expected, YEARS.between(start.atTime(12, 30), end.atTime(12, 30))); } - @Test(dataProvider = "yearsBetween") + @ParameterizedTest + @MethodSource("data_yearsBetween") public void test_yearsBetween_LocalDateTimeLaterTime(LocalDate start, LocalDate end, long expected) { if (expected >= 0) { - assertEquals(YEARS.between(start.atTime(12, 30), end.atTime(12, 31)), expected); + assertEquals(expected, YEARS.between(start.atTime(12, 30), end.atTime(12, 31))); } else { - assertEquals(YEARS.between(start.atTime(12, 30), end.atTime(12, 29)), expected); + assertEquals(expected, YEARS.between(start.atTime(12, 30), end.atTime(12, 29))); } } - @Test(dataProvider = "yearsBetween") + @ParameterizedTest + @MethodSource("data_yearsBetween") public void test_yearsBetween_ZonedDateSameOffset(LocalDate start, LocalDate end, long expected) { - assertEquals(YEARS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(2))), expected); + assertEquals(expected, YEARS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(2)))); } - @Test(dataProvider = "yearsBetween") + @ParameterizedTest + @MethodSource("data_yearsBetween") public void test_yearsBetween_ZonedDateLaterOffset(LocalDate start, LocalDate end, long expected) { // +01:00 is later than +02:00 if (expected >= 0) { - assertEquals(YEARS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(1))), expected); + assertEquals(expected, YEARS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(1)))); } else { - assertEquals(YEARS.between(start.atStartOfDay(ZoneOffset.ofHours(1)), end.atStartOfDay(ZoneOffset.ofHours(2))), expected); + assertEquals(expected, YEARS.between(start.atStartOfDay(ZoneOffset.ofHours(1)), end.atStartOfDay(ZoneOffset.ofHours(2)))); } } //----------------------------------------------------------------------- - @DataProvider(name = "monthsBetween") Object[][] data_monthsBetween() { return new Object[][] { {date(2012, JULY, 2), date(2012, JULY, 1), 0}, @@ -175,47 +181,52 @@ public class TestChronoUnit { }; } - @Test(dataProvider = "monthsBetween") + @ParameterizedTest + @MethodSource("data_monthsBetween") public void test_monthsBetween(LocalDate start, LocalDate end, long expected) { - assertEquals(MONTHS.between(start, end), expected); + assertEquals(expected, MONTHS.between(start, end)); } - @Test(dataProvider = "monthsBetween") + @ParameterizedTest + @MethodSource("data_monthsBetween") public void test_monthsBetweenReversed(LocalDate start, LocalDate end, long expected) { - assertEquals(MONTHS.between(end, start), -expected); + assertEquals(-expected, MONTHS.between(end, start)); } - @Test(dataProvider = "monthsBetween") + @ParameterizedTest + @MethodSource("data_monthsBetween") public void test_monthsBetween_LocalDateTimeSameTime(LocalDate start, LocalDate end, long expected) { - assertEquals(MONTHS.between(start.atTime(12, 30), end.atTime(12, 30)), expected); + assertEquals(expected, MONTHS.between(start.atTime(12, 30), end.atTime(12, 30))); } - @Test(dataProvider = "monthsBetween") + @ParameterizedTest + @MethodSource("data_monthsBetween") public void test_monthsBetween_LocalDateTimeLaterTime(LocalDate start, LocalDate end, long expected) { if (expected >= 0) { - assertEquals(MONTHS.between(start.atTime(12, 30), end.atTime(12, 31)), expected); + assertEquals(expected, MONTHS.between(start.atTime(12, 30), end.atTime(12, 31))); } else { - assertEquals(MONTHS.between(start.atTime(12, 30), end.atTime(12, 29)), expected); + assertEquals(expected, MONTHS.between(start.atTime(12, 30), end.atTime(12, 29))); } } - @Test(dataProvider = "monthsBetween") + @ParameterizedTest + @MethodSource("data_monthsBetween") public void test_monthsBetween_ZonedDateSameOffset(LocalDate start, LocalDate end, long expected) { - assertEquals(MONTHS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(2))), expected); + assertEquals(expected, MONTHS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(2)))); } - @Test(dataProvider = "monthsBetween") + @ParameterizedTest + @MethodSource("data_monthsBetween") public void test_monthsBetween_ZonedDateLaterOffset(LocalDate start, LocalDate end, long expected) { // +01:00 is later than +02:00 if (expected >= 0) { - assertEquals(MONTHS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(1))), expected); + assertEquals(expected, MONTHS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(1)))); } else { - assertEquals(MONTHS.between(start.atStartOfDay(ZoneOffset.ofHours(1)), end.atStartOfDay(ZoneOffset.ofHours(2))), expected); + assertEquals(expected, MONTHS.between(start.atStartOfDay(ZoneOffset.ofHours(1)), end.atStartOfDay(ZoneOffset.ofHours(2)))); } } //----------------------------------------------------------------------- - @DataProvider(name = "weeksBetween") Object[][] data_weeksBetween() { return new Object[][] { {date(2012, JULY, 2), date(2012, JUNE, 25), -1}, @@ -242,18 +253,19 @@ public class TestChronoUnit { }; } - @Test(dataProvider = "weeksBetween") + @ParameterizedTest + @MethodSource("data_weeksBetween") public void test_weeksBetween(LocalDate start, LocalDate end, long expected) { - assertEquals(WEEKS.between(start, end), expected); + assertEquals(expected, WEEKS.between(start, end)); } - @Test(dataProvider = "weeksBetween") + @ParameterizedTest + @MethodSource("data_weeksBetween") public void test_weeksBetweenReversed(LocalDate start, LocalDate end, long expected) { - assertEquals(WEEKS.between(end, start), -expected); + assertEquals(-expected, WEEKS.between(end, start)); } //----------------------------------------------------------------------- - @DataProvider(name = "daysBetween") Object[][] data_daysBetween() { return new Object[][] { {date(2012, JULY, 2), date(2012, JULY, 1), -1}, @@ -285,42 +297,48 @@ public class TestChronoUnit { }; } - @Test(dataProvider = "daysBetween") + @ParameterizedTest + @MethodSource("data_daysBetween") public void test_daysBetween(LocalDate start, LocalDate end, long expected) { - assertEquals(DAYS.between(start, end), expected); + assertEquals(expected, DAYS.between(start, end)); } - @Test(dataProvider = "daysBetween") + @ParameterizedTest + @MethodSource("data_daysBetween") public void test_daysBetweenReversed(LocalDate start, LocalDate end, long expected) { - assertEquals(DAYS.between(end, start), -expected); + assertEquals(-expected, DAYS.between(end, start)); } - @Test(dataProvider = "daysBetween") + @ParameterizedTest + @MethodSource("data_daysBetween") public void test_daysBetween_LocalDateTimeSameTime(LocalDate start, LocalDate end, long expected) { - assertEquals(DAYS.between(start.atTime(12, 30), end.atTime(12, 30)), expected); + assertEquals(expected, DAYS.between(start.atTime(12, 30), end.atTime(12, 30))); } - @Test(dataProvider = "daysBetween") + @ParameterizedTest + @MethodSource("data_daysBetween") public void test_daysBetween_LocalDateTimeLaterTime(LocalDate start, LocalDate end, long expected) { if (expected >= 0) { - assertEquals(DAYS.between(start.atTime(12, 30), end.atTime(12, 31)), expected); + assertEquals(expected, DAYS.between(start.atTime(12, 30), end.atTime(12, 31))); } else { - assertEquals(DAYS.between(start.atTime(12, 30), end.atTime(12, 29)), expected); + assertEquals(expected, DAYS.between(start.atTime(12, 30), end.atTime(12, 29))); } } - @Test(dataProvider = "daysBetween") + @ParameterizedTest + @MethodSource("data_daysBetween") public void test_daysBetween_ZonedDateSameOffset(LocalDate start, LocalDate end, long expected) { - assertEquals(DAYS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(2))), expected); + assertEquals(expected, DAYS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(2)))); } - @Test(dataProvider = "daysBetween") + @ParameterizedTest + @MethodSource("data_daysBetween") public void test_daysBetween_ZonedDateLaterOffset(LocalDate start, LocalDate end, long expected) { // +01:00 is later than +02:00 if (expected >= 0) { - assertEquals(DAYS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(1))), expected); + assertEquals(expected, DAYS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(1)))); } else { - assertEquals(DAYS.between(start.atStartOfDay(ZoneOffset.ofHours(1)), end.atStartOfDay(ZoneOffset.ofHours(2))), expected); + assertEquals(expected, DAYS.between(start.atStartOfDay(ZoneOffset.ofHours(1)), end.atStartOfDay(ZoneOffset.ofHours(2)))); } } diff --git a/test/jdk/java/time/test/java/time/temporal/TestDateTimeBuilderCombinations.java b/test/jdk/java/time/test/java/time/temporal/TestDateTimeBuilderCombinations.java index ffa9fc3c342..8a81da27458 100644 --- a/test/jdk/java/time/test/java/time/temporal/TestDateTimeBuilderCombinations.java +++ b/test/jdk/java/time/test/java/time/temporal/TestDateTimeBuilderCombinations.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -70,8 +70,9 @@ import static java.time.temporal.ChronoField.EPOCH_DAY; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.PROLEPTIC_MONTH; import static java.time.temporal.ChronoField.YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.time.DateTimeException; import java.time.LocalDate; @@ -80,15 +81,16 @@ import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalField; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestDateTimeBuilderCombinations { - @DataProvider(name = "combine") Object[][] data_combine() { return new Object[][] { {YEAR, 2012, MONTH_OF_YEAR, 6, DAY_OF_MONTH, 3, null, null, LocalDate.class, LocalDate.of(2012, 6, 3)}, @@ -101,7 +103,8 @@ public class TestDateTimeBuilderCombinations { }; } - @Test(dataProvider = "combine") + @ParameterizedTest + @MethodSource("data_combine") public void test_derive(final TemporalField field1, final Number value1, final TemporalField field2, final Number value2, final TemporalField field3, final Number value3, @@ -149,7 +152,7 @@ public class TestDateTimeBuilderCombinations { TemporalAccessor parsed = dtfb.toFormatter().parse(str); if (query == LocalDate.class) { if (expectedVal != null) { - assertEquals(parsed.query(LocalDate::from), expectedVal); + assertEquals(expectedVal, parsed.query(LocalDate::from)); } else { try { parsed.query(LocalDate::from); @@ -164,7 +167,6 @@ public class TestDateTimeBuilderCombinations { } //----------------------------------------------------------------------- - @DataProvider(name = "normalized") Object[][] data_normalized() { return new Object[][] { {YEAR, 2127, YEAR, 2127}, @@ -182,7 +184,8 @@ public class TestDateTimeBuilderCombinations { }; } - @Test(dataProvider = "normalized") + @ParameterizedTest + @MethodSource("data_normalized") public void test_normalized(final TemporalField field1, final Number value1, TemporalField expectedField, Number expectedVal) { // mock for testing that does not fully comply with TemporalAccessor contract TemporalAccessor test = new TemporalAccessor() { @@ -202,9 +205,9 @@ public class TestDateTimeBuilderCombinations { String str = value1.toString(); TemporalAccessor temporal = f.parse(str); if (expectedVal != null) { - assertEquals(temporal.getLong(expectedField), expectedVal.longValue()); + assertEquals(expectedVal.longValue(), temporal.getLong(expectedField)); } else { - assertEquals(temporal.isSupported(expectedField), false); + assertEquals(false, temporal.isSupported(expectedField)); } } diff --git a/test/jdk/java/time/test/java/time/temporal/TestDateTimeValueRange.java b/test/jdk/java/time/test/java/time/temporal/TestDateTimeValueRange.java index 570e6634a8a..e3e2f1758b9 100644 --- a/test/jdk/java/time/test/java/time/temporal/TestDateTimeValueRange.java +++ b/test/jdk/java/time/test/java/time/temporal/TestDateTimeValueRange.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,7 +59,7 @@ */ package test.java.time.temporal; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -69,15 +69,19 @@ import java.time.DateTimeException; import java.time.temporal.ChronoField; import java.time.temporal.ValueRange; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import test.java.time.AbstractTest; /** * Test. * @bug 8239520 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestDateTimeValueRange extends AbstractTest { //----------------------------------------------------------------------- @@ -91,63 +95,65 @@ public class TestDateTimeValueRange extends AbstractTest { //----------------------------------------------------------------------- // of(long,long) //----------------------------------------------------------------------- + @Test public void test_of_longlong() { ValueRange test = ValueRange.of(1, 12); - assertEquals(test.getMinimum(), 1); - assertEquals(test.getLargestMinimum(), 1); - assertEquals(test.getSmallestMaximum(), 12); - assertEquals(test.getMaximum(), 12); - assertEquals(test.isFixed(), true); - assertEquals(test.isIntValue(), true); + assertEquals(1, test.getMinimum()); + assertEquals(1, test.getLargestMinimum()); + assertEquals(12, test.getSmallestMaximum()); + assertEquals(12, test.getMaximum()); + assertEquals(true, test.isFixed()); + assertEquals(true, test.isIntValue()); } + @Test public void test_of_longlong_big() { ValueRange test = ValueRange.of(1, 123456789012345L); - assertEquals(test.getMinimum(), 1); - assertEquals(test.getLargestMinimum(), 1); - assertEquals(test.getSmallestMaximum(), 123456789012345L); - assertEquals(test.getMaximum(), 123456789012345L); - assertEquals(test.isFixed(), true); - assertEquals(test.isIntValue(), false); + assertEquals(1, test.getMinimum()); + assertEquals(1, test.getLargestMinimum()); + assertEquals(123456789012345L, test.getSmallestMaximum()); + assertEquals(123456789012345L, test.getMaximum()); + assertEquals(true, test.isFixed()); + assertEquals(false, test.isIntValue()); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_of_longlong_minGtMax() { - ValueRange.of(12, 1); + Assertions.assertThrows(IllegalArgumentException.class, () -> ValueRange.of(12, 1)); } //----------------------------------------------------------------------- // of(long,long,long) //----------------------------------------------------------------------- + @Test public void test_of_longlonglong() { ValueRange test = ValueRange.of(1, 28, 31); - assertEquals(test.getMinimum(), 1); - assertEquals(test.getLargestMinimum(), 1); - assertEquals(test.getSmallestMaximum(), 28); - assertEquals(test.getMaximum(), 31); - assertEquals(test.isFixed(), false); - assertEquals(test.isIntValue(), true); + assertEquals(1, test.getMinimum()); + assertEquals(1, test.getLargestMinimum()); + assertEquals(28, test.getSmallestMaximum()); + assertEquals(31, test.getMaximum()); + assertEquals(false, test.isFixed()); + assertEquals(true, test.isIntValue()); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_of_longlonglong_minGtMax() { - ValueRange.of(12, 1, 2); + Assertions.assertThrows(IllegalArgumentException.class, () -> ValueRange.of(12, 1, 2)); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_of_longlonglong_smallestmaxminGtMax() { - ValueRange.of(1, 31, 28); + Assertions.assertThrows(IllegalArgumentException.class, () -> ValueRange.of(1, 31, 28)); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void test_of_longlonglong_minGtSmallestMax() { - ValueRange.of(5, 2, 10); + Assertions.assertThrows(IllegalArgumentException.class, () -> ValueRange.of(5, 2, 10)); } //----------------------------------------------------------------------- // of(long,long,long,long) //----------------------------------------------------------------------- - @DataProvider(name="valid") Object[][] data_valid() { return new Object[][] { {1, 1, 1, 1}, @@ -162,18 +168,18 @@ public class TestDateTimeValueRange extends AbstractTest { }; } - @Test(dataProvider="valid") + @ParameterizedTest + @MethodSource("data_valid") public void test_of_longlonglonglong(long sMin, long lMin, long sMax, long lMax) { ValueRange test = ValueRange.of(sMin, lMin, sMax, lMax); - assertEquals(test.getMinimum(), sMin); - assertEquals(test.getLargestMinimum(), lMin); - assertEquals(test.getSmallestMaximum(), sMax); - assertEquals(test.getMaximum(), lMax); - assertEquals(test.isFixed(), sMin == lMin && sMax == lMax); - assertEquals(test.isIntValue(), true); + assertEquals(sMin, test.getMinimum()); + assertEquals(lMin, test.getLargestMinimum()); + assertEquals(sMax, test.getSmallestMaximum()); + assertEquals(lMax, test.getMaximum()); + assertEquals(sMin == lMin && sMax == lMax, test.isFixed()); + assertEquals(true, test.isIntValue()); } - @DataProvider(name="invalid") Object[][] data_invalid() { return new Object[][] { {1, 2, 31, 28}, @@ -192,118 +198,138 @@ public class TestDateTimeValueRange extends AbstractTest { }; } - @Test(dataProvider="invalid", expectedExceptions=IllegalArgumentException.class) + @ParameterizedTest + @MethodSource("data_invalid") public void test_of_longlonglonglong_invalid(long sMin, long lMin, long sMax, long lMax) { - ValueRange.of(sMin, lMin, sMax, lMax); + Assertions.assertThrows(IllegalArgumentException.class, () -> ValueRange.of(sMin, lMin, sMax, lMax)); } //----------------------------------------------------------------------- // isValidValue(long) //----------------------------------------------------------------------- + @Test public void test_isValidValue_long() { ValueRange test = ValueRange.of(1, 28, 31); - assertEquals(test.isValidValue(0), false); - assertEquals(test.isValidValue(1), true); - assertEquals(test.isValidValue(2), true); - assertEquals(test.isValidValue(30), true); - assertEquals(test.isValidValue(31), true); - assertEquals(test.isValidValue(32), false); + assertEquals(false, test.isValidValue(0)); + assertEquals(true, test.isValidValue(1)); + assertEquals(true, test.isValidValue(2)); + assertEquals(true, test.isValidValue(30)); + assertEquals(true, test.isValidValue(31)); + assertEquals(false, test.isValidValue(32)); } //----------------------------------------------------------------------- // isValidIntValue(long) //----------------------------------------------------------------------- + @Test public void test_isValidValue_long_int() { ValueRange test = ValueRange.of(1, 28, 31); - assertEquals(test.isValidValue(0), false); - assertEquals(test.isValidValue(1), true); - assertEquals(test.isValidValue(31), true); - assertEquals(test.isValidValue(32), false); + assertEquals(false, test.isValidValue(0)); + assertEquals(true, test.isValidValue(1)); + assertEquals(true, test.isValidValue(31)); + assertEquals(false, test.isValidValue(32)); } + @Test public void test_isValidValue_long_long() { ValueRange test = ValueRange.of(1, 28, Integer.MAX_VALUE + 1L); - assertEquals(test.isValidIntValue(0), false); - assertEquals(test.isValidIntValue(1), false); - assertEquals(test.isValidIntValue(31), false); - assertEquals(test.isValidIntValue(32), false); + assertEquals(false, test.isValidIntValue(0)); + assertEquals(false, test.isValidIntValue(1)); + assertEquals(false, test.isValidIntValue(31)); + assertEquals(false, test.isValidIntValue(32)); } //----------------------------------------------------------------------- // checkValidValue //----------------------------------------------------------------------- - @Test(dataProvider="valid") + @ParameterizedTest + @MethodSource("data_valid") public void test_of_checkValidValue(long sMin, long lMin, long sMax, long lMax) { ValueRange test = ValueRange.of(sMin, lMin, sMax, lMax); - assertEquals(test.checkValidIntValue(sMin, null), sMin); - assertEquals(test.checkValidIntValue(lMin, null), lMin); - assertEquals(test.checkValidIntValue(sMax, null), sMax); - assertEquals(test.checkValidIntValue(lMax, null), lMax); + assertEquals(sMin, test.checkValidIntValue(sMin, null)); + assertEquals(lMin, test.checkValidIntValue(lMin, null)); + assertEquals(sMax, test.checkValidIntValue(sMax, null)); + assertEquals(lMax, test.checkValidIntValue(lMax, null)); } - @Test(dataProvider="valid", expectedExceptions = DateTimeException.class) + @ParameterizedTest + @MethodSource("data_valid") public void test_of_checkValidValueMinException(long sMin, long lMin, long sMax, long lMax) { - ValueRange test = ValueRange.of(sMin, lMin, sMax, lMax); - test.checkValidIntValue(sMin-1, null); + Assertions.assertThrows(DateTimeException.class, () -> { + ValueRange test = ValueRange.of(sMin, lMin, sMax, lMax); + test.checkValidIntValue(sMin-1, null); + }); } - @Test(dataProvider="valid", expectedExceptions = DateTimeException.class) + @ParameterizedTest + @MethodSource("data_valid") public void test_of_checkValidValueMaxException(long sMin, long lMin, long sMax, long lMax) { - ValueRange test = ValueRange.of(sMin, lMin, sMax, lMax); - test.checkValidIntValue(lMax+1, null); + Assertions.assertThrows(DateTimeException.class, () -> { + ValueRange test = ValueRange.of(sMin, lMin, sMax, lMax); + test.checkValidIntValue(lMax+1, null); + }); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_checkValidValueUnsupported_long_long() { - ValueRange test = ValueRange.of(1, 28, Integer.MAX_VALUE + 1L); - test.checkValidIntValue(0, (ChronoField)null); + Assertions.assertThrows(DateTimeException.class, () -> { + ValueRange test = ValueRange.of(1, 28, Integer.MAX_VALUE + 1L); + test.checkValidIntValue(0, (ChronoField)null); + }); } - @Test(expectedExceptions = DateTimeException.class) + @Test public void test_checkValidValueInvalid_long_long() { - ValueRange test = ValueRange.of(1, 28, Integer.MAX_VALUE + 1L); - test.checkValidIntValue(Integer.MAX_VALUE + 2L, (ChronoField)null); + Assertions.assertThrows(DateTimeException.class, () -> { + ValueRange test = ValueRange.of(1, 28, Integer.MAX_VALUE + 1L); + test.checkValidIntValue(Integer.MAX_VALUE + 2L, (ChronoField)null); + }); } //----------------------------------------------------------------------- // equals() / hashCode() //----------------------------------------------------------------------- + @Test public void test_equals1() { ValueRange a = ValueRange.of(1, 2, 3, 4); ValueRange b = ValueRange.of(1, 2, 3, 4); - assertEquals(a.equals(a), true); - assertEquals(a.equals(b), true); - assertEquals(b.equals(a), true); - assertEquals(b.equals(b), true); - assertEquals(a.hashCode() == b.hashCode(), true); + assertEquals(true, a.equals(a)); + assertEquals(true, a.equals(b)); + assertEquals(true, b.equals(a)); + assertEquals(true, b.equals(b)); + assertEquals(true, a.hashCode() == b.hashCode()); } + @Test public void test_equals2() { ValueRange a = ValueRange.of(1, 2, 3, 4); - assertEquals(a.equals(ValueRange.of(0, 2, 3, 4)), false); - assertEquals(a.equals(ValueRange.of(1, 3, 3, 4)), false); - assertEquals(a.equals(ValueRange.of(1, 2, 4, 4)), false); - assertEquals(a.equals(ValueRange.of(1, 2, 3, 5)), false); + assertEquals(false, a.equals(ValueRange.of(0, 2, 3, 4))); + assertEquals(false, a.equals(ValueRange.of(1, 3, 3, 4))); + assertEquals(false, a.equals(ValueRange.of(1, 2, 4, 4))); + assertEquals(false, a.equals(ValueRange.of(1, 2, 3, 5))); } + @Test public void test_equals_otherType() { ValueRange a = ValueRange.of(1, 12); - assertEquals(a.equals("Rubbish"), false); + assertEquals(false, a.equals("Rubbish")); } + @Test public void test_equals_null() { ValueRange a = ValueRange.of(1, 12); - assertEquals(a.equals(null), false); + assertEquals(false, a.equals(null)); } //----------------------------------------------------------------------- // toString() //----------------------------------------------------------------------- + @Test public void test_toString() { - assertEquals(ValueRange.of(1, 1, 4, 4).toString(), "1 - 4"); - assertEquals(ValueRange.of(1, 1, 3, 4).toString(), "1 - 3/4"); - assertEquals(ValueRange.of(1, 2, 3, 4).toString(), "1/2 - 3/4"); - assertEquals(ValueRange.of(1, 2, 4, 4).toString(), "1/2 - 4"); + assertEquals("1 - 4", ValueRange.of(1, 1, 4, 4).toString()); + assertEquals("1 - 3/4", ValueRange.of(1, 1, 3, 4).toString()); + assertEquals("1/2 - 3/4", ValueRange.of(1, 2, 3, 4).toString()); + assertEquals("1/2 - 4", ValueRange.of(1, 2, 4, 4).toString()); } } diff --git a/test/jdk/java/time/test/java/time/temporal/TestIsoFields.java b/test/jdk/java/time/test/java/time/temporal/TestIsoFields.java index 53cd721c0e5..8a74582d976 100644 --- a/test/jdk/java/time/test/java/time/temporal/TestIsoFields.java +++ b/test/jdk/java/time/test/java/time/temporal/TestIsoFields.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2025, 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,9 @@ import static java.time.temporal.IsoFields.DAY_OF_QUARTER; import static java.time.temporal.IsoFields.QUARTER_OF_YEAR; import static java.time.temporal.IsoFields.WEEK_BASED_YEAR; import static java.time.temporal.IsoFields.WEEK_OF_WEEK_BASED_YEAR; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.LocalDate; import java.time.chrono.ChronoLocalDate; @@ -38,15 +39,16 @@ import java.time.temporal.TemporalField; import java.time.temporal.ValueRange; import java.util.List; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests fields in IsoFields class are supported in Japanese/Minguo/ThaiBuddhist * date classes * @bug 8279185 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestIsoFields { private static final LocalDate ld = LocalDate.of(2022, 2, 25); private static final ChronoLocalDate J_DATE = JapaneseDate.from(ld); @@ -54,7 +56,6 @@ public class TestIsoFields { private static final ChronoLocalDate TB_DATE = ThaiBuddhistDate.from(ld); private static final List CLDATES = List.of(J_DATE, M_DATE, TB_DATE); - @DataProvider(name = "isSupported") Object[][] data_isSupported() { return new Object[][]{ {DAY_OF_QUARTER}, @@ -64,7 +65,6 @@ public class TestIsoFields { }; } - @DataProvider(name = "range") Object[][] data_range() { return new Object[][]{ {J_DATE, DAY_OF_QUARTER, ValueRange.of(1, 90)}, @@ -82,7 +82,6 @@ public class TestIsoFields { }; } - @DataProvider(name = "with_getLong") Object[][] data_with_getLong() { return new Object[][]{ {DAY_OF_QUARTER, 45}, @@ -92,24 +91,27 @@ public class TestIsoFields { }; } - @Test(dataProvider = "isSupported") + @ParameterizedTest + @MethodSource("data_isSupported") public void test_isSupported(TemporalField f) { CLDATES.forEach(d -> assertTrue(d.isSupported(f))); } - @Test(dataProvider = "range") + @ParameterizedTest + @MethodSource("data_range") public void test_range(ChronoLocalDate cld, TemporalField f, ValueRange r) { - assertEquals(cld.range(f), r); + assertEquals(r, cld.range(f)); } - @Test(dataProvider = "with_getLong") + @ParameterizedTest + @MethodSource("data_with_getLong") public void test_with_getLong(TemporalField f, long val) { CLDATES.forEach(d -> { var min = d.range(f).getMinimum(); var max = d.range(f).getMaximum(); - assertEquals(d.with(f, min).getLong(f), min); - assertEquals(d.with(f, max).getLong(f), max); - assertEquals(d.with(f, val).getLong(f), val); + assertEquals(min, d.with(f, min).getLong(f)); + assertEquals(max, d.with(f, max).getLong(f)); + assertEquals(val, d.with(f, val).getLong(f)); }); } } diff --git a/test/jdk/java/time/test/java/time/temporal/TestIsoWeekFields.java b/test/jdk/java/time/test/java/time/temporal/TestIsoWeekFields.java index 4c40e7278ed..80caa3ffcc1 100644 --- a/test/jdk/java/time/test/java/time/temporal/TestIsoWeekFields.java +++ b/test/jdk/java/time/test/java/time/temporal/TestIsoWeekFields.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ package test.java.time.temporal; import static java.time.temporal.ChronoField.DAY_OF_WEEK; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.DayOfWeek; import java.time.LocalDate; @@ -40,16 +41,17 @@ import java.time.temporal.TemporalField; import java.time.temporal.ValueRange; import java.time.temporal.WeekFields; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Test. */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestIsoWeekFields { - @DataProvider(name = "fields") Object[][] data_Fields() { return new Object[][] { {IsoFields.WEEK_OF_WEEK_BASED_YEAR, IsoFields.WEEK_BASED_YEAR}, @@ -60,92 +62,101 @@ public class TestIsoWeekFields { //----------------------------------------------------------------------- // WEEK_OF_WEEK_BASED_YEAR //----------------------------------------------------------------------- - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_WOWBY_basics(TemporalField weekField, TemporalField yearField) { - assertEquals(weekField.isDateBased(), true); - assertEquals(weekField.isTimeBased(), false); - assertEquals(weekField.getBaseUnit(), ChronoUnit.WEEKS); - assertEquals(weekField.getRangeUnit(), IsoFields.WEEK_BASED_YEARS); + assertEquals(true, weekField.isDateBased()); + assertEquals(false, weekField.isTimeBased()); + assertEquals(ChronoUnit.WEEKS, weekField.getBaseUnit()); + assertEquals(IsoFields.WEEK_BASED_YEARS, weekField.getRangeUnit()); } - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_WOWBY_isSupportedBy(TemporalField weekField, TemporalField yearField) { - assertEquals(weekField.isSupportedBy(LocalTime.NOON), false); - assertEquals(weekField.isSupportedBy(MonthDay.of(2, 1)), false); - assertEquals(weekField.isSupportedBy(LocalDate.MIN), true); - assertEquals(weekField.isSupportedBy(OffsetDateTime.MAX), true); - assertEquals(weekField.isSupportedBy(ThaiBuddhistDate.now()), true); + assertEquals(false, weekField.isSupportedBy(LocalTime.NOON)); + assertEquals(false, weekField.isSupportedBy(MonthDay.of(2, 1))); + assertEquals(true, weekField.isSupportedBy(LocalDate.MIN)); + assertEquals(true, weekField.isSupportedBy(OffsetDateTime.MAX)); + assertEquals(true, weekField.isSupportedBy(ThaiBuddhistDate.now())); } @Test public void test_WOWBY_isSupportedBy_fieldsDiffer() { - assertEquals(IsoFields.WEEK_OF_WEEK_BASED_YEAR.isSupportedBy(HijrahDate.now()), false); - assertEquals(WeekFields.ISO.weekOfWeekBasedYear().isSupportedBy(HijrahDate.now()), true); + assertEquals(false, IsoFields.WEEK_OF_WEEK_BASED_YEAR.isSupportedBy(HijrahDate.now())); + assertEquals(true, WeekFields.ISO.weekOfWeekBasedYear().isSupportedBy(HijrahDate.now())); } - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_WOWBY_range(TemporalField weekField, TemporalField yearField) { - assertEquals(weekField.range(), ValueRange.of(1, 52, 53)); + assertEquals(ValueRange.of(1, 52, 53), weekField.range()); } - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_WOWBY_rangeRefinedBy(TemporalField weekField, TemporalField yearField) { - assertEquals(weekField.rangeRefinedBy(LocalDate.of(2012, 12, 31)), ValueRange.of(1, 52)); - assertEquals(weekField.rangeRefinedBy(LocalDate.of(2013, 12, 29)), ValueRange.of(1, 52)); - assertEquals(weekField.rangeRefinedBy(LocalDate.of(2013, 12, 30)), ValueRange.of(1, 52)); - assertEquals(weekField.rangeRefinedBy(LocalDate.of(2014, 12, 28)), ValueRange.of(1, 52)); - assertEquals(weekField.rangeRefinedBy(LocalDate.of(2014, 12, 29)), ValueRange.of(1, 53)); - assertEquals(weekField.rangeRefinedBy(LocalDate.of(2016, 1, 3)), ValueRange.of(1, 53)); - assertEquals(weekField.rangeRefinedBy(LocalDate.of(2016, 1, 4)), ValueRange.of(1, 52)); + assertEquals(ValueRange.of(1, 52), weekField.rangeRefinedBy(LocalDate.of(2012, 12, 31))); + assertEquals(ValueRange.of(1, 52), weekField.rangeRefinedBy(LocalDate.of(2013, 12, 29))); + assertEquals(ValueRange.of(1, 52), weekField.rangeRefinedBy(LocalDate.of(2013, 12, 30))); + assertEquals(ValueRange.of(1, 52), weekField.rangeRefinedBy(LocalDate.of(2014, 12, 28))); + assertEquals(ValueRange.of(1, 53), weekField.rangeRefinedBy(LocalDate.of(2014, 12, 29))); + assertEquals(ValueRange.of(1, 53), weekField.rangeRefinedBy(LocalDate.of(2016, 1, 3))); + assertEquals(ValueRange.of(1, 52), weekField.rangeRefinedBy(LocalDate.of(2016, 1, 4))); } //----------------------------------------------------------------------- // WEEK_BASED_YEAR //----------------------------------------------------------------------- - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_WBY_basics(TemporalField weekField, TemporalField yearField) { - assertEquals(yearField.isDateBased(), true); - assertEquals(yearField.isTimeBased(), false); - assertEquals(yearField.getBaseUnit(), IsoFields.WEEK_BASED_YEARS); - assertEquals(yearField.getRangeUnit(), ChronoUnit.FOREVER); + assertEquals(true, yearField.isDateBased()); + assertEquals(false, yearField.isTimeBased()); + assertEquals(IsoFields.WEEK_BASED_YEARS, yearField.getBaseUnit()); + assertEquals(ChronoUnit.FOREVER, yearField.getRangeUnit()); } - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_WBY_isSupportedBy(TemporalField weekField, TemporalField yearField) { - assertEquals(yearField.isSupportedBy(LocalTime.NOON), false); - assertEquals(yearField.isSupportedBy(MonthDay.of(2, 1)), false); - assertEquals(yearField.isSupportedBy(LocalDate.MIN), true); - assertEquals(yearField.isSupportedBy(OffsetDateTime.MAX), true); - assertEquals(yearField.isSupportedBy(ThaiBuddhistDate.now()), true); + assertEquals(false, yearField.isSupportedBy(LocalTime.NOON)); + assertEquals(false, yearField.isSupportedBy(MonthDay.of(2, 1))); + assertEquals(true, yearField.isSupportedBy(LocalDate.MIN)); + assertEquals(true, yearField.isSupportedBy(OffsetDateTime.MAX)); + assertEquals(true, yearField.isSupportedBy(ThaiBuddhistDate.now())); } @Test public void test_WBY_isSupportedBy_ISO() { - assertEquals(IsoFields.WEEK_BASED_YEAR.isSupportedBy(HijrahDate.now()), false); + assertEquals(false, IsoFields.WEEK_BASED_YEAR.isSupportedBy(HijrahDate.now())); } @Test public void test_Unit_isSupportedBy_ISO() { - assertEquals(IsoFields.WEEK_BASED_YEARS.isSupportedBy(LocalDate.now()), true); - assertEquals(IsoFields.WEEK_BASED_YEARS.isSupportedBy(ThaiBuddhistDate.now()), true); - assertEquals(IsoFields.WEEK_BASED_YEARS.isSupportedBy(HijrahDate.now()), false); - assertEquals(IsoFields.QUARTER_YEARS.isSupportedBy(LocalDate.now()), true); - assertEquals(IsoFields.QUARTER_YEARS.isSupportedBy(ThaiBuddhistDate.now()), true); - assertEquals(IsoFields.QUARTER_YEARS.isSupportedBy(HijrahDate.now()), false); + assertEquals(true, IsoFields.WEEK_BASED_YEARS.isSupportedBy(LocalDate.now())); + assertEquals(true, IsoFields.WEEK_BASED_YEARS.isSupportedBy(ThaiBuddhistDate.now())); + assertEquals(false, IsoFields.WEEK_BASED_YEARS.isSupportedBy(HijrahDate.now())); + assertEquals(true, IsoFields.QUARTER_YEARS.isSupportedBy(LocalDate.now())); + assertEquals(true, IsoFields.QUARTER_YEARS.isSupportedBy(ThaiBuddhistDate.now())); + assertEquals(false, IsoFields.QUARTER_YEARS.isSupportedBy(HijrahDate.now())); } - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_WBY_range(TemporalField weekField, TemporalField yearField) { - assertEquals(yearField.range(), ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE)); + assertEquals(ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE), yearField.range()); } - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_WBY_rangeRefinedBy(TemporalField weekField, TemporalField yearField) { - assertEquals(yearField.rangeRefinedBy(LocalDate.of(2012, 12, 31)), ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE)); + assertEquals(ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE), yearField.rangeRefinedBy(LocalDate.of(2012, 12, 31))); } //----------------------------------------------------------------------- - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_getFrom(TemporalField weekField, TemporalField yearField) { // tests every day from 2011 to 2016 inclusive LocalDate date = LocalDate.of(2011, 1, 3); @@ -153,9 +164,9 @@ public class TestIsoWeekFields { int week = 1; int dow = 1; for (int i = 1; i <= ((52 + 52 + 52 + 52 + 53 + 52) * 7); i++) { - assertEquals(yearField.getFrom(date), wby); - assertEquals(weekField.getFrom(date), week); - assertEquals(DAY_OF_WEEK.getFrom(date), dow); + assertEquals(wby, yearField.getFrom(date)); + assertEquals(week, weekField.getFrom(date)); + assertEquals(dow, DAY_OF_WEEK.getFrom(date)); if (dow == 7) { dow = 1; week++; @@ -168,12 +179,13 @@ public class TestIsoWeekFields { } date = date.plusDays(1); } - assertEquals(yearField.getFrom(date), 2017); - assertEquals(weekField.getFrom(date), 1); - assertEquals(DAY_OF_WEEK.getFrom(date), 1); + assertEquals(2017, yearField.getFrom(date)); + assertEquals(1, weekField.getFrom(date)); + assertEquals(1, DAY_OF_WEEK.getFrom(date)); } - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_adjustInto_dow(TemporalField weekField, TemporalField yearField) { // tests every day from 2012 to 2016 inclusive LocalDate date = LocalDate.of(2012, 1, 2); @@ -183,9 +195,9 @@ public class TestIsoWeekFields { for (int i = 1; i <= ((52 + 52 + 52 + 53 + 52) * 7); i++) { for (int j = 1; j <= 7; j++) { LocalDate adjusted = DAY_OF_WEEK.adjustInto(date, j); - assertEquals(adjusted.get(DAY_OF_WEEK), j); - assertEquals(adjusted.get(weekField), week); - assertEquals(adjusted.get(yearField), wby); + assertEquals(j, adjusted.get(DAY_OF_WEEK)); + assertEquals(week, adjusted.get(weekField)); + assertEquals(wby, adjusted.get(yearField)); } if (dow == 7) { dow = 1; @@ -201,7 +213,8 @@ public class TestIsoWeekFields { } } - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_adjustInto_week(TemporalField weekField, TemporalField yearField) { // tests every day from 2012 to 2016 inclusive LocalDate date = LocalDate.of(2012, 1, 2); @@ -212,9 +225,9 @@ public class TestIsoWeekFields { int weeksInYear = (wby == 2015 ? 53 : 52); for (int j = 1; j <= weeksInYear; j++) { LocalDate adjusted = weekField.adjustInto(date, j); - assertEquals(adjusted.get(weekField), j); - assertEquals(adjusted.get(DAY_OF_WEEK), dow); - assertEquals(adjusted.get(yearField), wby); + assertEquals(j, adjusted.get(weekField)); + assertEquals(dow, adjusted.get(DAY_OF_WEEK)); + assertEquals(wby, adjusted.get(yearField)); } if (dow == 7) { dow = 1; @@ -230,7 +243,8 @@ public class TestIsoWeekFields { } } - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_adjustInto_wby(TemporalField weekField, TemporalField yearField) { // tests every day from 2012 to 2016 inclusive LocalDate date = LocalDate.of(2012, 1, 2); @@ -240,9 +254,9 @@ public class TestIsoWeekFields { for (int i = 1; i <= ((52 + 52 + 52 + 53 + 52) * 7); i++) { for (int j = 2004; j <= 2015; j++) { LocalDate adjusted = yearField.adjustInto(date, j); - assertEquals(adjusted.get(yearField), j); - assertEquals(adjusted.get(DAY_OF_WEEK), dow); - assertEquals(adjusted.get(weekField), (week == 53 && wbyLen(j) == 52 ? 52 : week), "" + date + " " + adjusted); + assertEquals(j, adjusted.get(yearField)); + assertEquals(dow, adjusted.get(DAY_OF_WEEK)); + assertEquals((week == 53 && wbyLen(j) == 52 ? 52 : week), adjusted.get(weekField), "" + date + " " + adjusted); } if (dow == 7) { dow = 1; @@ -258,7 +272,8 @@ public class TestIsoWeekFields { } } - @Test(dataProvider = "fields") + @ParameterizedTest + @MethodSource("data_Fields") public void test_addTo_weekBasedYears(TemporalField weekField, TemporalField yearField) { // tests every day from 2012 to 2016 inclusive LocalDate date = LocalDate.of(2012, 1, 2); @@ -268,9 +283,9 @@ public class TestIsoWeekFields { for (int i = 1; i <= ((52 + 52 + 52 + 53 + 52) * 7); i++) { for (int j = -5; j <= 5; j++) { LocalDate adjusted = IsoFields.WEEK_BASED_YEARS.addTo(date, j); - assertEquals(adjusted.get(yearField), wby + j); - assertEquals(adjusted.get(DAY_OF_WEEK), dow); - assertEquals(adjusted.get(weekField), (week == 53 && wbyLen(wby + j) == 52 ? 52 : week), "" + date + " " + adjusted); + assertEquals(wby + j, adjusted.get(yearField)); + assertEquals(dow, adjusted.get(DAY_OF_WEEK)); + assertEquals((week == 53 && wbyLen(wby + j) == 52 ? 52 : week), adjusted.get(weekField), "" + date + " " + adjusted); } if (dow == 7) { dow = 1; diff --git a/test/jdk/java/time/test/java/time/temporal/TestJulianFields.java b/test/jdk/java/time/test/java/time/temporal/TestJulianFields.java index 0d9d79e3158..5ed393d1b87 100644 --- a/test/jdk/java/time/test/java/time/temporal/TestJulianFields.java +++ b/test/jdk/java/time/test/java/time/temporal/TestJulianFields.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -59,16 +59,15 @@ */ package test.java.time.temporal; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.temporal.JulianFields; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test. */ -@Test public class TestJulianFields { //----------------------------------------------------------------------- @@ -76,9 +75,9 @@ public class TestJulianFields { //----------------------------------------------------------------------- @Test public void test_toString() { - assertEquals(JulianFields.JULIAN_DAY.toString(), "JulianDay"); - assertEquals(JulianFields.MODIFIED_JULIAN_DAY.toString(), "ModifiedJulianDay"); - assertEquals(JulianFields.RATA_DIE.toString(), "RataDie"); + assertEquals("JulianDay", JulianFields.JULIAN_DAY.toString()); + assertEquals("ModifiedJulianDay", JulianFields.MODIFIED_JULIAN_DAY.toString()); + assertEquals("RataDie", JulianFields.RATA_DIE.toString()); } } diff --git a/test/jdk/java/time/test/java/time/zone/TestFixedZoneRules.java b/test/jdk/java/time/test/java/time/zone/TestFixedZoneRules.java index d479134c26e..8f52372ab01 100644 --- a/test/jdk/java/time/test/java/time/zone/TestFixedZoneRules.java +++ b/test/jdk/java/time/test/java/time/zone/TestFixedZoneRules.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -61,19 +61,18 @@ package test.java.time.zone; import java.time.zone.ZoneRules; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; /** * Test ZoneRules for fixed offset time-zones. */ -@Test public class TestFixedZoneRules { private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); @@ -86,16 +85,16 @@ public class TestFixedZoneRules { @Test public void test_data_nullInput() { ZoneRules test = make(OFFSET_PONE); - assertEquals(test.getOffset((Instant) null), OFFSET_PONE); - assertEquals(test.getOffset((LocalDateTime) null), OFFSET_PONE); - assertEquals(test.getValidOffsets(null).size(), 1); - assertEquals(test.getValidOffsets(null).get(0), OFFSET_PONE); - assertEquals(test.getTransition(null), null); - assertEquals(test.getStandardOffset(null), OFFSET_PONE); - assertEquals(test.getDaylightSavings(null), Duration.ZERO); - assertEquals(test.isDaylightSavings(null), false); - assertEquals(test.nextTransition(null), null); - assertEquals(test.previousTransition(null), null); + assertEquals(OFFSET_PONE, test.getOffset((Instant) null)); + assertEquals(OFFSET_PONE, test.getOffset((LocalDateTime) null)); + assertEquals(1, test.getValidOffsets(null).size()); + assertEquals(OFFSET_PONE, test.getValidOffsets(null).get(0)); + assertEquals(null, test.getTransition(null)); + assertEquals(OFFSET_PONE, test.getStandardOffset(null)); + assertEquals(Duration.ZERO, test.getDaylightSavings(null)); + assertEquals(false, test.isDaylightSavings(null)); + assertEquals(null, test.nextTransition(null)); + assertEquals(null, test.previousTransition(null)); } } diff --git a/test/jdk/java/time/test/java/time/zone/TestMutableZoneRules.java b/test/jdk/java/time/test/java/time/zone/TestMutableZoneRules.java index 4474f70db05..a8d7f4746c7 100644 --- a/test/jdk/java/time/test/java/time/zone/TestMutableZoneRules.java +++ b/test/jdk/java/time/test/java/time/zone/TestMutableZoneRules.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2025, 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,16 +27,15 @@ import java.time.*; import java.time.zone.*; import java.util.*; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; /** * @summary ZoneRules invariants can be broken. * * @bug 8246788 */ -@Test public class TestMutableZoneRules { static final ZoneOffset offset = ZoneOffset.ofHoursMinutes(1, 30); @@ -48,16 +47,18 @@ public class TestMutableZoneRules { ZoneOffsetTransitionRule.of(Month.MARCH, 2, DayOfWeek.MONDAY, LocalTime.MIN, true, ZoneOffsetTransitionRule.TimeDefinition.UTC, offset, offset, offset); + @Test public void testMutation() { ZoneOffsetTransitionRule[] array = { rule1 }; ZoneRules zr1 = ZoneRules.of(offset, offset, List.of(), List.of(), List.of(rule1)); ZoneRules zr2 = ZoneRules.of(offset, offset, List.of(), List.of(), new TestList(array, array.length)); - assertEquals(zr2, zr1); + assertEquals(zr1, zr2); array[0] = rule2; - assertEquals(zr2, zr1); + assertEquals(zr1, zr2); } + @Test public void testLength() { ZoneOffsetTransitionRule[] array = new ZoneOffsetTransitionRule[17]; Arrays.setAll(array, i -> rule1); diff --git a/test/jdk/java/time/test/java/time/zone/TestZoneRules.java b/test/jdk/java/time/test/java/time/zone/TestZoneRules.java index 584ed2e56c7..7a1e656ee87 100644 --- a/test/jdk/java/time/test/java/time/zone/TestZoneRules.java +++ b/test/jdk/java/time/test/java/time/zone/TestZoneRules.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -40,17 +40,19 @@ import java.time.zone.ZoneRules; import java.util.Collections; import java.util.List; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @summary Tests for ZoneRules class. * * @bug 8212970 8236903 8239836 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestZoneRules { private static final ZoneId DUBLIN = ZoneId.of("Europe/Dublin"); @@ -68,7 +70,6 @@ public class TestZoneRules { private static final ZoneOffsetTransition ZOT = ZoneId.of("America/Los_Angeles").getRules().getTransitions().get(0); private static final ZoneOffsetTransitionRule ZOTR = ZoneId.of("America/Los_Angeles").getRules().getTransitionRules().get(0); - @DataProvider private Object[][] negativeDST () { return new Object[][] { // ZoneId, localDate, offset, standard offset, isDaylightSavings @@ -102,7 +103,6 @@ public class TestZoneRules { }; } - @DataProvider private Object[][] transitionBeyondDay() { return new Object[][] { // ZoneId, LocalDateTime, beforeOffset, afterOffset @@ -117,7 +117,6 @@ public class TestZoneRules { }; } - @DataProvider private Object[][] emptyTransitionList() { return new Object[][] { // days, offset, std offset, savings, isDST @@ -126,7 +125,6 @@ public class TestZoneRules { }; } - @DataProvider private Object[][] isFixedOffset() { return new Object[][] { // ZoneRules, expected @@ -144,20 +142,22 @@ public class TestZoneRules { * negative savings in the source TZ files. * @bug 8212970 */ - @Test(dataProvider="negativeDST") + @ParameterizedTest + @MethodSource("negativeDST") public void test_NegativeDST(ZoneId zid, LocalDate ld, ZoneOffset offset, ZoneOffset stdOffset, boolean isDST) { Instant i = Instant.from(ZonedDateTime.of(ld, LocalTime.MIN, zid)); ZoneRules zr = zid.getRules(); - assertEquals(zr.getOffset(i), offset); - assertEquals(zr.getStandardOffset(i), stdOffset); - assertEquals(zr.isDaylightSavings(i), isDST); + assertEquals(offset, zr.getOffset(i)); + assertEquals(stdOffset, zr.getStandardOffset(i)); + assertEquals(isDST, zr.isDaylightSavings(i)); } /** * Check the transition cutover time beyond 24:00, which should translate into the next day. * @bug 8212970 */ - @Test(dataProvider="transitionBeyondDay") + @ParameterizedTest + @MethodSource("transitionBeyondDay") public void test_TransitionBeyondDay(ZoneId zid, LocalDateTime ldt, ZoneOffset before, ZoneOffset after) { ZoneOffsetTransition zot = ZoneOffsetTransition.of(ldt, before, after); ZoneRules zr = zid.getRules(); @@ -198,14 +198,15 @@ public class TestZoneRules { Collections.singletonList(transitionRule)); ZoneOffset offsetA = zoneRulesA.getOffset(maxLocalDateTime); ZoneOffset offsetB = zoneRulesB.getOffset(maxLocalDateTime); - assertEquals(offsetA, offsetB); + assertEquals(offsetB, offsetA); } /** * Tests whether empty "transitionList" is correctly interpreted. * @bug 8239836 */ - @Test(dataProvider="emptyTransitionList") + @ParameterizedTest + @MethodSource("emptyTransitionList") public void test_EmptyTransitionList(int days, int offset, int stdOffset, int savings, boolean isDST) { LocalDateTime transitionDay = LocalDateTime.of(2020, 1, 1, 2, 0); Instant testDay = transitionDay.plusDays(days).toInstant(ZoneOffset.UTC); @@ -217,18 +218,19 @@ public class TestZoneRules { Collections.singletonList(trans), Collections.emptyList(), Collections.emptyList()); - assertEquals(rules.getOffset(testDay), ZoneOffset.ofHours(offset)); - assertEquals(rules.getStandardOffset(testDay), ZoneOffset.ofHours(stdOffset)); - assertEquals(rules.getDaylightSavings(testDay), Duration.ofHours(savings)); - assertEquals(rules.isDaylightSavings(testDay), isDST); + assertEquals(ZoneOffset.ofHours(offset), rules.getOffset(testDay)); + assertEquals(ZoneOffset.ofHours(stdOffset), rules.getStandardOffset(testDay)); + assertEquals(Duration.ofHours(savings), rules.getDaylightSavings(testDay)); + assertEquals(isDST, rules.isDaylightSavings(testDay)); } /** * Tests whether isFixedOffset() is working correctly * @bug 8239836 */ - @Test(dataProvider="isFixedOffset") + @ParameterizedTest + @MethodSource("isFixedOffset") public void test_IsFixedOffset(ZoneRules zr, boolean expected) { - assertEquals(zr.isFixedOffset(), expected); + assertEquals(expected, zr.isFixedOffset()); } } diff --git a/test/jdk/java/time/test/java/time/zone/TestZoneRulesProvider.java b/test/jdk/java/time/test/java/time/zone/TestZoneRulesProvider.java index 3a20dc2b864..6b0463d1b26 100644 --- a/test/jdk/java/time/test/java/time/zone/TestZoneRulesProvider.java +++ b/test/jdk/java/time/test/java/time/zone/TestZoneRulesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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,17 +32,15 @@ import java.util.LinkedHashSet; import java.util.NavigableMap; import java.util.Set; -import org.testng.annotations.Test; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; /** * @summary Tests for ZoneRulesProvider class. * @bug 8299571 8302983 */ -@Test public class TestZoneRulesProvider { /** diff --git a/test/jdk/java/time/test/java/util/TestFormatter.java b/test/jdk/java/time/test/java/util/TestFormatter.java index 903e48ba96d..72b859e533e 100644 --- a/test/jdk/java/time/test/java/util/TestFormatter.java +++ b/test/jdk/java/time/test/java/util/TestFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -22,7 +22,7 @@ */ package test.java.util; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Instant; import java.time.LocalTime; @@ -42,14 +42,15 @@ import java.time.temporal.UnsupportedTemporalTypeException; import java.util.*; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /* @test * @summary Unit test for j.u.Formatter threeten date/time support * @bug 8003680 8043387 8012638 */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestFormatter { // time @@ -71,7 +72,6 @@ public class TestFormatter { private int failure = 0; private boolean verbose = false; - @DataProvider(name = "calendarsByLocale") Object[][] data_calendars() { return new Object[][] { {"en_US"}, @@ -80,7 +80,8 @@ public class TestFormatter { }; } - @Test(dataProvider="calendarsByLocale") + @ParameterizedTest + @MethodSource("data_calendars") public void test (String calendarLocale) { failure = 0; int N = 12; @@ -128,7 +129,7 @@ public class TestFormatter { System.out.println("All tests (" + total + ") PASSED"); } } - assertEquals(failure, 0); + assertEquals(0, failure); } private String getClassName(Object o) { diff --git a/test/jdk/java/util/Locale/PreserveTagCase.java b/test/jdk/java/util/Locale/PreserveTagCase.java index c5535e3a89f..3721067e831 100644 --- a/test/jdk/java/util/Locale/PreserveTagCase.java +++ b/test/jdk/java/util/Locale/PreserveTagCase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, 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 @@ -53,7 +53,7 @@ public class PreserveTagCase { */ @ParameterizedTest @MethodSource("filterProvider") - public static void testFilterTags(String ranges, List tags, + public void testFilterTags(String ranges, List tags, List expected, FilteringMode mode) { List priorityList = LanguageRange.parse(ranges); List actual = Locale.filterTags(priorityList, tags, mode); @@ -67,7 +67,7 @@ public class PreserveTagCase { */ @ParameterizedTest @MethodSource("lookupProvider") - public static void testLookupTag(String ranges, List tags, + public void testLookupTag(String ranges, List tags, String expected) { List priorityList = LanguageRange.parse(ranges); String actual = Locale.lookupTag(priorityList, tags); diff --git a/test/jdk/java/util/TimeZone/TimeZoneData/VERSION b/test/jdk/java/util/TimeZone/TimeZoneData/VERSION index 750d9fae2b1..76d146afc71 100644 --- a/test/jdk/java/util/TimeZone/TimeZoneData/VERSION +++ b/test/jdk/java/util/TimeZone/TimeZoneData/VERSION @@ -1 +1 @@ -tzdata2025b +tzdata2025c diff --git a/test/jdk/javax/net/ssl/HttpsURLConnection/DummyCacheResponse.java b/test/jdk/javax/net/ssl/HttpsURLConnection/DummyCacheResponse.java index f18dca8b0f7..e0d9a3cdc01 100644 --- a/test/jdk/javax/net/ssl/HttpsURLConnection/DummyCacheResponse.java +++ b/test/jdk/javax/net/ssl/HttpsURLConnection/DummyCacheResponse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, 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 @@ -43,7 +43,7 @@ import jdk.test.lib.net.SimpleSSLContext; import com.sun.net.httpserver.*; public class DummyCacheResponse extends SecureCacheResponse { - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); private final SSLSession cachedSession; private final Map> rqstHeaders; @@ -61,7 +61,6 @@ public class DummyCacheResponse extends SecureCacheResponse { executor = Executors.newCachedThreadPool(); httpsServer.setExecutor(executor); - sslContext = new SimpleSSLContext().get(); httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); httpsServer.start(); diff --git a/test/jdk/javax/net/ssl/HttpsURLConnection/Equals.java b/test/jdk/javax/net/ssl/HttpsURLConnection/Equals.java index 35913edd2bf..1e43547c59d 100644 --- a/test/jdk/javax/net/ssl/HttpsURLConnection/Equals.java +++ b/test/jdk/javax/net/ssl/HttpsURLConnection/Equals.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, 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 @@ -49,7 +49,7 @@ public class Equals { */ private static final boolean debug = false; - static SSLContext ctx; + private static final SSLContext ctx = SimpleSSLContext.findSSLContext(); public static void main(String[] args) throws Exception { if (debug) { @@ -65,7 +65,6 @@ public class Equals { HttpContext c2 = s2.createContext("/test1", h); executor = Executors.newCachedThreadPool(); s2.setExecutor(executor); - ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator(ctx)); s2.start(); int httpsport = s2.getAddress().getPort(); diff --git a/test/jdk/javax/net/ssl/HttpsURLConnection/HttpsSession.java b/test/jdk/javax/net/ssl/HttpsURLConnection/HttpsSession.java index e17ff6c95b2..7b6ac18c4c9 100644 --- a/test/jdk/javax/net/ssl/HttpsURLConnection/HttpsSession.java +++ b/test/jdk/javax/net/ssl/HttpsURLConnection/HttpsSession.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, 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,7 +41,7 @@ import jdk.test.lib.net.SimpleSSLContext; public class HttpsSession { - static SSLContext sslContext; + private static final SSLContext sslContext = SimpleSSLContext.findSSLContext(); public static void main(String[] args) throws Exception { HttpsServer httpsServer = null; @@ -53,8 +53,6 @@ public class HttpsSession { executor = Executors.newCachedThreadPool(); httpsServer.setExecutor(executor); - - sslContext = new SimpleSSLContext().get(); httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); httpsServer.start(); diff --git a/test/jdk/javax/net/ssl/HttpsURLConnection/SubjectAltNameIP.java b/test/jdk/javax/net/ssl/HttpsURLConnection/SubjectAltNameIP.java index cbd2089e7bd..de747922d7b 100644 --- a/test/jdk/javax/net/ssl/HttpsURLConnection/SubjectAltNameIP.java +++ b/test/jdk/javax/net/ssl/HttpsURLConnection/SubjectAltNameIP.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -101,7 +101,7 @@ public class SubjectAltNameIP { */ void doServerSide() throws Exception { SSLServerSocketFactory sslssf = - new SimpleSSLContext().get().getServerSocketFactory(); + SimpleSSLContext.findSSLContext().getServerSocketFactory(); SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket( serverPort, 0, @@ -139,7 +139,7 @@ public class SubjectAltNameIP { throw new RuntimeException("Server failed to start.", serverException); } - SSLSocketFactory sf = new SimpleSSLContext().get().getSocketFactory(); + SSLSocketFactory sf = SimpleSSLContext.findSSLContext().getSocketFactory(); URI uri = new URI("https://" + hostName + ":" + serverPort + "/index.html"); HttpsURLConnection conn = (HttpsURLConnection)uri.toURL().openConnection(); diff --git a/test/jdk/javax/swing/Security/6657138/bug6657138.java b/test/jdk/javax/swing/Security/6657138/bug6657138.java deleted file mode 100644 index 4670d57595c..00000000000 --- a/test/jdk/javax/swing/Security/6657138/bug6657138.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2009, 2018, 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. - */ - -/* - * @test - * @bug 6657138 - * @summary Verifies that buttons and labels don't share their ui's across appContexts - * @author Alexander Potochkin - * @modules java.desktop/sun.awt - */ - -import sun.awt.SunToolkit; - -import javax.swing.*; -import javax.swing.plaf.ButtonUI; -import javax.swing.plaf.ComponentUI; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class bug6657138 implements Runnable { - - private static Map> componentMap = - Collections.synchronizedMap( - new HashMap>()); - - public void run() { - SunToolkit.createNewAppContext(); - try { - testUIMap(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static void testUIMap() throws Exception { - UIManager.LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels(); - Set components = componentMap.keySet(); - for (JComponent c : components) { - Map uiMap = componentMap.get(c); - - for (UIManager.LookAndFeelInfo laf : lafs) { - if ("Nimbus".equals(laf.getName())) { - // for some unclear reasons - // Nimbus ui delegate for a button is null - // when this method is called from the new AppContext - continue; - } - String className = laf.getClassName(); - try { - UIManager.setLookAndFeel(className); - } catch (final UnsupportedLookAndFeelException ignored) { - continue; - } - ComponentUI ui = UIManager.getUI(c); - if (ui == null) { - throw new RuntimeException("UI is null for " + c); - } - if (ui == uiMap.get(laf.getName())) { - throw new RuntimeException( - "Two AppContexts share the same UI delegate! \n" + - c + "\n" + ui); - } - uiMap.put(laf.getName(), ui); - } - } - } - - public static void main(String[] args) throws Exception { - componentMap.put(new JButton("JButton"), - new HashMap()); - componentMap.put(new JToggleButton("JToggleButton"), - new HashMap()); - componentMap.put(new JRadioButton("JRadioButton"), - new HashMap()); - componentMap.put(new JCheckBox("JCheckBox"), - new HashMap()); - componentMap.put(new JCheckBox("JLabel"), - new HashMap()); - testUIMap(); - ThreadGroup group = new ThreadGroup("6657138"); - Thread thread = new Thread(group, new bug6657138()); - thread.start(); - thread.join(); - } -} - diff --git a/test/jdk/jdk/jfr/event/tracing/TestConstructors.java b/test/jdk/jdk/jfr/event/tracing/TestConstructors.java new file mode 100644 index 00000000000..26548646b49 --- /dev/null +++ b/test/jdk/jdk/jfr/event/tracing/TestConstructors.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2025, 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. + */ +package jdk.jfr.event.tracing; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import jdk.jfr.Recording; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedMethod; +import jdk.jfr.consumer.RecordingFile; +import jdk.test.lib.jfr.Events; + +/** + * @test + * @summary Tests that constructors are instrumented correctly. + * @requires vm.flagless + * @requires vm.hasJFR + * @library /test/lib + * @run main/othervm -Xlog:jfr+methodtrace=debug + * jdk.jfr.event.tracing.TestConstructors + **/ +public class TestConstructors { + static private void methodThatThrows() { + throw new RuntimeException(); + } + + public static class Cat { + Cat() { + new String(); + methodThatThrows(); + super(); + methodThatThrows(); + } + } + + public static class Dog { + Dog() { + super(); + methodThatThrows(); + } + } + + public static class Tiger { + Tiger() { + methodThatThrows(); + super(); + } + } + + public static class Zebra { + Zebra(boolean shouldThrow) { + this(shouldThrow ? 1 : 0); + } + + Zebra(int shouldThrow) { + if (shouldThrow == 1) { + throw new RuntimeException(); + } + } + } + + public static class Snake { + Snake() { + try { + throw new RuntimeException(); + } catch (Exception e) { + // Ignore + } + super(); + } + } + + public static void main(String... args) throws Exception { + try (Recording r = new Recording()) { + r.enable("jdk.MethodTrace").with("filter", Dog.class.getName() + ";" + Cat.class.getName() + ";" + Tiger.class.getName() + ";" + Zebra.class.getName() + ";" + Snake.class.getName()); + r.start(); + try { + new Cat(); + } catch (Exception e) { + // ignore + } + try { + new Dog(); + } catch (Exception e) { + // ignore + } + try { + new Tiger(); + } catch (Exception e) { + // ignore + } + try { + new Zebra(true); + } catch (Exception e) { + // ignore + } + try { + new Zebra(false); + } catch (Exception e) { + // ignore + } + try { + new Snake(); + } catch (Exception e) { + // ignore + } + r.stop(); + List events = Events.fromRecording(r); + var methods = buildMethodMap(events); + if (methods.size() != 5) { + throw new Exception("Expected 5 different methods"); + } + assertMethodCount(methods, "Cat", 1); + assertMethodCount(methods, "Dog", 1); + assertMethodCount(methods, "Snake", 1); + assertMethodCount(methods, "Tiger", 1); + assertMethodCount(methods, "Zebra", 3); + } + } + + private static void assertMethodCount(Map methods, String className, int expectedCount) throws Exception { + String name = TestConstructors.class.getName() + "$" + className + "::"; + Long count = methods.get(name); + if (count == null) { + throw new Exception("Could not find traced method " + name); + } + if (count != expectedCount) { + throw new Exception("Expected " + expectedCount + " trace event for " + name); + } + } + + private static Map buildMethodMap(List events) { + Map map = new TreeMap<>(); + for (RecordedEvent e : events) { + RecordedMethod m = e.getValue("method"); + String name = m.getType().getName() + "::" + m.getName(); + map.compute(name, (_, value) -> (value == null) ? 1 : value + 1); + } + for (var e : map.entrySet()) { + System.out.println(e.getKey() + " " + e.getValue()); + } + return map; + } +} \ No newline at end of file diff --git a/test/jdk/jdk/jfr/event/tracing/TestInstrumentation.java b/test/jdk/jdk/jfr/event/tracing/TestInstrumentation.java index 834d4ab4989..5709c95812a 100644 --- a/test/jdk/jdk/jfr/event/tracing/TestInstrumentation.java +++ b/test/jdk/jdk/jfr/event/tracing/TestInstrumentation.java @@ -93,6 +93,8 @@ public class TestInstrumentation { assertMethod(map, "exception", 2); assertMethod(map, "switchExpression", 3); assertMethod(map, "recursive", 4); + assertMethod(map, "deepException", 1); + assertMethod(map, "whileTrue", 1); assertMethod(map, "multipleReturns", 5); if (!map.isEmpty()) { throw new Exception("Found unexpected methods " + map.keySet()); @@ -105,6 +107,8 @@ public class TestInstrumentation { assertMethod(map, "exception", 2); assertMethod(map, "switchExpression", 3); assertMethod(map, "recursive", 4); + assertMethod(map, "deepException", 1); + assertMethod(map, "whileTrue", 1); assertMethod(map, "multipleReturns", 5); for (var entry : map.entrySet()) { long invocations = entry.getValue(); diff --git a/test/jdk/sun/awt/image/png/PngImageDecoder8BitTest.java b/test/jdk/sun/awt/image/png/PngImageDecoder8BitTest.java new file mode 100644 index 00000000000..b2c134e09b2 --- /dev/null +++ b/test/jdk/sun/awt/image/png/PngImageDecoder8BitTest.java @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2026, 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. + */ + +/* + * @test + * @bug 8374377 + * @summary This test confirms the PNGImageProducer decodes 8-bit interlaced + * and non-interlaced PNGs correctly. + */ + +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.Toolkit; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.ImageConsumer; +import java.awt.image.IndexColorModel; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Random; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +/** + * The proposed change for 8374377 affects how 8-bit PNGs are decoded. + * So this test confirms that 8-bit PNGs (both interlaced and non-interlaced) + * are still decoded by the PNGImageDecoder so they match what ImageIO decodes. + * + * This test has never failed. + */ +public class PngImageDecoder8BitTest { + + static BufferedImage createBufferedImage(Image img) + throws ExecutionException, InterruptedException { + CompletableFuture future = new CompletableFuture<>(); + img.getSource().startProduction(new ImageConsumer() { + private int imageWidth, imageHeight; + private BufferedImage bi; + + @Override + public void setDimensions(int width, int height) { + imageWidth = width; + imageHeight = height; + } + + @Override + public void setProperties(Hashtable props) { + // intentionally empty + } + + @Override + public void setColorModel(ColorModel model) { + // intentionally empty + } + + @Override + public void setHints(int hintflags) { + // intentionally empty + } + + @Override + public void setPixels(int x, int y, int w, int h, ColorModel model, + byte[] pixels, int off, int scansize) { + if (bi == null) { + bi = new BufferedImage(imageWidth, imageHeight, + BufferedImage.TYPE_BYTE_INDEXED, + (IndexColorModel) model); + } + + if (w == imageWidth && h == imageHeight) { + // this is how interlaced PNGs are decoded: + bi.getRaster().setDataElements(0, 0, + imageWidth, imageHeight, pixels); + return; + } + + if (h != 1) { + throw new UnsupportedOperationException( + "this test requires h = 1"); + } + if (off != 0) { + throw new UnsupportedOperationException( + "this test requires off = 0"); + } + + bi.getRaster().setDataElements(x, y, w, 1, pixels); + } + + @Override + public void setPixels(int x, int y, int w, int h, ColorModel model, + int[] pixels, int off, int scansize) { + throw new UnsupportedOperationException(); + } + + @Override + public void imageComplete(int status) { + future.complete(bi); + } + }); + return future.get(); + } + + public static void main(String[] args) throws Exception { + BufferedImage expected = createImageData(); + for (boolean interlace : new boolean[] { false, true} ) { + System.out.println("Testing interlacing = "+ interlace); + byte[] imageData = encodePNG(expected, interlace); + + Image i = Toolkit.getDefaultToolkit().createImage(imageData); + BufferedImage actual = createBufferedImage(i); + + testCorrectness(expected, actual); + } + System.out.println("Confirmed that 8-bit PNGs decode correctly " + + "whether we use interlacing or not."); + } + + /** + * Create a large sample image stored as an 8-bit PNG. + */ + private static BufferedImage createImageData() { + BufferedImage bi = new BufferedImage(6000, 6000, + BufferedImage.TYPE_BYTE_INDEXED); + Random r = new Random(0); + Graphics2D g = bi.createGraphics(); + for (int a = 0; a < 20000; a++) { + g.setColor(new Color(r.nextInt(0xffffff))); + int radius = 10 + r.nextInt(90); + g.fillOval(r.nextInt(bi.getWidth()), r.nextInt(bi.getHeight()), + radius, radius); + } + g.dispose(); + return bi; + } + + /** + * Encode an image as 8-bit PNG. + */ + private static byte[] encodePNG(BufferedImage bi, boolean interlace) + throws IOException { + Iterator writers = + ImageIO.getImageWritersByFormatName("png"); + if (!writers.hasNext()) { + throw new IllegalStateException("No PNG writers found"); + } + ImageWriter writer = writers.next(); + + ImageWriteParam param = writer.getDefaultWriteParam(); + if (interlace) { + param.setProgressiveMode(ImageWriteParam.MODE_DEFAULT); + } + + try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + ImageOutputStream imageOut = + ImageIO.createImageOutputStream(byteOut)) { + writer.setOutput(imageOut); + writer.write(null, new IIOImage(bi, null, null), param); + return byteOut.toByteArray(); + } finally { + writer.dispose(); + } + } + + /** + * This throws an Error if the two images are not identical. + *

    + * This unit test is intended to accompany a performance enhancement for + * PNGImageDecoder. This method makes sure the enhancement didn't cost us + * any accuracy. + */ + private static void testCorrectness(BufferedImage expected, + BufferedImage actual) { + if (expected.getWidth() != actual.getWidth()) { + throw new RuntimeException("expected.getWidth() = " + + expected.getWidth() + ", actual.getWidth() = " + + actual.getWidth()); + } + if (expected.getHeight() != actual.getHeight()) { + throw new RuntimeException("expected.getHeight() = " + + expected.getHeight() + ", actual.getHeight() = " + + actual.getHeight()); + } + for (int y = 0; y < expected.getHeight(); y++) { + for (int x = 0; x < expected.getWidth(); x++) { + int argb1 = expected.getRGB(x, y); + int argb2 = actual.getRGB(x, y); + if (argb1 != argb2) { + throw new RuntimeException("x = " + x + ", y = " + y + + " argb1 = " + Integer.toUnsignedString(argb1, 16) + + " argb2 = " + Integer.toUnsignedString(argb2, 16)); + } + } + } + } +} diff --git a/test/jdk/sun/net/www/protocol/http/RedirectOnPost.java b/test/jdk/sun/net/www/protocol/http/RedirectOnPost.java index 1f88c851f63..69da47651b7 100644 --- a/test/jdk/sun/net/www/protocol/http/RedirectOnPost.java +++ b/test/jdk/sun/net/www/protocol/http/RedirectOnPost.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2026, 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 @@ -46,7 +46,7 @@ public class RedirectOnPost { public static void main(String[] args) throws Exception { ExecutorService e= Executors.newFixedThreadPool(5); - SSLContext ctx = new SimpleSSLContext().get(); + SSLContext ctx = SimpleSSLContext.findSSLContext(); HttpServer httpServer = getHttpServer(e); HttpsServer httpsServer = getHttpsServer(e, ctx); diff --git a/test/jdk/sun/security/ec/ECDSAPrimitive.java b/test/jdk/sun/security/ec/ECDSAPrimitive.java index 71e2e30044b..b8901a784ff 100644 --- a/test/jdk/sun/security/ec/ECDSAPrimitive.java +++ b/test/jdk/sun/security/ec/ECDSAPrimitive.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -249,7 +249,7 @@ public class ECDSAPrimitive { byte[] u1Bytes = u1.asByteArray(length); byte[] u2Bytes = u2.asByteArray(length); - AffinePoint publicKeyPoint = ECDSAOperations.toAffinePoint(publicKey, + AffinePoint publicKeyPoint = AffinePoint.fromECPoint(publicKey, ecOps.getField()); MutablePoint R = ecOps.multiply(publicKeyPoint, u2Bytes); AffinePoint a1 = ops.basePointMultiply(u1Bytes); diff --git a/test/jdk/sun/security/krb5/auto/HttpsCB.java b/test/jdk/sun/security/krb5/auto/HttpsCB.java index 1f9f0de33ac..278e72592be 100644 --- a/test/jdk/sun/security/krb5/auto/HttpsCB.java +++ b/test/jdk/sun/security/krb5/auto/HttpsCB.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, 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 @@ -214,7 +214,7 @@ public class HttpsCB { MyHttpHandler h = new MyHttpHandler(); HttpsServer server = HttpsServer.create(new InetSocketAddress(0), 0); server.setHttpsConfigurator( - new HttpsConfigurator(new SimpleSSLContext().get())); + new HttpsConfigurator(SimpleSSLContext.findSSLContext())); server.createContext("/", h).setAuthenticator( new MyServerAuthenticator(scheme, principal, ktab)); server.start(); diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Chunghwa.java b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Chunghwa.java new file mode 100644 index 00000000000..8512640bb01 --- /dev/null +++ b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Chunghwa.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2026, 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 javax.net.ssl.X509TrustManager; +import java.io.File; +import java.security.Security; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Date; + +/* + * @test + * @bug 8369282 + * @summary Check that TLS Server certificates chaining back to distrusted + * Chunghwa root are invalid + * @library /test/lib + * @modules java.base/sun.security.validator + * @run main/othervm Chunghwa after policyOn invalid + * @run main/othervm Chunghwa after policyOff valid + * @run main/othervm Chunghwa before policyOn valid + * @run main/othervm Chunghwa before policyOff valid + */ + +public class Chunghwa { + + private static final String CERT_PATH = "chains" + File.separator + "chunghwa"; + + // The ePKI root has a test certificate chain stored in a file + // named "-chain.pem". + private static final String ROOT_TO_TEST = "chunghwaepkirootca"; + + // Date after the restrictions take effect + private static final ZonedDateTime DISTRUST_DATE = + LocalDate.of(2026, 03, 18).atStartOfDay(ZoneOffset.UTC); + + public static void main(String[] args) throws Exception { + + Distrust distrust = new Distrust(args); + + X509TrustManager[] tms = new X509TrustManager[]{ + distrust.getTMF("PKIX", null), + distrust.getTMF("SunX509", null) + }; + + Date notBefore = distrust.getNotBefore(DISTRUST_DATE); + distrust.testCertificateChain(CERT_PATH, notBefore, tms, ROOT_TO_TEST); + } +} diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/chunghwa/chunghwaepkirootca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/chunghwa/chunghwaepkirootca-chain.pem new file mode 100644 index 00000000000..fdaa6ee04df --- /dev/null +++ b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/chunghwa/chunghwaepkirootca-chain.pem @@ -0,0 +1,50 @@ +Owner: CN=HiPKI Root CA - G1, + O="Chunghwa Telecom Co., Ltd.", C=TW +Issuer: OU=ePKI Root Certification Authority, + O="Chunghwa Telecom Co., Ltd.", C=TW +Serial number: 23fba648360e15e92ba78aedb67a0ae5 +Valid from: Wed Dec 20 19:11:23 MST 2023 until: Tue Dec 19 08:59:59 MST 2034 +Certificate fingerprints: + SHA1: 87:F1:DD:3B:8E:F1:E0:8C:A8:CA:CB:9B:CE:4E:26:5A:E4:4E:05:F2 + SHA256: 68:07:C9:72:35:C5:EC:60:90:26:9A:4B:5F:ED:FA:B4:69:86:E4:2F:4D:67:D2:ED:DD:CF:6E:45:CF:0D:FA:80 +Signature algorithm name: SHA256withRSA +Subject Public Key Algorithm: 4096-bit RSA key +Version: 3 + +-----BEGIN CERTIFICATE----- +MIIGjDCCBHSgAwIBAgIQI/umSDYOFekrp4rttnoK5TANBgkqhkiG9w0BAQsFADBe +MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0 +ZC4xKjAoBgNVBAsMIWVQS0kgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe +Fw0yMzEyMjEwMjExMjNaFw0zNDEyMTkxNTU5NTlaME8xCzAJBgNVBAYTAlRXMSMw +IQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEbMBkGA1UEAwwSSGlQ +S0kgUm9vdCBDQSAtIEcxMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA +9B5/UnMyDHPkvRN0o9QwqNCuS9i233VHZvR85zkEHmpwINJaR3JnVfSl6J3VHiGh +8Ge6zCFovkRTv4354twvVcg3Px+kwJyz5HdcoEb+d/oaoDjq7Zpy3iu9lFc6uux5 +5199QmQ5eiY29yTw1S+6lZgRZq2XNdZ1AYDgr/SEYYwNHl98h5ZeQa/rh+r4XfEu +iAU+TCK72h8q3VJGZDnzQs7ZngyzsHeXZJzA9KMuH5UHsBffMNsAGJZMoYFL3QRt +U6M9/Aes1MU3guvklQgZKILSQjqj2FPseYlgSGDIcpJQ3AOPgz+yQlda22rpEZfd +hSi8MEyr48KxRURHH+CKFgeW0iEPU8DtqX7UTuybCeyvQqww1r/REEXgphaypcXT +T3OUM3ECoWqj1jOXTyFjHluP2cFeRXF3D4FdXyGarYPM+l7WjSNfGz1BryB1ZlpK +9p/7qxj3ccC2HTHsOyDry+K49a6SsvfhhEvyovKTmiKe0xRvNlS9H15ZFblzqMF8 +b3ti6RZsR1pl8w4Rm0bZ/W3c1pzAtH2lsN0/Vm+h+fbkEkj9Bn8SV7apI09bA8Pg +cSojt/ewsTu8mL3WmKgMa/aOEmem8rJY5AIJEzypuxC00jBF8ez3ABHfZfjcK0NV +vxaXxA/VLGGEqnKG/uY6fsI/fe78LxQ+5oXdUG+3Se0CAwEAAaOCAVMwggFPMB8G +A1UdIwQYMBaAFB4M97Zn8uGSJglFwFU5Lnc/QkqiMB0GA1UdDgQWBBTydxf6Xqj+ +9j1x1Wi6yUYMONivsDAOBgNVHQ8BAf8EBAMCAYYwQAYDVR0fBDkwNzA1oDOgMYYv +aHR0cDovL2VjYS5oaW5ldC5uZXQvcmVwb3NpdG9yeS9DUkxfU0hBMi9DQS5jcmww +gYIGCCsGAQUFBwEBBHYwdDA7BggrBgEFBQcwAoYvaHR0cDovL2VjYS5oaW5ldC5u +ZXQvcmVwb3NpdG9yeS9DZXJ0cy9lQ0FHMS5jcnQwNQYIKwYBBQUHMAGGKWh0dHA6 +Ly9vY3NwLmVjYS5oaW5ldC5uZXQvT0NTUC9vY3NwRzFzaGEyMBIGA1UdEwEB/wQI +MAYBAf8CAQEwIgYDVR0gBBswGTAIBgZngQwBAgIwDQYLKwYBBAGBtyNkAAMwDQYJ +KoZIhvcNAQELBQADggIBACY9pps8fqk3p8Xqv/qr26I1aFA4jOEG3VWd2bqn68Y9 +InOMZozTMVh7iOnOfat7mEqn/RNhikvR5MOV3qAeg4gwgNb1OMuGltwfXWGiuGeT +vhimsV6E2hhJFAmZyXtfuoV9vSrnr1a5pCWqhVYWSCvoAQ/8Kv0tATKbIe21CYXz +NIo7O9QBSXt0BiaP9+CVQtJAYYuy2MNAcXgzgL4rownrYYAixhPmkxQE0Dt1gVbW +s2htBLJGse0z1fJDblY0Zar4t2ly+kIScx5DhRrrd8XKMK0YvID9Ythb+ao8m7Wd +Kymqr36benGL3GsvmSypLPlqZtfEqVITFhXwQiL8ruxoL+3WfNQJ09x0iV4xaP+E +bZSLLVzIiyhU49YdFHaqKyAJQvzgF2Za3DOwQWlP7OngtUx0ScEGHsoo78AM+Y0T +eLFxmr82kuyH18wZkUT9bLZlot11P2aC8VTprBGr+jEAMJjpmEjSA83ja/ttmqgh +qjj29Jnw3Lgy91XIhzBFMxMYo+hhYeBRmBFWl5+Y5oxBgPVLZpDJvg2rKa8xdqim +KgvF0DMKHntE0hhVy7JfUCnKovNQ0pf0NodLfjpqcCS2GBZ1mNcsW2MG2uBPANcn +LRXmt7N4XX11mctQTADwt8yZZ+2HDrST4kghOz+FXgftrPBdtDtM0T6WJcHWR1uS +-----END CERTIFICATE----- diff --git a/test/jdk/sun/security/util/Password/EmptyIn.java b/test/jdk/sun/security/util/Password/EmptyIn.java new file mode 100644 index 00000000000..b5692b9e7f9 --- /dev/null +++ b/test/jdk/sun/security/util/Password/EmptyIn.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2026, 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 jdk.test.lib.Asserts; +import sun.security.util.Password; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +/* + * @test + * @bug 8374555 + * @summary only print warning when reading from System.in + * @modules java.base/sun.security.util + * @library /test/lib + */ +public class EmptyIn { + public static void main(String[] args) throws Exception { + testSystemIn(); + testNotSystemIn(); + } + + static void testSystemIn() throws Exception { + var in = new ByteArrayInputStream(new byte[0]); + var err = new ByteArrayOutputStream(); + var oldErr = System.err; + var oldIn = System.in; + try { + System.setIn(in); + System.setErr(new PrintStream(err)); + Password.readPassword(System.in); + } finally { + System.setIn(oldIn); + System.setErr(oldErr); + } + // Read from System.in. Should warn. + Asserts.assertNotEquals(0, err.size()); + } + + static void testNotSystemIn() throws Exception { + var in = new ByteArrayInputStream(new byte[0]); + var err = new ByteArrayOutputStream(); + var oldErr = System.err; + try { + System.setErr(new PrintStream(err)); + Password.readPassword(in); + } finally { + System.setErr(oldErr); + } + // Not read from System.in. Should not warn. + Asserts.assertEQ(0, err.size()); + } +} diff --git a/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/ExecutorTest.java b/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/ExecutorTest.java deleted file mode 100644 index 2b075e0f13c..00000000000 --- a/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/ExecutorTest.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Copyright (c) 2025, 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. - */ -package jdk.jpackage.test; - -import static java.util.stream.Collectors.joining; -import static java.util.stream.Collectors.toSet; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.UncheckedIOException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.function.Consumer; -import java.util.spi.ToolProvider; -import java.util.stream.Stream; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -public class ExecutorTest extends JUnitAdapter { - - private record Command(List stdout, List stderr) { - Command { - stdout.forEach(Objects::requireNonNull); - stderr.forEach(Objects::requireNonNull); - } - - List asExecutable() { - final List commandline = new ArrayList<>(); - if (TKit.isWindows()) { - commandline.addAll(List.of("cmd", "/C")); - } else { - commandline.addAll(List.of("sh", "-c")); - } - commandline.add(Stream.concat(createEchoCommands(stdout), - createEchoCommands(stderr).map(v -> v + ">&2")).collect(joining(" && "))); - return commandline; - } - - private static Stream createEchoCommands(List lines) { - return lines.stream().map(line -> { - if (TKit.isWindows()) { - return "(echo " + line + ")"; - } else { - return "echo " + line; - } - }); - } - - ToolProvider asToolProvider() { - return new ToolProvider() { - - @Override - public int run(PrintWriter out, PrintWriter err, String... args) { - stdout.forEach(out::println); - stderr.forEach(err::println); - return 0; - } - - @Override - public String name() { - return "test"; - } - }; - } - } - - private enum OutputData { - EMPTY(List.of()), - ONE_LINE(List.of("Jupiter")), - MANY(List.of("Uranus", "Saturn", "Earth")); - - OutputData(List data) { - data.forEach(Objects::requireNonNull); - this.data = data; - } - - final List data; - } - - private record CommandSpec(OutputData stdout, OutputData stderr) { - CommandSpec { - Objects.requireNonNull(stdout); - Objects.requireNonNull(stderr); - } - - Command command() { - return new Command(stdout.data.stream().map(line -> { - return "stdout." + line; - }).toList(), stderr.data.stream().map(line -> { - return "stderr." + line; - }).toList()); - } - } - - public enum OutputControl { - DUMP(Executor::dumpOutput), - SAVE_ALL(Executor::saveOutput), - SAVE_FIRST_LINE(Executor::saveFirstLineOfOutput), - DISCARD_STDOUT(Executor::discardStdout), - DISCARD_STDERR(Executor::discardStderr), - ; - - OutputControl(Consumer configureExector) { - this.configureExector = Objects.requireNonNull(configureExector); - } - - Executor applyTo(Executor exec) { - configureExector.accept(exec); - return exec; - } - - static List> variants() { - final List> variants = new ArrayList<>(); - for (final var withDump : BOOLEAN_VALUES) { - variants.addAll(Stream.of( - Set.of(), - Set.of(SAVE_ALL), - Set.of(SAVE_FIRST_LINE), - Set.of(DISCARD_STDOUT), - Set.of(DISCARD_STDERR), - Set.of(SAVE_ALL, DISCARD_STDOUT), - Set.of(SAVE_FIRST_LINE, DISCARD_STDOUT), - Set.of(SAVE_ALL, DISCARD_STDERR), - Set.of(SAVE_FIRST_LINE, DISCARD_STDERR), - Set.of(SAVE_ALL, DISCARD_STDOUT, DISCARD_STDERR), - Set.of(SAVE_FIRST_LINE, DISCARD_STDOUT, DISCARD_STDERR) - ).map(v -> { - if (withDump) { - return Stream.concat(Stream.of(DUMP), v.stream()).collect(toSet()); - } else { - return v; - } - }).toList()); - } - return variants.stream().map(options -> { - return options.stream().filter(o -> { - return o.configureExector != NOP; - }).collect(toSet()); - }).distinct().toList(); - } - - private final Consumer configureExector; - - static final Set SAVE = Set.of(SAVE_ALL, SAVE_FIRST_LINE); - } - - public record OutputTestSpec(boolean toolProvider, Set outputControl, CommandSpec commandSpec) { - public OutputTestSpec { - outputControl.forEach(Objects::requireNonNull); - if (outputControl.containsAll(OutputControl.SAVE)) { - throw new IllegalArgumentException(); - } - Objects.requireNonNull(commandSpec); - } - - @Override - public String toString() { - final List tokens = new ArrayList<>(); - - if (toolProvider) { - tokens.add("tool-provider"); - } - - tokens.add("output=" + format(outputControl)); - tokens.add("command=" + commandSpec); - - return String.join(",", tokens.toArray(String[]::new)); - } - - void test() { - final var command = commandSpec.command(); - final var commandWithDiscardedStreams = discardStreams(command); - - final Executor.Result[] result = new Executor.Result[1]; - final var outputCapture = OutputCapture.captureOutput(() -> { - result[0] = createExecutor(command).executeWithoutExitCodeCheck(); - }); - - assertEquals(0, result[0].getExitCode()); - - // If we dump the subprocesses's output, and the command produced both STDOUT and STDERR, - // then the captured STDOUT may contain interleaved command's STDOUT and STDERR, - // not in sequential order (STDOUT followed by STDERR). - // In this case don't check the contents of the captured command's STDOUT. - if (toolProvider || outputCapture.outLines().isEmpty() || (command.stdout().isEmpty() || command.stderr().isEmpty())) { - assertEquals(expectedCapturedSystemOut(commandWithDiscardedStreams), outputCapture.outLines()); - } - assertEquals(expectedCapturedSystemErr(commandWithDiscardedStreams), outputCapture.errLines()); - - assertEquals(expectedResultStdout(commandWithDiscardedStreams), result[0].stdout().getOutput()); - assertEquals(expectedResultStderr(commandWithDiscardedStreams), result[0].stderr().getOutput()); - - if (!saveOutput()) { - assertNull(result[0].getOutput()); - } else { - assertNotNull(result[0].getOutput()); - final var allExpectedOutput = expectedCommandOutput(command); - assertEquals(allExpectedOutput.isEmpty(), result[0].getOutput().isEmpty()); - if (!allExpectedOutput.isEmpty()) { - if (outputControl.contains(OutputControl.SAVE_ALL)) { - assertEquals(allExpectedOutput, result[0].getOutput()); - } else if (outputControl.contains(OutputControl.SAVE_FIRST_LINE)) { - assertEquals(1, result[0].getOutput().size()); - assertEquals(allExpectedOutput.getFirst(), result[0].getFirstLineOfOutput()); - } else { - throw new UnsupportedOperationException(); - } - } - } - } - - private boolean dumpOutput() { - return outputControl.contains(OutputControl.DUMP); - } - - private boolean saveOutput() { - return !Collections.disjoint(outputControl, OutputControl.SAVE); - } - - private boolean discardStdout() { - return outputControl.contains(OutputControl.DISCARD_STDOUT); - } - - private boolean discardStderr() { - return outputControl.contains(OutputControl.DISCARD_STDERR); - } - - private static String format(Set outputControl) { - return outputControl.stream().map(OutputControl::name).sorted().collect(joining("+")); - } - - private List expectedCapturedSystemOut(Command command) { - if (!dumpOutput() || (!toolProvider && !saveOutput())) { - return List.of(); - } else if(saveOutput()) { - return Stream.concat(command.stdout().stream(), command.stderr().stream()).toList(); - } else { - return command.stdout(); - } - } - - private List expectedCapturedSystemErr(Command command) { - if (!dumpOutput() || (!toolProvider && !saveOutput())) { - return List.of(); - } else if(saveOutput()) { - return List.of(); - } else { - return command.stderr(); - } - } - - private List expectedResultStdout(Command command) { - return expectedResultStream(command.stdout()); - } - - private List expectedResultStderr(Command command) { - if (outputControl.contains(OutputControl.SAVE_FIRST_LINE) && !command.stdout().isEmpty()) { - return List.of(); - } - return expectedResultStream(command.stderr()); - } - - private List expectedResultStream(List commandOutput) { - Objects.requireNonNull(commandOutput); - if (outputControl.contains(OutputControl.SAVE_ALL)) { - return commandOutput; - } else if (outputControl.contains(OutputControl.SAVE_FIRST_LINE)) { - return commandOutput.stream().findFirst().map(List::of).orElseGet(List::of); - } else { - return null; - } - } - - private Command discardStreams(Command command) { - return new Command(discardStdout() ? List.of() : command.stdout(), discardStderr() ? List.of() : command.stderr()); - } - - private record OutputCapture(byte[] out, byte[] err, Charset outCharset, Charset errCharset) { - OutputCapture { - Objects.requireNonNull(out); - Objects.requireNonNull(err); - Objects.requireNonNull(outCharset); - Objects.requireNonNull(errCharset); - } - - List outLines() { - return toLines(out, outCharset); - } - - List errLines() { - return toLines(err, errCharset); - } - - private static List toLines(byte[] buf, Charset charset) { - try (var reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf), charset))) { - return reader.lines().filter(line -> { - return !line.contains("TRACE"); - }).toList(); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - static OutputCapture captureOutput(Runnable runnable) { - final var captureOut = new ByteArrayOutputStream(); - final var captureErr = new ByteArrayOutputStream(); - - final var out = System.out; - final var err = System.err; - try { - final var outCharset = System.out.charset(); - final var errCharset = System.err.charset(); - System.setOut(new PrintStream(captureOut, true, outCharset)); - System.setErr(new PrintStream(captureErr, true, errCharset)); - runnable.run(); - return new OutputCapture(captureOut.toByteArray(), captureErr.toByteArray(), outCharset, errCharset); - } finally { - try { - System.setOut(out); - } finally { - System.setErr(err); - } - } - } - } - - private List expectedCommandOutput(Command command) { - command = discardStreams(command); - return Stream.of(command.stdout(), command.stderr()).flatMap(List::stream).toList(); - } - - private Executor createExecutor(Command command) { - final Executor exec; - if (toolProvider) { - exec = Executor.of(command.asToolProvider()); - } else { - exec = Executor.of(command.asExecutable()); - } - - outputControl.forEach(control -> control.applyTo(exec)); - - return exec; - } - } - - @ParameterizedTest - @MethodSource - public void testSavedOutput(OutputTestSpec spec) { - spec.test(); - } - - public static List testSavedOutput() { - List testCases = new ArrayList<>(); - for (final var toolProvider : BOOLEAN_VALUES) { - for (final var outputControl : OutputControl.variants()) { - for (final var stdoutContent : List.of(OutputData.values())) { - for (final var stderrContent : List.of(OutputData.values())) { - final var commandSpec = new CommandSpec(stdoutContent, stderrContent); - testCases.add(new OutputTestSpec(toolProvider, outputControl, commandSpec)); - } - } - } - } - return testCases; - } - - private static final List BOOLEAN_VALUES = List.of(Boolean.TRUE, Boolean.FALSE); - private static final Consumer NOP = exec -> {}; -} diff --git a/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/PackageTestTest.java b/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/PackageTestTest.java index 16909d0eb40..3e169b9e184 100644 --- a/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/PackageTestTest.java +++ b/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/PackageTestTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -213,7 +213,7 @@ public class PackageTestTest extends JUnitAdapter { @Override public void accept(JPackageCommand cmd, Executor.Result result) { tick(); - jpackageExitCode = result.exitCode(); + jpackageExitCode = result.getExitCode(); } @Override @@ -371,8 +371,7 @@ public class PackageTestTest extends JUnitAdapter { } catch (IOException ex) { throw new UncheckedIOException(ex); } - return new Executor.Result(actualJPackageExitCode, - this::getPrintableCommandLine).assertExitCodeIs(expectedExitCode); + return new Executor.Result(actualJPackageExitCode).assertExitCodeIs(expectedExitCode); } }; }).setExpectedExitCode(expectedJPackageExitCode) diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/AppImageFile.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/AppImageFile.java index 94f5b0a52b4..1c6c0ce4447 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/AppImageFile.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/AppImageFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2026, 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 @@ -28,7 +28,6 @@ import static jdk.jpackage.internal.util.function.ThrowingFunction.toFunction; import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; @@ -132,7 +131,7 @@ public record AppImageFile(String mainLauncherName, Optional mainLaunche public static AppImageFile load(Path appImageDir) { return toSupplier(() -> { Document doc = XmlUtils.initDocumentBuilder().parse( - Files.newInputStream(getPathInAppImage(appImageDir))); + getPathInAppImage(appImageDir).toFile()); XPath xPath = XPathFactory.newInstance().newXPath(); diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java index ef118e525c5..5d3033e2e8c 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ -22,18 +22,9 @@ */ package jdk.jpackage.test; -import static java.util.stream.Collectors.joining; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.StringReader; import java.io.UncheckedIOException; -import java.io.Writer; +import java.nio.charset.Charset; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; @@ -43,15 +34,17 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; +import java.util.concurrent.TimeUnit; import java.util.function.Supplier; -import java.util.regex.Pattern; import java.util.spi.ToolProvider; -import java.util.stream.Collectors; +import java.util.stream.IntStream; import java.util.stream.Stream; -import jdk.jpackage.internal.util.function.ThrowingSupplier; +import jdk.jpackage.internal.util.CommandLineFormat; +import jdk.jpackage.internal.util.CommandOutputControl; +import jdk.jpackage.internal.util.CommandOutputControl.UnexpectedExitCodeException; +import jdk.jpackage.internal.util.RetryExecutor; import jdk.jpackage.internal.util.function.ExceptionBox; +import jdk.jpackage.internal.util.function.ThrowingSupplier; public final class Executor extends CommandArguments { @@ -69,8 +62,6 @@ public final class Executor extends CommandArguments { } public Executor() { - outputStreamsControl = new OutputStreamsControl(); - winEnglishOutput = false; } public Executor setExecutable(String v) { @@ -136,62 +127,31 @@ public final class Executor extends CommandArguments { return this; } - /** - * Configures this instance to save all stdout and stderr streams from the to be - * executed command. - *

    - * This function is mutually exclusive with {@link #saveFirstLineOfOutput()}. - * - * @return this - */ public Executor saveOutput() { return saveOutput(true); } - /** - * Configures if all stdout and stderr streams from the to be executed command - * should be saved. - *

    - * If v is true, the function call is equivalent to - * {@link #saveOutput()} call. If v is false, command - * output will not be saved. - * - * @parameter v if both stdout and stderr streams should be saved - * - * @return this - */ public Executor saveOutput(boolean v) { - return setOutputControl(v, OutputControlOption.SAVE_ALL); + commandOutputControl.saveOutput(v); + return this; } - /** - * Configures this instance to save the first line of a stream merged from - * stdout and stderr streams from the to be executed command. - *

    - * This function is mutually exclusive with {@link #saveOutput()}. - * - * @return this - */ public Executor saveFirstLineOfOutput() { - return setOutputControl(true, OutputControlOption.SAVE_FIRST_LINE); + commandOutputControl.saveFirstLineOfOutput(); + return this; } - /** - * Configures this instance to dump both stdout and stderr streams from the to - * be executed command into {@link System.out}. - * - * @return this - */ public Executor dumpOutput() { return dumpOutput(true); } public Executor dumpOutput(boolean v) { - return setOutputControl(v, OutputControlOption.DUMP); + commandOutputControl.dumpOutput(v); + return this; } public Executor discardStdout(boolean v) { - outputStreamsControl.stdout().discard(v); + commandOutputControl.discardStdout(v); return this; } @@ -200,7 +160,7 @@ public final class Executor extends CommandArguments { } public Executor discardStderr(boolean v) { - outputStreamsControl.stderr().discard(v); + commandOutputControl.discardStderr(v); return this; } @@ -208,45 +168,126 @@ public final class Executor extends CommandArguments { return discardStderr(true); } - public interface Output { - public List getOutput(); - - public default String getFirstLineOfOutput() { - return findFirstLineOfOutput().orElseThrow(); - } - - public default Optional findFirstLineOfOutput() { - return getOutput().stream().findFirst(); - } + public Executor binaryOutput(boolean v) { + commandOutputControl.binaryOutput(v); + return this; } - public record Result(int exitCode, CommandOutput output, Supplier cmdline) implements Output { + public Executor binaryOutput() { + return binaryOutput(true); + } + + public Executor charset(Charset v) { + commandOutputControl.charset(v); + return this; + } + + public Charset charset() { + return commandOutputControl.charset(); + } + + Executor storeOutputInFiles(boolean v) { + commandOutputControl.storeOutputInFiles(v); + return this; + } + + Executor storeOutputInFiles() { + return storeOutputInFiles(true); + } + + public record Result(CommandOutputControl.Result base) { public Result { - Objects.requireNonNull(output); - Objects.requireNonNull(cmdline); + Objects.requireNonNull(base); } - public Result(int exitCode, Supplier cmdline) { - this(exitCode, CommandOutput.EMPTY, cmdline); + public Result(int exitCode) { + this(new CommandOutputControl.Result(exitCode)); } - @Override public List getOutput() { - return output.lines().orElse(null); + return base.content(); } - public Output stdout() { - return createView(output.stdoutLines()); + public String getFirstLineOfOutput() { + return getOutput().getFirst(); } - public Output stderr() { - return createView(output.stderrLines()); + public List stdout() { + return base.stdout(); } - public Result assertExitCodeIs(int expectedExitCode) { - TKit.assertEquals(expectedExitCode, exitCode, String.format( - "Check command %s exited with %d code", - cmdline.get(), expectedExitCode)); + public List stderr() { + return base.stderr(); + } + + public Optional> findContent() { + return base.findContent(); + } + + public Optional> findStdout() { + return base.findStdout(); + } + + public Optional> findStderr() { + return base.findStderr(); + } + + public byte[] byteContent() { + return base.byteContent(); + } + + public byte[] byteStdout() { + return base.byteStdout(); + } + + public byte[] byteStderr() { + return base.byteStderr(); + } + + public Optional findByteContent() { + return base.findByteContent(); + } + + public Optional findByteStdout() { + return base.findByteStdout(); + } + + public Optional findByteStderr() { + return base.findByteStderr(); + } + + public Result toCharacterResult(Charset charset, boolean keepByteContent) { + try { + return new Result(base.toCharacterResult(charset, keepByteContent)); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + + public Result assertExitCodeIs(int main, int... other) { + if (other.length != 0) { + return assertExitCodeIs(IntStream.concat(IntStream.of(main), IntStream.of(other)).boxed().toList()); + } else { + return assertExitCodeIs(List.of(main)); + } + } + + private Result assertExitCodeIs(List expectedExitCodes) { + Objects.requireNonNull(expectedExitCodes); + switch (expectedExitCodes.size()) { + case 0 -> { + throw new IllegalArgumentException(); + } case 1 -> { + long expectedExitCode = expectedExitCodes.getFirst(); + TKit.assertEquals(expectedExitCode, getExitCode(), String.format( + "Check command %s exited with %d code", + base.execAttrs(), expectedExitCode)); + } default -> { + TKit.assertTrue(expectedExitCodes.contains(getExitCode()), String.format( + "Check command %s exited with one of %s codes", + base.execAttrs(), expectedExitCodes.stream().sorted().toList())); + } + } return this; } @@ -255,16 +296,11 @@ public final class Executor extends CommandArguments { } public int getExitCode() { - return exitCode; + return base.getExitCode(); } - private static Output createView(Optional> lines) { - return new Output() { - @Override - public List getOutput() { - return lines.orElse(null); - } - }; + public String getPrintableCommandLine() { + return base.execAttrs().toString(); } } @@ -292,8 +328,8 @@ public final class Executor extends CommandArguments { }).get(); } - public Result execute(int expectedCode) { - return executeWithoutExitCodeCheck().assertExitCodeIs(expectedCode); + Result execute(int mainExitCode, int... otherExitCodes) { + return executeWithoutExitCodeCheck().assertExitCodeIs(mainExitCode, otherExitCodes); } public Result execute() { @@ -301,28 +337,36 @@ public final class Executor extends CommandArguments { } public String executeAndGetFirstLineOfOutput() { - return saveFirstLineOfOutput().execute().getFirstLineOfOutput(); + return saveFirstLineOfOutput().execute().getOutput().getFirst(); } public List executeAndGetOutput() { return saveOutput().execute().getOutput(); } - private static class BadResultException extends RuntimeException { - BadResultException(Result v) { - value = v; + private static class FailedAttemptException extends Exception { + FailedAttemptException(Exception cause) { + super(Objects.requireNonNull(cause)); } - Result getValue() { - return value; - } - - private final transient Result value; private static final long serialVersionUID = 1L; } + public RetryExecutor retryUntilExitCodeIs( + int mainExpectedExitCode, int... otherExpectedExitCodes) { + return new RetryExecutor(UnexpectedExitCodeException.class).setExecutable(() -> { + var result = executeWithoutExitCodeCheck(); + result.base().expectExitCode(mainExpectedExitCode, otherExpectedExitCodes); + return result; + }).setExceptionMapper((UnexpectedExitCodeException ex) -> { + createResult(ex.getResult()).assertExitCodeIs(mainExpectedExitCode, otherExpectedExitCodes); + // Unreachable, because the above `Result.assertExitCodeIs(...)` must throw. + throw ExceptionBox.reachedUnreachable(); + }); + } + /** - * Executes the configured command {@code max} at most times and waits for + * Executes the configured command at most {@code max} times and waits for * {@code wait} seconds between each execution until the command exits with * {@code expectedCode} exit code. * @@ -332,17 +376,10 @@ public final class Executor extends CommandArguments { * command */ public Result executeAndRepeatUntilExitCode(int expectedExitCode, int max, int wait) { - try { - return tryRunMultipleTimes(() -> { - Result result = executeWithoutExitCodeCheck(); - if (result.getExitCode() != expectedExitCode) { - throw new BadResultException(result); - } - return result; - }, max, wait).assertExitCodeIs(expectedExitCode); - } catch (BadResultException ex) { - return ex.getValue().assertExitCodeIs(expectedExitCode); - } + return retryUntilExitCodeIs(expectedExitCode) + .setAttemptTimeout(wait, TimeUnit.SECONDS) + .setMaxAttemptsCount(max) + .executeUnchecked(); } /** @@ -359,26 +396,16 @@ public final class Executor extends CommandArguments { * @param wait number of seconds to wait between executions of the */ public static T tryRunMultipleTimes(Supplier task, int max, int wait) { - RuntimeException lastException = null; - int count = 0; - - do { + return new RetryExecutor(FailedAttemptException.class).setExecutable(() -> { try { return task.get(); } catch (RuntimeException ex) { - lastException = ex; + throw new FailedAttemptException(ex); } + }).setExceptionMapper((FailedAttemptException ex) -> { + return (RuntimeException)ex.getCause(); + }).setAttemptTimeout(wait, TimeUnit.SECONDS).setMaxAttemptsCount(max).executeUnchecked(); - try { - Thread.sleep(wait * 1000); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - - count++; - } while (count < max); - - throw lastException; } public static void tryRunMultipleTimes(Runnable task, int max, int wait) { @@ -392,12 +419,6 @@ public final class Executor extends CommandArguments { return saveOutput().executeWithoutExitCodeCheck().getOutput(); } - private Executor setOutputControl(boolean set, OutputControlOption v) { - outputStreamsControl.stdout().set(set, v); - outputStreamsControl.stderr().set(set, v); - return this; - } - private Path executablePath() { if (directory == null || executable.isAbsolute() @@ -431,12 +452,8 @@ public final class Executor extends CommandArguments { builder.environment().put("TMP", winTmpDir); } - outputStreamsControl.applyTo(builder); - StringBuilder sb = new StringBuilder(getPrintableCommandLine()); - outputStreamsControl.describe().ifPresent(desc -> { - sb.append("; ").append(desc); - }); + sb.append("; ").append(commandOutputControl.description()); if (directory != null) { builder.directory(directory.toFile()); @@ -466,141 +483,31 @@ public final class Executor extends CommandArguments { }); } - trace("Execute " + sb.toString() + "..."); - Process process = builder.start(); - - var stdoutGobbler = CompletableFuture.>>supplyAsync(() -> { - try { - return processProcessStream(outputStreamsControl.stdout(), process.getInputStream()); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - }); - - var stderrGobbler = CompletableFuture.>>supplyAsync(() -> { - try { - return processProcessStream(outputStreamsControl.stderr(), process.getErrorStream()); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - }); - - final CommandOutput output; - - try { - output = combine(stdoutGobbler.join(), stderrGobbler.join()); - } catch (CompletionException ex) { - var cause = ex.getCause(); - switch (cause) { - case UncheckedIOException uioex -> { - throw uioex.getCause(); - } - default -> { - throw ExceptionBox.toUnchecked(ExceptionBox.unbox(cause)); - } - } - } - - final int exitCode = process.waitFor(); - trace("Done. Exit code: " + exitCode); - - return createResult(exitCode, output); + return execute(sb, commandOutputControl.createExecutable(builder)); } - private int runToolProvider(PrintStream out, PrintStream err) { + private Result runToolProvider() throws IOException, InterruptedException { final var sb = new StringBuilder(getPrintableCommandLine()); - outputStreamsControl.describe().ifPresent(desc -> { - sb.append("; ").append(desc); - }); - trace("Execute " + sb + "..."); - final int exitCode = toolProvider.run(out, err, args.toArray( - String[]::new)); - trace("Done. Exit code: " + exitCode); - return exitCode; + sb.append("; ").append(commandOutputControl.description()); + + return execute(sb, commandOutputControl.createExecutable(toolProvider, args.toArray(String[]::new))); } - private Result runToolProvider() throws IOException { - final var toolProviderStreamConfig = ToolProviderStreamConfig.create(outputStreamsControl); + private Result execute(StringBuilder traceMsg, CommandOutputControl.Executable exec) throws IOException, InterruptedException { + Objects.requireNonNull(traceMsg); - final var exitCode = runToolProvider(toolProviderStreamConfig); + trace("Execute " + traceMsg + "..."); - final var output = combine( - read(outputStreamsControl.stdout(), toolProviderStreamConfig.out()), - read(outputStreamsControl.stderr(), toolProviderStreamConfig.err())); - return createResult(exitCode, output); + var result = exec.execute(); + + trace("Done. Exit code: " + result.getExitCode()); + + return createResult(result); } - private int runToolProvider(ToolProviderStreamConfig cfg) throws IOException { - try { - return runToolProvider(cfg.out().ps(), cfg.err().ps()); - } finally { - cfg.out().ps().flush(); - cfg.err().ps().flush(); - } - } - - private static Optional> processProcessStream(OutputControl outputControl, InputStream in) throws IOException { - List outputLines = null; - try (final var bufReader = new BufferedReader(new InputStreamReader(in))) { - if (outputControl.dump() || outputControl.saveAll()) { - outputLines = bufReader.lines().toList(); - } else if (outputControl.saveFirstLine()) { - outputLines = Optional.ofNullable(bufReader.readLine()).map(List::of).orElseGet(List::of); - // Read all input, or the started process may exit with an error (cmd.exe does so). - bufReader.transferTo(Writer.nullWriter()); - } else { - // This should be empty input stream, fetch it anyway. - bufReader.transferTo(Writer.nullWriter()); - } - } finally { - if (outputControl.dump() && outputLines != null) { - outputLines.forEach(System.out::println); - if (outputControl.saveFirstLine()) { - outputLines = outputLines.stream().findFirst().map(List::of).orElseGet(List::of); - } - } - if (!outputControl.save()) { - outputLines = null; - } - } - return Optional.ofNullable(outputLines); - } - - private static Optional> read(OutputControl outputControl, CachingPrintStream cps) throws IOException { - final var bufferAsString = cps.bufferContents(); - try (final var bufReader = new BufferedReader(new StringReader(bufferAsString.orElse("")))) { - if (outputControl.saveFirstLine()) { - return Optional.of(bufReader.lines().findFirst().map(List::of).orElseGet(List::of)); - } else if (outputControl.saveAll()) { - return Optional.of(bufReader.lines().toList()); - } else if (bufferAsString.isPresent()) { - return Optional.of(List.of()); - } else { - return Optional.empty(); - } - } - } - - private CommandOutput combine(Optional> out, Optional> err) { - if (out.isEmpty() && err.isEmpty()) { - return new CommandOutput(); - } else if (out.isEmpty()) { - return new CommandOutput(err, -1); - } else if (err.isEmpty()) { - return new CommandOutput(out, Integer.MAX_VALUE); - } else { - final var combined = Stream.of(out, err).map(Optional::orElseThrow).flatMap(List::stream); - if (outputStreamsControl.stdout().saveFirstLine() && outputStreamsControl.stderr().saveFirstLine()) { - return new CommandOutput(Optional.of(combined.findFirst().map(List::of).orElseGet(List::of)), - Integer.min(1, out.orElseThrow().size())); - } else { - return new CommandOutput(Optional.of(combined.toList()), out.orElseThrow().size()); - } - } - } - - private Result createResult(int exitCode, CommandOutput output) { - return new Result(exitCode, output, this::getPrintableCommandLine); + private Result createResult(CommandOutputControl.Result baseResult) { + return new Result(baseResult.copyWithExecutableAttributes( + new ExecutableAttributes(baseResult.execAttrs(), getPrintableCommandLine()))); } public String getPrintableCommandLine() { @@ -618,359 +525,40 @@ public final class Executor extends CommandArguments { var cmdline = Stream.of(prefixCommandLineArgs(), List.of(exec), args).flatMap( List::stream).toList(); - return String.format(format, printCommandLine(cmdline), cmdline.size()); + return String.format(format, CommandLineFormat.DEFAULT.apply(cmdline), cmdline.size()); } - private static String printCommandLine(List cmdline) { - // Want command line printed in a way it can be easily copy/pasted - // to be executed manually - Pattern regex = Pattern.compile("\\s"); - return cmdline.stream().map( - v -> (v.isEmpty() || regex.matcher(v).find()) ? "\"" + v + "\"" : v).collect( - Collectors.joining(" ")); + private record ExecutableAttributes(CommandOutputControl.ExecutableAttributes base, String toStringValue) + implements CommandOutputControl.ExecutableAttributes { + + ExecutableAttributes { + Objects.requireNonNull(base); + if (toStringValue.isBlank()) { + throw new IllegalArgumentException(); + } + } + + @Override + public String toString() { + return toStringValue; + } + + @Override + public List commandLine() { + return base.commandLine(); + } } private static void trace(String msg) { TKit.trace(String.format("exec: %s", msg)); } - private static PrintStream nullPrintStream() { - return new PrintStream(OutputStream.nullOutputStream()); - } - - private record OutputStreamsControl(OutputControl stdout, OutputControl stderr) { - OutputStreamsControl { - Objects.requireNonNull(stdout); - Objects.requireNonNull(stderr); - } - - OutputStreamsControl() { - this(new OutputControl(), new OutputControl()); - } - - void applyTo(ProcessBuilder pb) { - pb.redirectOutput(stdout.asProcessBuilderRedirect()); - pb.redirectError(stderr.asProcessBuilderRedirect()); - } - - Optional describe() { - final List tokens = new ArrayList<>(); - if (stdout.save() || stderr.save()) { - streamsLabel("save ", true).ifPresent(tokens::add); - } - if (stdout.dump() || stderr.dump()) { - streamsLabel("inherit ", true).ifPresent(tokens::add); - } - streamsLabel("discard ", false).ifPresent(tokens::add); - if (tokens.isEmpty()) { - return Optional.empty(); - } else { - return Optional.of(String.join("; ", tokens)); - } - } - - Optional streamsLabel(String prefix, boolean negate) { - Objects.requireNonNull(prefix); - final var str = Stream.of(stdoutLabel(negate), stderrLabel(negate)) - .filter(Optional::isPresent) - .map(Optional::orElseThrow) - .collect(joining("+")); - if (str.isEmpty()) { - return Optional.empty(); - } else { - return Optional.of(prefix + str); - } - } - - private Optional stdoutLabel(boolean negate) { - if ((stdout.discard() && !negate) || (!stdout.discard() && negate)) { - return Optional.of("out"); - } else { - return Optional.empty(); - } - } - - private Optional stderrLabel(boolean negate) { - if ((stderr.discard() && !negate) || (!stderr.discard() && negate)) { - return Optional.of("err"); - } else { - return Optional.empty(); - } - } - } - - private record CachingPrintStream(PrintStream ps, Optional buf) { - CachingPrintStream { - Objects.requireNonNull(ps); - Objects.requireNonNull(buf); - } - - Optional bufferContents() { - return buf.map(ByteArrayOutputStream::toString); - } - - static Builder build() { - return new Builder(); - } - - static final class Builder { - - Builder save(boolean v) { - save = v; - return this; - } - - Builder discard(boolean v) { - discard = v; - return this; - } - - Builder dumpStream(PrintStream v) { - dumpStream = v; - return this; - } - - CachingPrintStream create() { - final Optional buf; - if (save && !discard) { - buf = Optional.of(new ByteArrayOutputStream()); - } else { - buf = Optional.empty(); - } - - final PrintStream ps; - if (buf.isPresent() && dumpStream != null) { - ps = new PrintStream(new TeeOutputStream(List.of(buf.orElseThrow(), dumpStream)), true, dumpStream.charset()); - } else if (!discard) { - ps = buf.map(PrintStream::new).or(() -> Optional.ofNullable(dumpStream)).orElseGet(Executor::nullPrintStream); - } else { - ps = nullPrintStream(); - } - - return new CachingPrintStream(ps, buf); - } - - private boolean save; - private boolean discard; - private PrintStream dumpStream; - } - } - - private record ToolProviderStreamConfig(CachingPrintStream out, CachingPrintStream err) { - ToolProviderStreamConfig { - Objects.requireNonNull(out); - Objects.requireNonNull(err); - } - - static ToolProviderStreamConfig create(OutputStreamsControl cfg) { - final var errCfgBuilder = cfg.stderr().buildCachingPrintStream(System.err); - if (cfg.stderr().dump() && cfg.stderr().save()) { - errCfgBuilder.dumpStream(System.out); - } - return new ToolProviderStreamConfig( - cfg.stdout().buildCachingPrintStream(System.out).create(), errCfgBuilder.create()); - } - } - - private static final class OutputControl { - - boolean save() { - return save.isPresent(); - } - - boolean saveAll() { - return save.orElse(null) == OutputControlOption.SAVE_ALL; - } - - boolean saveFirstLine() { - return save.orElse(null) == OutputControlOption.SAVE_FIRST_LINE; - } - - boolean discard() { - return discard || (!dump && save.isEmpty()); - } - - boolean dump() { - return !discard && dump; - } - - OutputControl dump(boolean v) { - this.dump = v; - return this; - } - - OutputControl discard(boolean v) { - this.discard = v; - return this; - } - - OutputControl saveAll(boolean v) { - if (v) { - save = Optional.of(OutputControlOption.SAVE_ALL); - } else { - save = Optional.empty(); - } - return this; - } - - OutputControl saveFirstLine(boolean v) { - if (v) { - save = Optional.of(OutputControlOption.SAVE_FIRST_LINE); - } else { - save = Optional.empty(); - } - return this; - } - - OutputControl set(boolean set, OutputControlOption v) { - switch (v) { - case DUMP -> dump(set); - case SAVE_ALL -> saveAll(set); - case SAVE_FIRST_LINE -> saveFirstLine(set); - } - return this; - } - - ProcessBuilder.Redirect asProcessBuilderRedirect() { - if (discard()) { - return ProcessBuilder.Redirect.DISCARD; - } else if (dump && !save()) { - return ProcessBuilder.Redirect.INHERIT; - } else { - return ProcessBuilder.Redirect.PIPE; - } - } - - CachingPrintStream.Builder buildCachingPrintStream(PrintStream dumpStream) { - Objects.requireNonNull(dumpStream); - final var builder = CachingPrintStream.build().save(save()).discard(discard()); - if (dump()) { - builder.dumpStream(dumpStream); - } - return builder; - } - - private boolean dump; - private boolean discard; - private Optional save = Optional.empty(); - } - - private static final class TeeOutputStream extends OutputStream { - - public TeeOutputStream(Iterable streams) { - streams.forEach(Objects::requireNonNull); - this.streams = streams; - } - - @Override - public void write(int b) throws IOException { - for (final var out : streams) { - out.write(b); - } - } - - @Override - public void write(byte[] b) throws IOException { - for (final var out : streams) { - out.write(b); - } - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - for (final var out : streams) { - out.write(b, off, len); - } - } - - @Override - public void flush() throws IOException { - forEach(OutputStream::flush); - } - - @Override - public void close() throws IOException { - forEach(OutputStream::close); - } - - private void forEach(OutputStreamConsumer c) throws IOException { - IOException firstEx = null; - for (final var out : streams) { - try { - c.accept(out); - } catch (IOException e) { - if (firstEx == null) { - firstEx = e; - } - } - } - if (firstEx != null) { - throw firstEx; - } - } - - @FunctionalInterface - private static interface OutputStreamConsumer { - void accept(OutputStream out) throws IOException; - } - - private final Iterable streams; - } - - private static final class CommandOutput { - CommandOutput(Optional> lines, int stdoutLineCount) { - this.lines = Objects.requireNonNull(lines); - this.stdoutLineCount = stdoutLineCount; - } - - CommandOutput() { - this(Optional.empty(), 0); - } - - Optional> lines() { - return lines; - } - - Optional> stdoutLines() { - if (lines.isEmpty() || stdoutLineCount < 0) { - return Optional.empty(); - } - - final var theLines = lines.orElseThrow(); - if (stdoutLineCount == theLines.size()) { - return lines; - } else { - return Optional.of(theLines.subList(0, Integer.min(stdoutLineCount, theLines.size()))); - } - } - - Optional> stderrLines() { - if (lines.isEmpty() || stdoutLineCount > lines.orElseThrow().size()) { - return Optional.empty(); - } else if (stdoutLineCount == 0) { - return lines; - } else { - final var theLines = lines.orElseThrow(); - return Optional.of(theLines.subList(stdoutLineCount, theLines.size())); - } - } - - private final Optional> lines; - private final int stdoutLineCount; - - static final CommandOutput EMPTY = new CommandOutput(); - } - private ToolProvider toolProvider; private Path executable; - private OutputStreamsControl outputStreamsControl; + private final CommandOutputControl commandOutputControl = new CommandOutputControl(); private Path directory; private Set removeEnvVars = new HashSet<>(); private Map setEnvVars = new HashMap<>(); private boolean winEnglishOutput; private String winTmpDir = null; - - private static enum OutputControlOption { - SAVE_ALL, SAVE_FIRST_LINE, DUMP - } } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java index 38091cb3452..c5c4f87b097 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ -52,6 +52,8 @@ import java.util.Optional; import java.util.OptionalInt; import java.util.Set; import java.util.TreeSet; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; @@ -780,10 +782,9 @@ public class JPackageCommand extends CommandArguments { } /** - * Starts a new thread. In this thread calls - * {@link #useToolProviderByDefault(ToolProvider)} with the specified - * {@code jpackageToolProvider} and then calls {@code workload.run()}. Joins the - * thread. + * In a separate thread calls {@link #useToolProviderByDefault(ToolProvider)} + * with the specified {@code jpackageToolProvider} and then calls + * {@code workload.run()}. Joins the thread. *

    * The idea is to run the {@code workload} in the context of the specified * jpackage {@code ToolProvider} without altering the global variable holding @@ -794,13 +795,23 @@ public class JPackageCommand extends CommandArguments { * @param jpackageToolProvider jpackage {@code ToolProvider} * @param workload the workload to run */ - public static void withToolProvider(ToolProvider jpackageToolProvider, Runnable workload) { - Objects.requireNonNull(jpackageToolProvider); + public static void withToolProvider(Runnable workload, ToolProvider jpackageToolProvider) { Objects.requireNonNull(workload); - ThrowingRunnable.toRunnable(Thread.ofVirtual().start(() -> { + Objects.requireNonNull(jpackageToolProvider); + + CompletableFuture.runAsync(() -> { + var oldValue = defaultToolProvider.get(); useToolProviderByDefault(jpackageToolProvider); - workload.run(); - })::join).run(); + try { + workload.run(); + } finally { + defaultToolProvider.set(oldValue); + } + // Run the future in a new native thread. Don't run it in a virtual/pooled thread. + // Pooled and/or virtual threads are problematic when used with inheritable thread-local variables. + // TKit class depends on such a variable, which results in intermittent test failures + // if the default executor runs this future. + }, Executors.newThreadPerTaskExecutor(Thread.ofPlatform().factory())).join(); } public JPackageCommand useToolProvider(boolean v) { @@ -1022,7 +1033,7 @@ public class JPackageCommand extends CommandArguments { outputValidator.accept(result.getOutput().iterator()); } - if (result.exitCode() == 0 && expectedExitCode.isPresent()) { + if (result.getExitCode() == 0 && expectedExitCode.isPresent()) { verifyActions.run(); } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherVerifier.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherVerifier.java index 15d96311d98..f9fcfb905af 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherVerifier.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherVerifier.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -39,7 +39,6 @@ import java.util.function.BiFunction; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; -import javax.xml.parsers.ParserConfigurationException; import jdk.jpackage.internal.resources.ResourceLocator; import jdk.jpackage.internal.util.PListReader; import jdk.jpackage.internal.util.function.ThrowingBiConsumer; @@ -367,7 +366,7 @@ public final class LauncherVerifier { } } - private void verifyMacEntitlements(JPackageCommand cmd) throws ParserConfigurationException, SAXException, IOException { + private void verifyMacEntitlements(JPackageCommand cmd) throws SAXException, IOException { Path launcherPath = cmd.appLauncherPath(name); var entitlements = MacSignVerify.findEntitlements(launcherPath); @@ -457,8 +456,10 @@ public final class LauncherVerifier { private static final class DefaultEntitlements { private static Map loadFromResources(String resourceName) { return ThrowingSupplier.toSupplier(() -> { - var bytes = ResourceLocator.class.getResourceAsStream(resourceName).readAllBytes(); - return new PListReader(bytes).toMap(true); + try (var in = ResourceLocator.class.getResourceAsStream(resourceName)) { + var bytes = in.readAllBytes(); + return new PListReader(bytes).toMap(true); + } }).get(); } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LinuxHelper.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LinuxHelper.java index 3b02a3f6a69..78562b2ed26 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LinuxHelper.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LinuxHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ -723,7 +723,9 @@ public final class LinuxHelper { private static Optional queryMimeTypeDefaultHandler(String mimeType) { return Executor.of("xdg-mime", "query", "default", mimeType) - .discardStderr().saveFirstLineOfOutput().execute().findFirstLineOfOutput(); + .discardStderr() + .saveFirstLineOfOutput() + .execute().getOutput().stream().findFirst(); } private static void verifyIconInScriptlet(Scriptlet scriptletType, diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java index 92d9fa0bd44..6a5be77457a 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ -49,11 +49,11 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.Set; +import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; @@ -66,10 +66,10 @@ import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; -import jdk.jpackage.internal.RetryExecutor; import jdk.jpackage.internal.util.FileUtils; import jdk.jpackage.internal.util.PListReader; import jdk.jpackage.internal.util.PathUtils; +import jdk.jpackage.internal.util.RetryExecutor; import jdk.jpackage.internal.util.XmlUtils; import jdk.jpackage.internal.util.function.ThrowingConsumer; import jdk.jpackage.internal.util.function.ThrowingSupplier; @@ -90,38 +90,34 @@ public final class MacHelper { final var mountRoot = TKit.createTempDirectory("mountRoot"); // Explode DMG assuming this can require interaction, thus use `yes`. - String attachCMD[] = { - "sh", "-c", - String.join(" ", "yes", "|", "/usr/bin/hdiutil", "attach", - JPackageCommand.escapeAndJoin(cmd.outputBundle().toString()), - "-mountroot", PathUtils.normalizedAbsolutePathString(mountRoot), - "-nobrowse", "-plist")}; - RetryExecutor attachExecutor = new RetryExecutor(); - try { - // 10 times with 6 second delays. - attachExecutor.setMaxAttemptsCount(10) - .setAttemptTimeoutMillis(6000) - .setWriteOutputToFile(true) - .saveOutput(true) - .execute(attachCMD); - } catch (IOException ex) { - throw new RuntimeException(ex); - } + final var attachStdout = Executor.of("sh", "-c", String.join(" ", + "yes", + "|", + "/usr/bin/hdiutil", + "attach", + JPackageCommand.escapeAndJoin(cmd.outputBundle().toString()), + "-mountroot", PathUtils.normalizedAbsolutePathString(mountRoot), + "-nobrowse", + "-plist" + )).saveOutput().storeOutputInFiles().executeAndRepeatUntilExitCode(0, 10, 6).stdout(); - Path mountPoint = null; + final Path mountPoint; + + boolean mountPointInitialized = false; try { // One of "dict" items of "system-entities" array property should contain "mount-point" string property. - mountPoint = readPList(attachExecutor.getOutput()).queryArrayValue("system-entities", false).map(PListReader.class::cast).map(dict -> { - try { - return dict.queryValue("mount-point"); - } catch (NoSuchElementException ex) { - return (String)null; - } - }).filter(Objects::nonNull).map(Path::of).findFirst().orElseThrow(); + mountPoint = readPList(attachStdout).queryArrayValue("system-entities", false) + .map(PListReader.class::cast) + .map(dict -> { + return dict.findValue("mount-point"); + }) + .filter(Optional::isPresent).map(Optional::get) + .map(Path::of).findFirst().orElseThrow(); + mountPointInitialized = true; } finally { - if (mountPoint == null) { + if (!mountPointInitialized) { TKit.trace("Unexpected plist file missing `system-entities` array:"); - attachExecutor.getOutput().forEach(TKit::trace); + attachStdout.forEach(TKit::trace); TKit.trace("Done"); } } @@ -138,39 +134,27 @@ public final class MacHelper { ThrowingConsumer.toConsumer(consumer).accept(childPath); } } finally { - String detachCMD[] = { - "/usr/bin/hdiutil", - "detach", - "-verbose", - mountPoint.toAbsolutePath().toString()}; // "hdiutil detach" might not work right away due to resource busy error, so // repeat detach several times. - RetryExecutor detachExecutor = new RetryExecutor(); - // Image can get detach even if we got resource busy error, so stop - // trying to detach it if it is no longer attached. - final Path mp = mountPoint; - detachExecutor.setExecutorInitializer(exec -> { - if (!Files.exists(mp)) { - detachExecutor.abort(); + new RetryExecutor(RuntimeException.class).setExecutable(context -> { + var exec = Executor.of("/usr/bin/hdiutil", "detach").storeOutputInFiles(); + if (context.isLastAttempt()) { + // The last attempt, force detach. + exec.addArgument("-force"); } - }); - try { - // 10 times with 6 second delays. - detachExecutor.setMaxAttemptsCount(10) - .setAttemptTimeoutMillis(6000) - .setWriteOutputToFile(true) - .saveOutput(true) - .execute(detachCMD); - } catch (IOException ex) { - if (!detachExecutor.isAborted()) { - // Now force to detach if it still attached - if (Files.exists(mountPoint)) { - Executor.of("/usr/bin/hdiutil", "detach", - "-force", "-verbose") - .addArgument(mountPoint).execute(); - } + exec.addArgument(mountPoint); + + // The image can get detached even if we get a resource busy error, + // so execute the detach command without checking the exit code. + var result = exec.executeWithoutExitCodeCheck(); + + if (result.getExitCode() == 0 || !Files.exists(mountPoint)) { + // Detached successfully! + return null; + } else { + throw new RuntimeException(String.format("[%s] mount point still attached", mountPoint)); } - } + }).setMaxAttemptsCount(10).setAttemptTimeout(6, TimeUnit.SECONDS).execute(); } } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSign.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSign.java index 15249c51887..70de6ba92af 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSign.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSign.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -1172,7 +1172,7 @@ public final class MacSign { "-c", certFile.normalize().toString(), "-k", keychain.name(), "-p", resolvedCertificateRequest.installed().type().verifyPolicy()).saveOutput(!quite).executeWithoutExitCodeCheck(); - if (result.exitCode() == 0) { + if (result.getExitCode() == 0) { return VerifyStatus.VERIFY_OK; } } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSignVerify.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSignVerify.java index 1f37829791e..0ecfd4c3432 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSignVerify.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSignVerify.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -94,7 +94,7 @@ public final class MacSignVerify { public static Optional findEntitlements(Path path) { final var exec = Executor.of("/usr/bin/codesign", "-d", "--entitlements", "-", "--xml", path.toString()).saveOutput().dumpOutput(); final var result = exec.execute(); - var xml = result.stdout().getOutput(); + var xml = result.stdout(); if (xml.isEmpty()) { return Optional.empty(); } else { @@ -137,7 +137,7 @@ public final class MacSignVerify { public static Optional findSpctlSignOrigin(SpctlType type, Path path) { final var exec = Executor.of("/usr/sbin/spctl", "-vv", "--raw", "--assess", "--type", type.value(), path.toString()).saveOutput().discardStderr(); final var result = exec.executeWithoutExitCodeCheck(); - TKit.assertTrue(Set.of(0, 3).contains(result.exitCode()), + TKit.assertTrue(Set.of(0, 3).contains(result.getExitCode()), String.format("Check exit code of command %s is either 0 or 3", exec.getPrintableCommandLine())); return toSupplier(() -> { try { @@ -173,7 +173,7 @@ public final class MacSignVerify { } else if (result.getExitCode() == 1 && result.getFirstLineOfOutput().endsWith("code object is not signed at all")) { return Optional.empty(); } else { - reportUnexpectedCommandOutcome(exec.getPrintableCommandLine(), result); + reportUnexpectedCommandOutcome(result); return null; // Unreachable } } @@ -205,7 +205,7 @@ public final class MacSignVerify { TKit.trace("Try /usr/bin/codesign again with `sudo`"); assertSigned(path, true); } else { - reportUnexpectedCommandOutcome(exec.getPrintableCommandLine(), result); + reportUnexpectedCommandOutcome(result); } } @@ -264,13 +264,13 @@ public final class MacSignVerify { return signIdentities; } catch (Exception ex) { ex.printStackTrace(); - reportUnexpectedCommandOutcome(exec.getPrintableCommandLine(), result); + reportUnexpectedCommandOutcome(result); return null; // Unreachable } } else if (result.getExitCode() == 1 && result.getOutput().getLast().endsWith("Status: no signature")) { return List.of(); } else { - reportUnexpectedCommandOutcome(exec.getPrintableCommandLine(), result); + reportUnexpectedCommandOutcome(result); return null; // Unreachable } } @@ -282,14 +282,13 @@ public final class MacSignVerify { } } - private static void reportUnexpectedCommandOutcome(String printableCommandLine, Executor.Result result) { - Objects.requireNonNull(printableCommandLine); + private static void reportUnexpectedCommandOutcome(Executor.Result result) { Objects.requireNonNull(result); TKit.trace(String.format("Command %s exited with exit code %d and the following output:", - printableCommandLine, result.getExitCode())); + result.getPrintableCommandLine(), result.getExitCode())); result.getOutput().forEach(TKit::trace); TKit.trace("Done"); - TKit.assertUnexpected(String.format("Outcome of command %s", printableCommandLine)); + TKit.assertUnexpected(String.format("Outcome of command %s", result.getPrintableCommandLine())); } private static final Pattern SIGN_IDENTITY_NAME_REGEXP = Pattern.compile("^\\s+\\d+\\.\\s+(.*)$"); diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java index 72b5dbc578b..f9fbf285b49 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, 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 @@ -81,16 +81,16 @@ public class WindowsHelper { msiLog.ifPresent(v -> misexec.clearArguments().addArguments(origArgs).addArgument("/L*v").addArgument(v)); result = misexec.executeWithoutExitCodeCheck(); - if (result.exitCode() == 1605) { + if (result.getExitCode() == 1605) { // ERROR_UNKNOWN_PRODUCT, attempt to uninstall not installed // package - return result.exitCode(); + return result.getExitCode(); } // The given Executor may either be of an msiexec command or an // unpack.bat script containing the msiexec command. In the later // case, when misexec returns 1618, the unpack.bat may return 1603 - if ((result.exitCode() == 1618) || (result.exitCode() == 1603 && isUnpack)) { + if ((result.getExitCode() == 1618) || (result.getExitCode() == 1603 && isUnpack)) { // Another installation is already in progress. // Wait a little and try again. Long timeout = 1000L * (attempt + 3); // from 3 to 10 seconds @@ -100,7 +100,7 @@ public class WindowsHelper { break; } - return result.exitCode(); + return result.getExitCode(); } static PackageHandlers createMsiPackageHandlers(boolean createMsiLog) { @@ -462,7 +462,7 @@ public class WindowsHelper { var status = Executor.of("reg", "query", keyPath, "/v", valueName) .saveOutput() .executeWithoutExitCodeCheck(); - if (status.exitCode() == 1) { + if (status.getExitCode() == 1) { // Should be the case of no such registry value or key String lookupString = "ERROR: The system was unable to find the specified registry key or value."; TKit.assertTextStream(lookupString) diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandAction.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandAction.java new file mode 100644 index 00000000000..d9ab38e006a --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandAction.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.io.PrintStream; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * An action. + */ +@FunctionalInterface +public interface CommandAction { + + public record Context(PrintStream out, PrintStream err, List args) { + + public Context { + Objects.requireNonNull(out); + Objects.requireNonNull(err); + args.forEach(Objects::requireNonNull); + } + + public Optional findOptionValue(String option) { + Objects.requireNonNull(option); + var idx = args.indexOf(option); + if (idx >= 0 && idx + 1 < args.size()) { + return Optional.of(args.get(idx + 1)); + } else { + return Optional.empty(); + } + } + + public String optionValue(String option) { + return findOptionValue(option).orElseThrow(() -> { + throw new MockIllegalStateException(String.format("No option %s", option)); + }); + } + + public MockIllegalStateException unexpectedArguments() { + return new MockIllegalStateException(String.format("Unexpected arguments: %s", args)); + } + } + + /** + * Runs the action in the given context. + * + * @param context the context + * @return an {@code Optional} wrapping the exit code, indicating it is the last + * action in the sequence or an empty {@code Optional} otherwise + * @throws Exception simulates a failure + * @throws MockIllegalStateException if error in internal mock logic occurred. + * E.g.: if the action was called unexpectedly + */ + Optional run(Context context) throws Exception, MockIllegalStateException; +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandActionSpec.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandActionSpec.java new file mode 100644 index 00000000000..25814d84205 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandActionSpec.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.util.Objects; +import java.util.Optional; +import jdk.jpackage.internal.util.function.ThrowingSupplier; +import jdk.jpackage.internal.util.function.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingRunnable; + +/** + * Specification of a {@link CommandAction}. + *

    + * Comprised of a human-readable description and an associated action. + */ +public interface CommandActionSpec { + + String description(); + CommandAction action(); + + public static CommandActionSpec create(String description, CommandAction action) { + return new Internal.DefaultCommandActionSpec(description, action); + } + + public static CommandActionSpec create(String description, ThrowingSupplier action) { + Objects.requireNonNull(action); + return create(description, _ -> { + return Optional.of(action.get()); + }); + } + + public static CommandActionSpec create(String description, ThrowingRunnable action) { + Objects.requireNonNull(action); + return create(description, _ -> { + action.run(); + return Optional.empty(); + }); + } + + @SuppressWarnings("overloads") + public static CommandActionSpec create(String description, ThrowingConsumer action) { + Objects.requireNonNull(action); + return create(description, context -> { + action.accept(context); + return Optional.empty(); + }); + } + + final class Internal { + + private Internal() { + } + + private record DefaultCommandActionSpec(String description, CommandAction action) implements CommandActionSpec { + DefaultCommandActionSpec { + Objects.requireNonNull(description); + Objects.requireNonNull(action); + } + + @Override + public String toString() { + return description(); + } + } + } +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandActionSpecs.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandActionSpecs.java new file mode 100644 index 00000000000..e89e458c02d --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandActionSpecs.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.stream.Stream; +import jdk.jpackage.internal.util.function.ExceptionBox; + +/** + * A sequence of actions. + */ +public record CommandActionSpecs(List specs) { + + public CommandActionSpecs { + Objects.requireNonNull(specs); + } + + public CommandActionSpecs andThen(CommandActionSpecs other) { + return build().append(this).append(other).create(); + } + + public Stream actions() { + return specs.stream().map(CommandActionSpec::action); + } + + public CommandMock.Builder toCommandMockBuilder() { + return new CommandMock.Builder().mutate(builder -> { + builder.actions().append(this); + }); + } + + @Override + public String toString() { + return specs.toString(); + } + + public static Builder build() { + return new Builder(); + } + + public static final class Builder { + + public CommandActionSpecs create() { + return new CommandActionSpecs(List.copyOf(specs)); + } + + public Builder stdout(List content) { + Objects.requireNonNull(content); + return action(CommandActionSpec.create(String.format("%s>>1", content), context -> { + var out = context.out(); + content.forEach(out::println); + })); + } + + public Builder stdout(String... str) { + return stdout(List.of(str)); + } + + public Builder stderr(List content) { + Objects.requireNonNull(content); + return action(CommandActionSpec.create(String.format("%s>>2", content), context -> { + var err = context.err(); + content.forEach(err::println); + })); + } + + public Builder stderr(String... str) { + return stderr(List.of(str)); + } + + public Builder printToStdout(List content) { + Objects.requireNonNull(content); + return action(CommandActionSpec.create(String.format("%s(no-eol)>>1", content), context -> { + var out = context.out(); + content.forEach(out::print); + })); + } + + public Builder printToStdout(String... str) { + return printToStdout(List.of(str)); + } + + public Builder printToStderr(List content) { + Objects.requireNonNull(content); + return action(CommandActionSpec.create(String.format("%s(no-eol)>>2", content), context -> { + var err = context.err(); + content.forEach(err::print); + })); + } + + public Builder printToStderr(String... str) { + return printToStderr(List.of(str)); + } + + public Builder exit(int exitCode) { + return action(CommandActionSpec.create(String.format("exit(%d)", exitCode), () -> { + return exitCode; + })); + } + + public Builder exit() { + return exit(0); + } + + public Builder exit(CommandMockExit exit) { + switch (exit) { + case SUCCEED -> { + return exit(); + } + case EXIT_1 -> { + return exit(1); + } + case THROW_MOCK_IO_EXCEPTION -> { + return action(CommandActionSpec.create("", () -> { + throw new MockingToolProvider.RethrowableException(new MockIOException("Kaput!")); + })); + } + default -> { + throw ExceptionBox.reachedUnreachable(); + } + } + } + + public Builder mutate(Consumer mutator) { + mutator.accept(this); + return this; + } + + public Builder append(Builder other) { + return append(other.specs); + } + + public Builder append(CommandActionSpecs other) { + return append(other.specs()); + } + + public Builder append(List other) { + specs.addAll(other); + return this; + } + + public Builder action(CommandActionSpec v) { + specs.add(Objects.requireNonNull(v)); + return this; + } + + public Builder copy() { + return new Builder().append(this); + } + + public CommandMock.Builder toCommandMockBuilder() { + return new CommandMock.Builder().mutate(builder -> { + builder.actions(this); + }); + } + + private final List specs = new ArrayList<>(); + } + + public static final CommandActionSpecs UNREACHABLE = new CommandActionSpecs(List.of()); +} + diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandMock.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandMock.java new file mode 100644 index 00000000000..bb3980fd4e0 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandMock.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.stream.IntStream; + +/** + * Command mock. + */ +public sealed interface CommandMock permits ToolProviderCommandMock, VerbatimCommandMock, CompletableCommandMock { + + public static CommandMock ioerror(String name) { + return CommandActionSpecs.build() + .exit(CommandMockExit.THROW_MOCK_IO_EXCEPTION) + .toCommandMockBuilder().name(Objects.requireNonNull(name)).create(); + } + + public static CommandMock fail(String name) { + return CommandActionSpecs.build() + .exit(CommandMockExit.EXIT_1) + .toCommandMockBuilder().name(Objects.requireNonNull(name)).create(); + } + + public static CommandMock succeed(String name) { + return CommandActionSpecs.build() + .exit(CommandMockExit.SUCCEED) + .toCommandMockBuilder().name(Objects.requireNonNull(name)).create(); + } + + public static CommandMock unreachable() { + return MockingToolProvider.UNREACHABLE; + } + + public final class Builder { + + public ToolProviderCommandMock create() { + + var actionSpecs = Optional.ofNullable(scriptBuilder) + .map(CommandActionSpecs.Builder::create) + .orElse(CommandActionSpecs.UNREACHABLE); + if (actionSpecs.equals(CommandActionSpecs.UNREACHABLE)) { + return (ToolProviderCommandMock)unreachable(); + } + + var theName = Optional.ofNullable(name).orElse("mock"); + var script = actionSpecs.actions().toList(); + switch (repeat) { + case 0 -> { + return MockingToolProvider.create(theName, script); + } + case -1 -> { + return MockingToolProvider.createLoop(theName, script); + } + default -> { + var repeatedScript = IntStream.rangeClosed(0, repeat) + .mapToObj(i -> script) + .flatMap(List::stream) + .toList(); + return MockingToolProvider.create(theName, repeatedScript); + } + } + } + + public Builder name(String v) { + name = v; + return this; + } + + public Builder mutate(Consumer mutator) { + mutator.accept(this); + return this; + } + + public Builder repeat(int v) { + repeat = Integer.max(-1, v); + return this; + } + + public Builder noRepeats() { + return repeat(0); + } + + public Builder repeatInfinitely() { + return repeat(-1); + } + + public Builder actions(CommandActionSpecs.Builder v) { + scriptBuilder = Optional.ofNullable(v).orElseGet(CommandActionSpecs::build); + return this; + } + + public CommandActionSpecs.Builder actions() { + if (scriptBuilder == null) { + scriptBuilder = CommandActionSpecs.build(); + } + return scriptBuilder; + } + + private String name; + private int repeat = -1; + private CommandActionSpecs.Builder scriptBuilder; + } + +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandMockExit.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandMockExit.java new file mode 100644 index 00000000000..26bc8ba757b --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandMockExit.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import jdk.jpackage.internal.util.CommandOutputControl; + +public enum CommandMockExit { + /** + * Exit normally with "0" exit code. + */ + SUCCEED(true, true), + /** + * Exit normally with "1" exit code. + */ + EXIT_1(false, true), + /** + * Throw {@link MockIOException}. This simulates a situation when an I/O error + * occurs starting a subprocess with {@link ProcessBuilder#start()}. + * {@link CommandOutputControl.Executable#execute()} will handle I/O errors and + * let them out. + */ + THROW_MOCK_IO_EXCEPTION(false, false), + ; + + CommandMockExit(boolean succeed, boolean exitNormally) { + this.succeed = succeed; + this.exitNormally = exitNormally; + } + + public boolean succeed() { + return succeed; + } + + public boolean exitNormally() { + return exitNormally; + } + + private final boolean succeed; + private final boolean exitNormally; +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandMockSpec.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandMockSpec.java new file mode 100644 index 00000000000..2572309e751 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandMockSpec.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.nio.file.Path; +import java.util.Objects; + +/** + * Specification of a {@link CommandMock}. + */ +public record CommandMockSpec(Path name, Path mockName, CommandActionSpecs actions) { + + public CommandMockSpec { + Objects.requireNonNull(name); + Objects.requireNonNull(mockName); + Objects.requireNonNull(actions); + } + + public CommandMockSpec(Path name, CommandActionSpecs actions) { + this(name, Path.of(name.toString() + "-mock"), actions); + } + + public CommandMockSpec(String name, CommandActionSpecs actions) { + this(Path.of(name), actions); + } + + public CommandMockSpec(String name, String mockName, CommandActionSpecs actions) { + this(Path.of(name), Path.of(mockName), actions); + } + + public CommandMock.Builder toCommandMockBuilder() { + return actions.toCommandMockBuilder().name(mockName.toString()); + } + + public boolean isDefaultMockName() { + return (name.getFileName().toString() + "-mock").equals(mockName.getFileName().toString()); + } + + @Override + public String toString() { + return String.format("mock-of(%s)%s", name, actions); + } +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CompletableCommandMock.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CompletableCommandMock.java new file mode 100644 index 00000000000..c9441e038b3 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CompletableCommandMock.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +/** + * Command mock that runs a finite sequence of actions. + */ +public sealed interface CompletableCommandMock extends CommandMock permits ToolProviderCompletableCommandMock { + + boolean completed(); +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockIOException.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockIOException.java new file mode 100644 index 00000000000..3b299f05d3f --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockIOException.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.io.IOException; + +/** + * Simulates I/O error. + * + * @see CommandMockExit#THROW_MOCK_IO_EXCEPTION + */ +public final class MockIOException extends IOException { + + MockIOException(String msg) { + super(msg); + } + + private static final long serialVersionUID = 1L; +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockIllegalStateException.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockIllegalStateException.java new file mode 100644 index 00000000000..1817587364a --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockIllegalStateException.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +/** + * Indicates command mock internal error. + */ +public final class MockIllegalStateException extends IllegalStateException { + + public MockIllegalStateException(String msg) { + super(msg); + } + + private static final long serialVersionUID = 1L; +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockingToolProvider.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockingToolProvider.java new file mode 100644 index 00000000000..f8c04cc3927 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockingToolProvider.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.io.PrintStream; +import java.io.PrintWriter; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Objects; +import jdk.jpackage.internal.util.function.ExceptionBox; + +/** + * A command simulator implementing {@code ToolProvider}. + *

    + * Iterates over actions and runs them. Each action is write to stdout/stderr, create a file, etc. + */ +abstract sealed class MockingToolProvider implements ToolProviderCommandMock { + + MockingToolProvider(String name, Iterator actionIter) { + this.name = Objects.requireNonNull(name); + this.actionIter = Objects.requireNonNull(actionIter); + } + + static ToolProviderCommandMock createLoop(String name, Iterable actions) { + return new MockingToolProvider.NonCompletable(name, actions); + } + + static MockingToolProvider create(String name, Iterable actions) { + return new MockingToolProvider.Completable(name, actions); + } + + public boolean completed() { + return !actionIter.hasNext(); + } + + @Override + public String name() { + return name; + } + + @Override + public int run(PrintStream out, PrintStream err, String... args) { + var context = new CommandAction.Context(out, err, List.of(args)); + try { + while (actionIter.hasNext()) { + var action = actionIter.next(); + var reply = action.run(context); + if (reply.isPresent()) { + return reply.get(); + } + } + } catch (RethrowableException ex) { + // Let the checked exception out. + throwAny(ex.getCause()); + // Unreachable + return 0; + } catch (Exception ex) { + throw ExceptionBox.toUnchecked(ex); + } + + // No more actions to execute, but still expect it to keep going. + throw new MockIllegalStateException("No more actions to execute"); + } + + @Override + public int run(PrintWriter out, PrintWriter err, String... args) { + throw new UnsupportedOperationException(); + } + + static final class RethrowableException extends Exception { + + RethrowableException(Exception ex) { + super(Objects.requireNonNull(ex)); + } + + private static final long serialVersionUID = 1L; + } + + @SuppressWarnings("unchecked") + private static void throwAny(Throwable e) throws E { + throw (E)e; + } + + private static final class LoopIterator implements Iterator { + + LoopIterator(Iterable iterable) { + this.iterable = Objects.requireNonNull(iterable); + rewind(); + } + + @Override + public boolean hasNext() { + return iter != null; + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } else if (iter.hasNext()) { + return iter.next(); + } else { + rewind(); + if (!hasNext()) { + throw new NoSuchElementException(); + } else { + return iter.next(); + } + } + } + + private void rewind() { + iter = Objects.requireNonNull(iterable.iterator()); + if (!iter.hasNext()) { + iter = null; + } + } + + private final Iterable iterable; + private Iterator iter; + } + + static final class NonCompletable extends MockingToolProvider { + + NonCompletable(String name, Iterable actions) { + super(name, new LoopIterator<>(actions)); + } + + } + + static final class Completable extends MockingToolProvider implements ToolProviderCompletableCommandMock { + + Completable(String name, Iterable actions) { + super(name, actions.iterator()); + } + + } + + private final String name; + private final Iterator actionIter; + + static ToolProviderCommandMock UNREACHABLE = new MockingToolProvider.NonCompletable("", List.of()); +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/Script.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/Script.java new file mode 100644 index 00000000000..bc51d2b69f8 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/Script.java @@ -0,0 +1,297 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Stream; +import jdk.jpackage.internal.util.IdentityWrapper; + +/** + * Script of command mocks. + */ +public interface Script { + + /** + * Returns a command mock for the given command line. + * + * @param cmdline the command line for which to look up a command mock + * + * @return a command mock matching the given command line + * @throws ScriptException if an internal script error occures + */ + CommandMock map(List cmdline) throws ScriptException; + + /** + * Returns command mocks registered with this object that have not completed yet. + * + * @See {@link CompletableCommandMock#completed()} + * + * @return the command mocks registered with this object that have not completed yet + */ + Collection incompleteMocks(); + + public static Builder build() { + return new Builder(); + } + + public static Predicate> cmdlinePredicate( + Predicate pred, + Function conv, + Function, Stream> toStream) { + + Objects.requireNonNull(pred); + Objects.requireNonNull(conv); + Objects.requireNonNull(toStream); + + return cmdline -> { + return toStream.apply(cmdline).map(conv).filter(pred).findFirst().isPresent(); + }; + } + + public static Predicate> cmdlineContains(String arg) { + return cmdlinePredicate(Predicate.isEqual(Objects.requireNonNull(arg)), x -> x, List::stream); + } + + public static Predicate> cmdlineContains(Path arg) { + return cmdlinePredicate(Predicate.isEqual(Objects.requireNonNull(arg)), Path::of, List::stream); + } + + public static Predicate> cmdlineStartsWith(String arg) { + return cmdlinePredicate(Predicate.isEqual(Objects.requireNonNull(arg)), x -> x, cmdline -> { + return cmdline.stream().limit(1); + }); + } + + public static Predicate> cmdlineStartsWith(Path arg) { + return cmdlinePredicate(Predicate.isEqual(Objects.requireNonNull(arg)), Path::of, cmdline -> { + return cmdline.stream().limit(1); + }); + } + + public final class ScriptException extends RuntimeException { + + ScriptException(RuntimeException cause) { + super(Objects.requireNonNull(cause)); + } + + ScriptException(String msg) { + super(Objects.requireNonNull(msg)); + } + + private static final long serialVersionUID = 1L; + } + + public final class Builder { + + public Script createSequence() { + return new SequenceScript(List.copyOf(instructions), completableMocks()); + } + + public Script createLoop() { + return new LoopScript(List.copyOf(instructions), completableMocks()); + } + + public Builder map(Predicate> pred, CommandMock mock) { + Objects.requireNonNull(pred); + Objects.requireNonNull(mock); + if (mock instanceof CompletableCommandMock completable) { + completableMocks.add(new IdentityWrapper<>(completable)); + } + instruction(cmdline -> { + if (pred.test(cmdline)) { + return new CommandMockResult(Optional.of(mock)); + } else { + return new CommandMockResult(Optional.empty()); + } + }); + return this; + } + + public Builder map(Predicate> pred, CommandMock.Builder mock) { + Optional.ofNullable(commandMockBuilderMutator).ifPresent(mock::mutate); + return map(pred, mock.create()); + } + + public Builder map(Predicate> pred, CommandMockSpec mock) { + return map(pred, mock.toCommandMockBuilder()); + } + + public Builder map(CommandMockSpec mock) { + return map(cmdlineStartsWith(mock.name()), mock.toCommandMockBuilder()); + } + + public Builder use(CommandMock mock) { + return map(_ -> true, mock); + } + + public Builder use(Predicate> pred, CommandMock.Builder mock) { + return map(_ -> true, mock); + } + + public Builder use(Predicate> pred, CommandMockSpec mock) { + return map(_ -> true, mock); + } + + public Builder branch(Predicate> pred, Script script) { + Objects.requireNonNull(pred); + Objects.requireNonNull(script); + instruction(cmdline -> { + if (pred.test(cmdline)) { + return new ScriptResult(script); + } else { + return new CommandMockResult(Optional.empty()); + } + }); + return this; + } + + public Builder commandMockBuilderMutator(Consumer v) { + commandMockBuilderMutator = v; + return this; + } + + public Builder mutate(Consumer mutator) { + mutator.accept(this); + return this; + } + + private Builder instruction(Function, Result> instruction) { + instructions.add(Objects.requireNonNull(instruction)); + return this; + } + + private Collection completableMocks() { + return completableMocks.stream().map(IdentityWrapper::value).toList(); + } + + private static RuntimeException noMapping(List cmdline) { + return new ScriptException(String.format("Mapping for %s command line not found", cmdline)); + } + + private sealed interface Result { + } + + private record CommandMockResult(Optional value) implements Result { + CommandMockResult { + Objects.requireNonNull(value); + } + } + + private record ScriptResult(Script value) implements Result { + ScriptResult { + Objects.requireNonNull(value); + } + } + + private abstract static class AbstractScript implements Script { + + AbstractScript(Collection completableMocks) { + this.completableMocks = Objects.requireNonNull(completableMocks); + } + + @Override + public Collection incompleteMocks() { + return completableMocks.stream().filter(Predicate.not(CompletableCommandMock::completed)).toList(); + } + + private final Collection completableMocks; + } + + private static final class LoopScript extends AbstractScript { + + LoopScript(List, Result>> instructions, + Collection completableMocks) { + super(completableMocks); + this.instructions = Objects.requireNonNull(instructions); + } + + @Override + public CommandMock map(List cmdline) { + for (var instruction : instructions) { + switch (instruction.apply(cmdline)) { + case CommandMockResult result -> { + var mock = result.value(); + if (mock.isPresent()) { + return mock.get(); + } + } + case ScriptResult result -> { + return result.value().map(cmdline); + } + } + } + + throw noMapping(cmdline); + } + + private final List, Result>> instructions; + } + + private static final class SequenceScript extends AbstractScript { + + SequenceScript(List, Result>> instructions, + Collection completableMocks) { + super(completableMocks); + this.iter = instructions.iterator(); + } + + @Override + public CommandMock map(List cmdline) { + if (!iter.hasNext()) { + throw new ScriptException("No more mappings"); + } else { + switch (iter.next().apply(cmdline)) { + case CommandMockResult result -> { + var mock = result.value(); + if (mock.isPresent()) { + return mock.get(); + } + } + case ScriptResult result -> { + return result.value().map(cmdline); + } + } + } + + throw noMapping(cmdline); + } + + private final Iterator, Result>> iter; + } + + private Consumer commandMockBuilderMutator = CommandMock.Builder::noRepeats; + private final List, Result>> instructions = new ArrayList<>(); + private final Set> completableMocks = new HashSet<>(); + } +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ScriptSpec.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ScriptSpec.java new file mode 100644 index 00000000000..60e5723e9a7 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ScriptSpec.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.stream.IntStream; + +/** + * Specification of a {@link Script}. + */ +public record ScriptSpec(List items, boolean loop) { + + public ScriptSpec { + Objects.requireNonNull(items); + } + + @Override + public String toString() { + var sb = new StringBuilder(); + sb.append(items.toString()); + if (loop) { + // Append "Clockwise Gapped Circle Arrow" Unicode symbol. + sb.append('(').appendCodePoint(0x27F3).append(')'); + } + return sb.toString(); + } + + public Script create() { + var script = Script.build(); + items.forEach(item -> { + item.applyTo(script, loop); + }); + if (loop) { + return script.createLoop(); + } else { + return script.createSequence(); + } + } + + public Collection commandNames() { + return items.stream().map(Item::mockSpec).map(CommandMockSpec::name).distinct().toList(); + } + + private record Item(CommandMockSpec mockSpec, int repeatCount, boolean detailedDescription) { + + private Item { + Objects.requireNonNull(mockSpec); + if (repeatCount < 0) { + throw new IllegalArgumentException(); + } + } + + @Override + public String toString() { + var sb = new StringBuilder(); + if (detailedDescription) { + sb.append(mockSpec); + } else if (mockSpec.isDefaultMockName()) { + sb.append(mockSpec.name()); + } else { + sb.append(mockSpec.mockName()); + } + if (repeatCount > 0) { + sb.append('(').append(repeatCount + 1).append(')'); + } + return sb.toString(); + } + + void applyTo(Script.Builder script, boolean loopScript) { + var pred = Script.cmdlineStartsWith(mockSpec.name()); + + var mockBuilder = mockSpec.toCommandMockBuilder(); + if (loopScript) { + script.map(pred, mockBuilder.repeat(repeatCount).create()); + } else { + mockBuilder.repeat(0); + IntStream.rangeClosed(0, repeatCount).forEach(_ -> { + script.map(pred, mockBuilder.create()); + }); + } + } + + } + + public static Builder build() { + return new Builder(); + } + + public static final class Builder { + + private Builder() { + } + + public ScriptSpec create() { + return new ScriptSpec(List.copyOf(items), loop); + } + + public Builder loop(boolean v) { + loop = v; + return this; + } + + public Builder loop() { + return loop(true); + } + + public final class ItemBuilder { + + private ItemBuilder(CommandMockSpec mockSpec) { + this.mockSpec = Objects.requireNonNull(mockSpec); + } + + public Builder add() { + items.add(new Item(mockSpec, repeat, detailedDescription)); + return Builder.this; + } + + public ItemBuilder repeat(int v) { + if (repeat < 0) { + throw new IllegalArgumentException(); + } + repeat = v; + return this; + } + + public ItemBuilder detailedDescription(boolean v) { + detailedDescription = v; + return this; + } + + public ItemBuilder detailedDescription() { + return detailedDescription(true); + } + + private final CommandMockSpec mockSpec; + private int repeat; + private boolean detailedDescription; + } + + public Builder add(CommandMockSpec mockSpec) { + return build(mockSpec).add(); + } + + public Builder addLoop(CommandMockSpec mockSpec) { + return build(mockSpec).add(); + } + + public ItemBuilder build(CommandMockSpec mockSpec) { + return new ItemBuilder(mockSpec); + } + + private final List items = new ArrayList<>(); + private boolean loop; + } +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ScriptSpecInDir.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ScriptSpecInDir.java new file mode 100644 index 00000000000..8c59c777d96 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ScriptSpecInDir.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.nio.file.Path; +import java.util.Objects; + +/** + * Specification of a {@link Script} bound to a specific directory. + */ +public class ScriptSpecInDir { + + public ScriptSpecInDir() { + } + + @Override + public String toString() { + return scriptSpec.toString(); + } + + public boolean isPathInDir(Path path) { + return path.startsWith(dir); + } + + public ScriptSpecInDir dir(Path v) { + dir = v; + return this; + } + + public ScriptSpecInDir scriptSpec(ScriptSpec v) { + scriptSpec = v; + return this; + } + + public ScriptSpec scriptSpec() { + Objects.requireNonNull(dir); + return Objects.requireNonNull(scriptSpec); + } + + public Script create() { + return scriptSpec().create(); + } + + private ScriptSpec scriptSpec; + private Path dir; +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ToolProviderCommandMock.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ToolProviderCommandMock.java new file mode 100644 index 00000000000..ee9556277d4 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ToolProviderCommandMock.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +import java.util.spi.ToolProvider; + +public sealed interface ToolProviderCommandMock extends CommandMock, ToolProvider + permits ToolProviderCompletableCommandMock, MockingToolProvider { +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ToolProviderCompletableCommandMock.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ToolProviderCompletableCommandMock.java new file mode 100644 index 00000000000..907cedd38d7 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/ToolProviderCompletableCommandMock.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +public sealed interface ToolProviderCompletableCommandMock extends ToolProviderCommandMock, CompletableCommandMock + permits MockingToolProvider.Completable { +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/VerbatimCommandMock.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/VerbatimCommandMock.java new file mode 100644 index 00000000000..799caaa0ea9 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/VerbatimCommandMock.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.test.mock; + +public enum VerbatimCommandMock implements CommandMock { + + INSTANCE +} diff --git a/test/jdk/tools/jpackage/junit/linux/jdk.jpackage/jdk/jpackage/internal/LibProvidersLookupTest.java b/test/jdk/tools/jpackage/junit/linux/jdk.jpackage/jdk/jpackage/internal/LibProvidersLookupTest.java new file mode 100644 index 00000000000..41a9bdc647e --- /dev/null +++ b/test/jdk/tools/jpackage/junit/linux/jdk.jpackage/jdk/jpackage/internal/LibProvidersLookupTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2026, 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. + */ + +package jdk.jpackage.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import jdk.jpackage.test.mock.CommandActionSpecs; +import jdk.jpackage.test.mock.CommandMockExit; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +public class LibProvidersLookupTest { + + @ParameterizedTest + @EnumSource(value = CommandMockExit.class) + public void test_supported(CommandMockExit exit) { + + var ldd = CommandActionSpecs.build().exit(exit).toCommandMockBuilder().name("ldd-mock").create(); + + Globals.main(() -> { + Globals.instance().executorFactory(() -> { + return new Executor().mapper(executor -> { + return executor.copy().mapper(null).toolProvider(ldd); + }); + }); + + boolean actual = LibProvidersLookup.supported(); + assertEquals(exit.exitNormally(), actual); + + return 0; + }); + } +} diff --git a/test/jdk/tools/jpackage/junit/linux/jdk.jpackage/jdk/jpackage/internal/LinuxPackageArchTest.java b/test/jdk/tools/jpackage/junit/linux/jdk.jpackage/jdk/jpackage/internal/LinuxPackageArchTest.java new file mode 100644 index 00000000000..baf03a32142 --- /dev/null +++ b/test/jdk/tools/jpackage/junit/linux/jdk.jpackage/jdk/jpackage/internal/LinuxPackageArchTest.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2026, 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. + */ + +package jdk.jpackage.internal; + +import static jdk.jpackage.internal.model.StandardPackageType.LINUX_DEB; +import static jdk.jpackage.internal.model.StandardPackageType.LINUX_RPM; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import jdk.jpackage.internal.model.StandardPackageType; +import jdk.jpackage.internal.util.Result; +import jdk.jpackage.test.mock.CommandActionSpecs; +import jdk.jpackage.test.mock.CommandMockExit; +import jdk.jpackage.test.mock.CommandMockSpec; +import jdk.jpackage.test.mock.Script; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +public class LinuxPackageArchTest { + + @ParameterizedTest + @MethodSource + public void test(Runnable test) { + test.run(); + } + + private static List test() { + var data = new ArrayList(); + + // "foo" stdout interleaved with "bar" stderr + var fooArch = CommandActionSpecs.build() + .printToStdout("f").printToStderr("b") + .printToStdout("o").printToStderr("a") + .printToStdout("o").printToStderr("r"); + + for (var exit : CommandMockExit.values()) { + var dpkg = fooArch.copy().printToStdout("-deb").exit(exit).create(); + + data.add(new DebTestSpec(dpkg, Optional.of("foo-deb").filter(_ -> { + return exit.succeed(); + }))); + } + + for (var rpmbuildExit : CommandMockExit.values()) { + var rpmbuild = fooArch.copy().printToStdout("-rpmbuild").exit(rpmbuildExit).create(); + for (var rpmExit : CommandMockExit.values()) { + var rpm = fooArch.copy().printToStdout("-rpm").exit(rpmExit).create(); + Optional expect; + if (rpmbuildExit.succeed()) { + expect = Optional.of("foo-rpmbuild"); + rpm = CommandActionSpecs.UNREACHABLE; + } else { + if (rpmExit.succeed()) { + expect = Optional.of("foo-rpm"); + } else { + expect = Optional.empty(); + } + } + + data.add(new RpmTestSpec(rpmbuild, rpm, expect)); + } + } + + return data; + } + + record RpmTestSpec(CommandActionSpecs rpmbuild, CommandActionSpecs rpm, Optional expect) implements Runnable { + + RpmTestSpec { + Objects.requireNonNull(rpm); + Objects.requireNonNull(rpmbuild); + Objects.requireNonNull(expect); + } + + @Override + public void run() { + + // Create an executor factory that will: + // - Substitute the "rpm" command with `rpm` mock. + // - Substitute the "rpmbuild" command with `rpmbuild` mock. + // - Throw if a command with the name other than "rpm" and "rpmbuild" is requested for execution. + + var script = Script.build() + // LinuxPackageArch must run the "rpmbuild" command first. Put its mapping at the first position. + .map(new CommandMockSpec("rpmbuild", rpmbuild)) + // LinuxPackageArch may optionally run the "rpm" command. Put its mapping after the "rpmbuild" command mapping. + .map(new CommandMockSpec("rpm", rpm)) + // Create a sequential script: after every Script#map() call, the script will advance the current mapping. + // This means each mapping in the script will be considered only once. + // If "rpm" and "rpmbuild" commands are executed in reverse order, the second Script#map() will throw. + .createSequence(); + + test(expect, LINUX_RPM, script); + } + } + + record DebTestSpec(CommandActionSpecs dpkg, Optional expect) implements Runnable { + + DebTestSpec { + Objects.requireNonNull(dpkg); + Objects.requireNonNull(expect); + } + + @Override + public void run() { + var script = Script.build().map(new CommandMockSpec("dpkg", dpkg)).createSequence(); + + test(expect, LINUX_DEB, script); + } + } + + private static void test(Optional expectedArch, StandardPackageType pkgType, Script script) { + + Globals.main(() -> { + + MockUtils.buildJPackage().script(script).applyToGlobals(); + + Result arch = LinuxPackageArch.create(pkgType); + + assertEquals(arch.hasValue(), expectedArch.isPresent()); + expectedArch.ifPresent(v -> { + assertEquals(v, arch.orElseThrow().value()); + }); + + assertEquals(List.of(), script.incompleteMocks()); + + return 0; + }); + } +} diff --git a/test/jdk/tools/jpackage/junit/linux/jdk.jpackage/jdk/jpackage/internal/LinuxSystemEnvironmentTest.java b/test/jdk/tools/jpackage/junit/linux/jdk.jpackage/jdk/jpackage/internal/LinuxSystemEnvironmentTest.java new file mode 100644 index 00000000000..8ff958491b1 --- /dev/null +++ b/test/jdk/tools/jpackage/junit/linux/jdk.jpackage/jdk/jpackage/internal/LinuxSystemEnvironmentTest.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2026, 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. + */ + +package jdk.jpackage.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import jdk.jpackage.internal.model.StandardPackageType; +import jdk.jpackage.test.mock.CommandActionSpecs; +import jdk.jpackage.test.mock.CommandMockExit; +import jdk.jpackage.test.mock.CommandMockSpec; +import jdk.jpackage.test.mock.Script; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +public class LinuxSystemEnvironmentTest { + + @ParameterizedTest + @MethodSource + public void test_detectNativePackageType(DetectNativePackageTypeTestSpec test) { + test.run(); + } + + private static List test_detectNativePackageType() { + var data = new ArrayList(); + for (var rpmExit : CommandMockExit.values()) { + for (var debExit : CommandMockExit.values()) { + CommandActionSpecs deb = CommandActionSpecs.build().exit(debExit).create(); + CommandActionSpecs rpm; + Optional expected; + if (debExit.succeed()) { + expected = Optional.of(StandardPackageType.LINUX_DEB); + rpm = CommandActionSpecs.UNREACHABLE; + } else { + rpm = CommandActionSpecs.build().exit(rpmExit).create(); + if (rpmExit.succeed()) { + expected = Optional.of(StandardPackageType.LINUX_RPM); + } else { + expected = Optional.empty(); + } + } + data.add(new DetectNativePackageTypeTestSpec(expected, rpm, deb)); + } + } + return data; + } + + record DetectNativePackageTypeTestSpec(Optional expect, CommandActionSpecs rpm, CommandActionSpecs deb) { + + DetectNativePackageTypeTestSpec { + Objects.requireNonNull(expect); + Objects.requireNonNull(rpm); + Objects.requireNonNull(deb); + } + + void run() { + + var script = Script.build() + .map(new CommandMockSpec("rpm", rpm)) + .map(new CommandMockSpec("dpkg", deb)) + .createLoop(); + + Globals.main(() -> { + + MockUtils.buildJPackage().script(script).applyToGlobals(); + + var actual = LinuxSystemEnvironment.detectNativePackageType(); + + assertEquals(expect, actual); + + assertEquals(List.of(), script.incompleteMocks()); + + return 0; + }); + } + } +} diff --git a/test/jdk/tools/jpackage/junit/linux/junit.java b/test/jdk/tools/jpackage/junit/linux/junit.java index 214812e951e..0fd337c812c 100644 --- a/test/jdk/tools/jpackage/junit/linux/junit.java +++ b/test/jdk/tools/jpackage/junit/linux/junit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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,3 +30,35 @@ * ../../share/jdk.jpackage/jdk/jpackage/internal/model/ApplicationLayoutTest.java * @run junit jdk.jpackage/jdk.jpackage.internal.LinuxApplicationLayoutTest */ + +/* @test + * @summary Test LinuxSystemEnvironment + * @requires (os.family == "linux") + * @library /test/jdk/tools/jpackage/helpers + * @build jdk.jpackage.test.mock.* + * @compile/module=jdk.jpackage -Xlint:all -Werror + * jdk/jpackage/internal/LinuxSystemEnvironmentTest.java + * ../../share/jdk.jpackage/jdk/jpackage/internal/MockUtils.java + * @run junit jdk.jpackage/jdk.jpackage.internal.LinuxSystemEnvironmentTest + */ + +/* @test + * @summary Test LibProvidersLookup + * @requires (os.family == "linux") + * @library /test/jdk/tools/jpackage/helpers + * @build jdk.jpackage.test.mock.* + * @compile/module=jdk.jpackage -Xlint:all -Werror + * jdk/jpackage/internal/LibProvidersLookupTest.java + * @run junit jdk.jpackage/jdk.jpackage.internal.LibProvidersLookupTest + */ + +/* @test + * @summary Test LinuxPackageArch + * @requires (os.family == "linux") + * @library /test/jdk/tools/jpackage/helpers + * @build jdk.jpackage.test.mock.* + * @compile/module=jdk.jpackage -Xlint:all -Werror + * jdk/jpackage/internal/LinuxPackageArchTest.java + * ../../share/jdk.jpackage/jdk/jpackage/internal/MockUtils.java + * @run junit jdk.jpackage/jdk.jpackage.internal.LinuxPackageArchTest + */ diff --git a/test/jdk/tools/jpackage/junit/macosx/jdk.jpackage/jdk/jpackage/internal/MacDmgPackagerTest.java b/test/jdk/tools/jpackage/junit/macosx/jdk.jpackage/jdk/jpackage/internal/MacDmgPackagerTest.java new file mode 100644 index 00000000000..e5da383142a --- /dev/null +++ b/test/jdk/tools/jpackage/junit/macosx/jdk.jpackage/jdk/jpackage/internal/MacDmgPackagerTest.java @@ -0,0 +1,420 @@ +/* + * Copyright (c) 2026, 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. + */ + +package jdk.jpackage.internal; + +import static jdk.jpackage.internal.model.StandardPackageType.MAC_DMG; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import jdk.internal.util.OperatingSystem; +import jdk.jpackage.internal.MacPackagingPipeline.MacBuildApplicationTaskID; +import jdk.jpackage.internal.PackagingPipeline.BuildApplicationTaskID; +import jdk.jpackage.internal.model.AppImageLayout; +import jdk.jpackage.internal.model.RuntimeBuilder; +import jdk.jpackage.internal.util.CommandOutputControl.UnexpectedResultException; +import jdk.jpackage.internal.util.FileUtils; +import jdk.jpackage.internal.util.RetryExecutor; +import jdk.jpackage.internal.util.function.ExceptionBox; +import jdk.jpackage.test.mock.CommandActionSpec; +import jdk.jpackage.test.mock.CommandActionSpecs; +import jdk.jpackage.test.mock.CommandMockSpec; +import jdk.jpackage.test.mock.MockIllegalStateException; +import jdk.jpackage.test.mock.ScriptSpec; +import jdk.jpackage.test.mock.ScriptSpecInDir; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +public class MacDmgPackagerTest { + + /** + * Exercise branches in {@link MacDmgPackager#buildDMG()}. + */ + @ParameterizedTest + @MethodSource + public void test(DmgScript scriptSpec, @TempDir Path workDir) { + scriptSpec.run(workDir); + } + + private static List test() { + var data = new ArrayList(); + + var succeed = CommandActionSpecs.build().exit().create(); + var fail = CommandActionSpecs.build().exit(1).create(); + + // Test create + for (var createFullSucceed : List.of(true, false)) { + var dmgScript = new DmgScript(); + + var scriptBuilder = ScriptSpec.build(); + + if (createFullSucceed) { + // `hdiutil create -srcfolder` succeeds + scriptBuilder.add(new CommandMockSpec("hdiutil", "hdiutil-create", dmgScript.hdiutilCreate().exit().create())); + } else { + // `hdiutil create -srcfolder` fails + scriptBuilder.add(new CommandMockSpec("hdiutil", "hdiutil-create", fail)); + scriptBuilder.add(new CommandMockSpec("hdiutil", "hdiutil-create-empty", dmgScript.hdiutilCreateEmpty().exit().create())); + } + + scriptBuilder + // `hdiutil attach` succeeds + .add(new CommandMockSpec("hdiutil", "hdiutil-attach", succeed)) + // `osascript` succeeds + .add(new CommandMockSpec("osascript", succeed)) + // `hdiutil detach` succeeds + .add(new CommandMockSpec("hdiutil", "hdiutil-detach", dmgScript.hdiutilDetach().exit().create())) + // `hdiutil convert` succeeds + .add(new CommandMockSpec("hdiutil", "hdiutil-convert", dmgScript.hdiutilConvert().exit().create())); + + data.add(dmgScript.scriptSpec(scriptBuilder.create())); + } + + // Test detach + for (var detachResult : DetachResult.values()) { + var dmgScript = new DmgScript(); + + var scriptBuilder = ScriptSpec.build() + .add(new CommandMockSpec("hdiutil", "hdiutil-create", dmgScript.hdiutilCreate().exit().create())) + .add(new CommandMockSpec("hdiutil", "hdiutil-attach", succeed)) + .add(new CommandMockSpec("osascript", succeed)); + + switch (detachResult) { + case ALL_FAIL -> { + dmgScript.expect(UnexpectedResultException.class); + scriptBuilder.build(new CommandMockSpec("hdiutil", "hdiutil-detach", fail)).repeat(9).add(); + } + case LAST_SUCCEED -> { + scriptBuilder + .build(new CommandMockSpec("hdiutil", "hdiutil-detach", fail)).repeat(8).add() + .add(new CommandMockSpec("hdiutil", "hdiutil-detach", dmgScript.hdiutilDetach().exit().create())) + .add(new CommandMockSpec("hdiutil", "hdiutil-convert", dmgScript.hdiutilConvert().exit().create())); + } + case FIRST_SUCCEED_WITH_EXIT_1 -> { + scriptBuilder + .build(new CommandMockSpec("hdiutil", "hdiutil-detach", dmgScript.hdiutilDetach().exit(1).create())) + .detailedDescription().add() + .add(new CommandMockSpec("hdiutil", "hdiutil-convert", dmgScript.hdiutilConvert().exit().create())); + } + case FIRST_SUCCEED_MOUNT_POINT_REMAINS -> { + scriptBuilder + .build(new CommandMockSpec("hdiutil", "hdiutil-detach", dmgScript.hdiutilDetach(false).exit().create())) + .detailedDescription().add() + .add(new CommandMockSpec("hdiutil", "hdiutil-convert", dmgScript.hdiutilConvert().exit().create())); + } + } + + data.add(dmgScript.scriptSpec(scriptBuilder.create())); + } + + return data; + } + + private enum DetachResult { + ALL_FAIL, + LAST_SUCCEED, + // The first `hdiutil detach` attempt exits with exit code "1" but deletes the mounted directory. + FIRST_SUCCEED_WITH_EXIT_1, + // The first `hdiutil detach` attempt exits with exit code "0" and the mounted directory stays undeleted. + FIRST_SUCCEED_MOUNT_POINT_REMAINS, + ; + } + + private static MacDmgSystemEnvironment createSysEnv(ScriptSpec scriptSpec) { + return new MacDmgSystemEnvironment( + Path.of("hdiutil"), + Path.of("osascript"), + Stream.of("SetFile").map(Path::of).filter(scriptSpec.commandNames()::contains).findFirst() + ); + } + + private static RuntimeBuilder createRuntimeBuilder() { + return new RuntimeBuilder() { + @Override + public void create(AppImageLayout appImageLayout) { + throw new UnsupportedOperationException(); + } + }; + } + + private static void runPackagingMock(Path workDir, MacDmgSystemEnvironment sysEnv) { + + var app = new ApplicationBuilder() + .appImageLayout(MacPackagingPipeline.APPLICATION_LAYOUT) + .runtimeBuilder(createRuntimeBuilder()) + .name("foo") + .create(); + + var macApp = new MacApplicationBuilder(app).create(); + + var macDmgPkg = new MacDmgPackageBuilder(new MacPackageBuilder(new PackageBuilder(macApp, MAC_DMG))).create(); + + var buildEnv = new BuildEnvBuilder(workDir.resolve("build-root")).appImageDirFor(macDmgPkg).create(); + + var packager = new MacDmgPackager(buildEnv, macDmgPkg, workDir, sysEnv); + + var pipelineBuilder = MacPackagingPipeline.build(Optional.of(packager.pkg())); + packager.accept(pipelineBuilder); + + // Disable actions of tasks filling an application image. + Stream.concat( + Stream.of(BuildApplicationTaskID.values()), + Stream.of(MacBuildApplicationTaskID.values()) + ).forEach(taskId -> { + pipelineBuilder.task(taskId).noaction().add(); + }); + + var contentMock = new ContentMock(); + + // Fill application image with content mock. + pipelineBuilder.task(BuildApplicationTaskID.CONTENT).applicationAction(env -> { + contentMock.create(env.resolvedLayout().contentDirectory()); + }).add(); + + pipelineBuilder.create().execute(buildEnv, packager.pkg(), packager.outputDir()); + + var outputDmg = packager.outputDir().resolve(packager.pkg().packageFileNameWithSuffix()); + + contentMock.verifyStoredInFile(outputDmg); + } + + private static final class DmgScript extends ScriptSpecInDir { + + @Override + public String toString() { + var sb = new StringBuilder(); + sb.append(super.toString()); + Optional.ofNullable(expectedErrorType).ifPresent(type -> { + sb.append("; ").append(type.getCanonicalName()); + }); + return sb.toString(); + } + + @Override + public DmgScript scriptSpec(ScriptSpec v) { + super.scriptSpec(v); + return this; + } + + DmgScript expect(Class v) { + expectedErrorType = v; + return this; + } + + void run(Path workDir) { + + var script = dir(Objects.requireNonNull(workDir)).create(); + + ExecutorFactory executorFactory = MockUtils.buildJPackage() + .script(script).listener(System.out::println).createExecutorFactory(); + + var objectFactory = ObjectFactory.build() + .executorFactory(executorFactory) + .retryExecutorFactory(new RetryExecutorFactory() { + @Override + public RetryExecutor retryExecutor(Class exceptionType) { + return RetryExecutorFactory.DEFAULT.retryExecutor(exceptionType).setSleepFunction(_ -> { + // Don't "sleep" to make the test run faster. + }); + } + }) + .create(); + + Globals.main(() -> { + Globals.instance().objectFactory(objectFactory); + if (expectedErrorType == null) { + runPackagingMock(workDir, createSysEnv(scriptSpec())); + } else { + var ex = assertThrows(Exception.class, () -> { + runPackagingMock(workDir, createSysEnv(scriptSpec())); + }); + var cause = ExceptionBox.unbox(ex); + assertEquals(expectedErrorType, cause.getClass()); + } + return 0; + }); + + assertEquals(List.of(), script.incompleteMocks()); + } + + CommandActionSpecs.Builder hdiutilCreate(boolean empty) { + CommandActionSpec action = CommandActionSpec.create("create", context -> { + var dstDmg = Path.of(context.optionValue("-ov")); + assertTrue(isPathInDir(dstDmg)); + + var volumeName = context.optionValue("-volname"); + + if (empty) { + createDmg(new CreateDmgResult(dstDmg, volumeName, Optional.empty())); + Files.createFile(dstDmg); + } else { + var srcDir = Path.of(context.optionValue("-srcfolder")); + assertTrue(isPathInDir(srcDir)); + + createDmg(new CreateDmgResult(dstDmg, volumeName, Optional.of(srcDir))); + + try (var walk = Files.walk(srcDir)) { + var paths = walk.map(srcDir::relativize).map(Path::toString).toList(); + Files.write(dstDmg, paths); + } + } + }); + return CommandActionSpecs.build().action(action); + } + + CommandActionSpecs.Builder hdiutilCreate() { + return hdiutilCreate(false); + } + + CommandActionSpecs.Builder hdiutilCreateEmpty() { + return hdiutilCreate(true); + } + + CommandActionSpecs.Builder hdiutilDetach() { + return hdiutilDetach(true); + } + + CommandActionSpecs.Builder hdiutilDetach(boolean deleteMountPoint) { + var sb = new StringBuilder(); + sb.append("detach"); + if (!deleteMountPoint) { + sb.append("(rm-mount-point)"); + } + CommandActionSpec action = CommandActionSpec.create(sb.toString(), context -> { + var mountPoint = Path.of(context.args().getLast()); + assertTrue(isPathInDir(mountPoint)); + + try (var walk = Files.walk(mountPoint)) { + var dstDmg = dmg().dmg(); + var paths = Stream.concat( + walk.map(mountPoint::relativize), + Files.readAllLines(dstDmg).stream().filter(Predicate.not(String::isEmpty)).map(Path::of) + ).sorted().map(Path::toString).toList(); + Files.write(dstDmg, paths); + } + + if (deleteMountPoint) { + FileUtils.deleteRecursive(mountPoint); + } + }); + return CommandActionSpecs.build().action(action); + } + + CommandActionSpecs.Builder hdiutilConvert() { + CommandActionSpec action = CommandActionSpec.create("convert", context -> { + var srcDmg = Path.of(context.args().get(1)); + assertTrue(isPathInDir(srcDmg)); + + var dstDmg = Path.of(context.args().getLast()); + assertTrue(isPathInDir(dstDmg)); + + Files.copy(srcDmg, dstDmg); + }); + return CommandActionSpecs.build().action(action); + } + + private void createDmg(CreateDmgResult v) { + if (dmg != null) { + throw new MockIllegalStateException("The DMG already set"); + } else { + dmg = Objects.requireNonNull(v); + } + } + + private CreateDmgResult dmg() { + if (dmg == null) { + throw new MockIllegalStateException("The DMG not set"); + } else { + return dmg; + } + } + + private record CreateDmgResult(Path dmg, String volumeName, Optional srcFolder) { + CreateDmgResult { + Objects.requireNonNull(dmg); + Objects.requireNonNull(volumeName); + Objects.requireNonNull(srcFolder); + } + } + + private CreateDmgResult dmg; + private Class expectedErrorType; + } + + private static final class ContentMock { + + void create(Path dir) throws IOException { + Files.createDirectories(dir.resolve("foo/bar")); + Files.writeString(dir.resolve("foo/bar/buz"), "Hello!"); + if (!OperatingSystem.isWindows()) { + Files.createSymbolicLink(dir.resolve("symlink"), Path.of("foo")); + } + } + + void verifyStoredInFile(Path file) { + try { + var expectedPaths = Stream.of( + Stream.of(Path.of("")), + DMG_ICON_FILES.stream(), + Stream.of( + Stream.of("foo/bar/buz"), + Stream.of("symlink").filter(_ -> { + return !OperatingSystem.isWindows(); + }) + ).flatMap(x -> x).map(Path::of).map(Path.of("foo.app/Contents")::resolve) + ).flatMap(x -> x).mapMulti(EXPAND_PATH).sorted().distinct().toList(); + var actualPaths = Files.readAllLines(file).stream().map(Path::of).toList(); + assertEquals(expectedPaths, actualPaths); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + } + + private final static BiConsumer> EXPAND_PATH = (path, sink) -> { + do { + sink.accept(path); + path = path.getParent(); + } while (path != null); + }; + + private final static List DMG_ICON_FILES = Stream.of( + ".VolumeIcon.icns", + ".background/background.tiff" + ).map(Path::of).collect(Collectors.toUnmodifiableList()); +} diff --git a/test/jdk/tools/jpackage/junit/macosx/jdk.jpackage/jdk/jpackage/internal/MacDmgSystemEnvironmentTest.java b/test/jdk/tools/jpackage/junit/macosx/jdk.jpackage/jdk/jpackage/internal/MacDmgSystemEnvironmentTest.java new file mode 100644 index 00000000000..de2b07e86a6 --- /dev/null +++ b/test/jdk/tools/jpackage/junit/macosx/jdk.jpackage/jdk/jpackage/internal/MacDmgSystemEnvironmentTest.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2026, 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. + */ + +package jdk.jpackage.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; +import jdk.jpackage.internal.util.RetryExecutor; +import jdk.jpackage.test.mock.CommandActionSpecs; +import jdk.jpackage.test.mock.CommandMockExit; +import jdk.jpackage.test.mock.CommandMockSpec; +import jdk.jpackage.test.mock.Script; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +public class MacDmgSystemEnvironmentTest { + + @ParameterizedTest + @MethodSource + void test_findSetFileUtility(FindSetFileUtilityTestSpec test) { + test.run(); + } + + private static List test_findSetFileUtility() { + var data = new ArrayList(); + + var succeed = CommandActionSpecs.build().exit().create(); + + for (var failureCause : List.of(CommandMockExit.EXIT_1, CommandMockExit.THROW_MOCK_IO_EXCEPTION)) { + + var fail = CommandActionSpecs.build().exit(failureCause).create(); + + for (var i = 0; i != MacDmgSystemEnvironment.SETFILE_KNOWN_PATHS.size(); i++) { + + var expected = MacDmgSystemEnvironment.SETFILE_KNOWN_PATHS.get(i); + + var mocks = new ArrayList(); + + MacDmgSystemEnvironment.SETFILE_KNOWN_PATHS.subList(0, i).stream().map(failureSetFilePath -> { + return new CommandMockSpec(failureSetFilePath, fail); + }).forEach(mocks::add); + + mocks.add(new CommandMockSpec(expected, succeed)); + + data.add(new FindSetFileUtilityTestSpec(Optional.of(expected), mocks)); + } + + var lastMocks = data.getLast().mockSpecs(); + var lastSucceedMock = lastMocks.getLast(); + var lastFailMock = new CommandMockSpec(lastSucceedMock.name(), lastSucceedMock.mockName(), fail); + + var mocks = new ArrayList<>(lastMocks); + mocks.set(mocks.size() - 1, lastFailMock); + + for (var xcrunOutout : List., Boolean>>of( + // Use the path to the command of the current process + // as an output mock for the /usr/bin/xcrun command. + // MacDmgSystemEnvironment.findSetFileUtility() reads the command output + // and checks whether it is an executable file, + // so the hardcoded value is not an option for the output mock. + Map.entry(Optional.of(ProcessHandle.current().info().command().orElseThrow()), true), + // "/usr/bin/xcrun" outputs a path to non-executable file. + Map.entry(Optional.of("/dev/null"), false), + // "/usr/bin/xcrun" outputs '\0' making subsequent Path.of("\0") fail. + Map.entry(Optional.of("\0"), false), + // "/usr/bin/xcrun" doesn't output anything. + Map.entry(Optional.empty(), false) + )) { + + + mocks.add(new CommandMockSpec("/usr/bin/xcrun", CommandActionSpecs.build().mutate(builder -> { + xcrunOutout.getKey().ifPresent(builder::stdout); + }).exit(CommandMockExit.SUCCEED).create())); + + Optional expected; + if (xcrunOutout.getValue()) { + expected = xcrunOutout.getKey(); + } else { + expected = Optional.empty(); + } + + data.add(new FindSetFileUtilityTestSpec(expected.map(Path::of), List.copyOf(mocks))); + + mocks.removeLast(); + } + + // The last test case: "/usr/bin/xcrun" fails + mocks.add(new CommandMockSpec("/usr/bin/xcrun", fail)); + data.add(new FindSetFileUtilityTestSpec(Optional.empty(), mocks)); + } + + return data; + } + + record FindSetFileUtilityTestSpec(Optional expected, List mockSpecs) { + + FindSetFileUtilityTestSpec { + Objects.requireNonNull(expected); + Objects.requireNonNull(mockSpecs); + } + + @Override + public String toString() { + var tokens = new ArrayList(); + expected.ifPresent(v -> { + tokens.add(String.format("expect=%s", v)); + }); + tokens.add(mockSpecs.toString()); + return tokens.stream().collect(Collectors.joining(", ")); + } + + void run() { + + var script = Script.build().mutate(builder -> { + mockSpecs.forEach(builder::map); + }).createSequence(); + + Globals.main(() -> { + MockUtils.buildJPackage().script(script).applyToGlobals(); + + var actual = MacDmgSystemEnvironment.findSetFileUtility(); + + assertEquals(expected, actual); + assertEquals(List.of(), script.incompleteMocks()); + + return 0; + }); + } + } +} diff --git a/test/jdk/tools/jpackage/junit/macosx/junit.java b/test/jdk/tools/jpackage/junit/macosx/junit.java index 1549aaa6cd7..c7fd2bc5f8d 100644 --- a/test/jdk/tools/jpackage/junit/macosx/junit.java +++ b/test/jdk/tools/jpackage/junit/macosx/junit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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,3 +30,25 @@ * ../../share/jdk.jpackage/jdk/jpackage/internal/model/ApplicationLayoutTest.java * @run junit jdk.jpackage/jdk.jpackage.internal.MacApplicationLayoutTest */ + +/* @test + * @summary Test MacDmgSystemEnvironmentTest + * @requires (os.family == "mac") + * @library /test/jdk/tools/jpackage/helpers + * @build jdk.jpackage.test.mock.* + * @compile/module=jdk.jpackage -Xlint:all -Werror + * jdk/jpackage/internal/MacDmgSystemEnvironmentTest.java + * ../../share/jdk.jpackage/jdk/jpackage/internal/MockUtils.java + * @run junit jdk.jpackage/jdk.jpackage.internal.MacDmgSystemEnvironmentTest + */ + +/* @test + * @summary Test MacDmgPackagerTest + * @requires (os.family == "mac") + * @library /test/jdk/tools/jpackage/helpers + * @build jdk.jpackage.test.mock.* + * @compile/module=jdk.jpackage -Xlint:all -Werror + * jdk/jpackage/internal/MacDmgPackagerTest.java + * ../../share/jdk.jpackage/jdk/jpackage/internal/MockUtils.java + * @run junit jdk.jpackage/jdk.jpackage.internal.MacDmgPackagerTest + */ diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/DefaultBundlingEnvironmentTest.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/DefaultBundlingEnvironmentTest.java index 35ab1fbec5e..1a14330fe6e 100644 --- a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/DefaultBundlingEnvironmentTest.java +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/DefaultBundlingEnvironmentTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, 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 @@ -22,15 +22,42 @@ */ package jdk.jpackage.internal; + +import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; +import static jdk.jpackage.test.mock.CommandMock.ioerror; +import static jdk.jpackage.test.mock.CommandMock.succeed; import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.Set; +import java.util.spi.ToolProvider; +import java.util.stream.Stream; import jdk.internal.util.OperatingSystem; +import jdk.jpackage.internal.cli.StandardBundlingOperation; +import jdk.jpackage.internal.model.AppImagePackageType; import jdk.jpackage.internal.model.BundlingOperationDescriptor; +import jdk.jpackage.internal.model.PackageType; +import jdk.jpackage.internal.model.StandardPackageType; +import jdk.jpackage.test.Annotations; +import jdk.jpackage.test.HelloApp; +import jdk.jpackage.test.JUnitAdapter; +import jdk.jpackage.test.JavaAppDesc; +import jdk.jpackage.test.TKit; +import jdk.jpackage.test.mock.CommandActionSpecs; +import jdk.jpackage.test.mock.CommandMock; +import jdk.jpackage.test.mock.CommandMockExit; +import jdk.jpackage.test.mock.Script; import org.junit.jupiter.api.Test; -public class DefaultBundlingEnvironmentTest { +public class DefaultBundlingEnvironmentTest extends JUnitAdapter { @Test void testDefaultBundlingOperation() { @@ -55,4 +82,200 @@ public class DefaultBundlingEnvironmentTest { assertEquals(descriptor, env.defaultOperation().orElseThrow()); assertEquals(1, executed[0]); } + + /** + * Tests that commands executed to initialize the system environment are + * executed only once. + * @throws IOException + */ + @Annotations.Test + @Annotations.ParameterSupplier + public void testInitializedOnce(StandardBundlingOperation op) throws IOException { + + List> executedCommands = Collections.synchronizedList(new ArrayList<>()); + + var script = createMockScript(op); + + ToolProvider jpackage = MockUtils.buildJPackage() + .os(op.os()) + .script(script) + .listener(executedCommands::add).create(); + + var inputDir = TKit.createTempDirectory("input"); + var appDesc = JavaAppDesc.parse(null); + HelloApp.createBundle(appDesc, inputDir); + + // + // The command line should fail as the main class name is not specified and it is not set in the main jar. + // + // Run native packaging twice. + // It can execute commands required to configure the system environment in the first iteration. + // It must not execute a single command in the second iteration. + // + // Run app image packaging once. + // It must not execute a single command because app image packaging should not require native commands (Unless + // it is macOS where it will sign the app image with an ad hoc signature + // using the codesign tool. But: #1 - it is not a variable part of the system environment; + // #2 - jpackage should bail out earlier). + // + + final var type = op.packageTypeValue(); + final int iterationCount; + if (op.packageType() instanceof AppImagePackageType) { + iterationCount = 1; + } else { + iterationCount = 2; + } + + for (var i = 0; i != iterationCount; i++) { + var result = new Executor().toolProvider(jpackage).saveOutput().args( + "--type=" + type, + "--input", inputDir.toString(), + "--main-jar", appDesc.jarFileName()).execute(); + + assertEquals(1, result.getExitCode()); + + // Assert it bailed out with the expected error. + assertEquals(List.of( + I18N.format("message.error-header", I18N.format("error.no-main-class-with-main-jar", appDesc.jarFileName())), + I18N.format("message.advice-header", I18N.format("error.no-main-class-with-main-jar.advice", appDesc.jarFileName())) + ), result.stderr()); + + TKit.trace("The list of executed commands:"); + executedCommands.forEach(cmdline -> { + TKit.trace(" " + cmdline); + }); + TKit.trace("Done"); + + if (i == 0) { + executedCommands.clear(); + } + } + + assertEquals(List.of(), executedCommands); + assertEquals(List.of(), script.incompleteMocks()); + } + + public static List testInitializedOnce() { + return StandardBundlingOperation.ofPlatform(OperatingSystem.current()) + .filter(StandardBundlingOperation::isCreateBundle).map(v -> { + return new Object[] {v}; + }).toList(); + } + + private static Script createMockScript(StandardBundlingOperation op) { + + if (op.packageType() instanceof AppImagePackageType) { + return Script.build().createSequence(); + } + + switch (op.os()) { + case WINDOWS -> { + return createWinMockScript(); + } + case LINUX -> { + return createLinuxMockScript(op.packageType()); + } + case MACOS -> { + return createMacMockScript(); + } + default -> { + throw new AssertionError(); + } + } + } + + private static Script createWinMockScript() { + + // Make "candle.exe" and "light.exe" always fail. + var candle = ioerror("candle-mock"); + var light = ioerror("light-mock"); + + // Make the "wix.exe" functional. + var wix = CommandActionSpecs.build() + .stdout("5.0.2+aa65968c") + .exit(CommandMockExit.SUCCEED) + .toCommandMockBuilder().name("wix-mock").create(); + + var script = Script.build() + .map(Script.cmdlineStartsWith("candle.exe"), candle) + .map(Script.cmdlineStartsWith("light.exe"), light) + .map(Script.cmdlineStartsWith("wix.exe"), wix) + .createLoop(); + + return script; + } + + private static Script createMacMockScript() { + + @SuppressWarnings("unchecked") + var setfilePaths = (List)toSupplier(() -> { + return Class.forName(String.join(".", + DefaultBundlingEnvironmentTest.class.getPackageName(), + "MacDmgSystemEnvironment" + )).getDeclaredField("SETFILE_KNOWN_PATHS").get(null); + }).get(); + + var script = Script.build(); + + for (var setfilePath: setfilePaths) { + script.map(Script.cmdlineStartsWith(setfilePath), ioerror(setfilePath.toString() + "-mock")); + } + + script.map(Script.cmdlineStartsWith("/usr/bin/xcrun"), succeed("/usr/bin/xcrun-mock")); + + return script.createLoop(); + } + + private static Script createLinuxMockScript(PackageType pkgType) { + + final Map mocks = new HashMap<>(); + + var script = Script.build(); + + final Set debCommandNames = Set.of("dpkg", "dpkg-deb", "fakeroot"); + final Set rpmCommandNames = Set.of("rpm", "rpmbuild"); + + final Set succeedCommandNames; + switch (pkgType) { + case StandardPackageType.LINUX_DEB -> { + succeedCommandNames = debCommandNames; + // Simulate "dpkg --print-architecture". + var dpkg = CommandActionSpecs.build() + .stdout("foo-arch") + .exit(CommandMockExit.SUCCEED) + .toCommandMockBuilder().name("dpkg-mock").create(); + mocks.put("dpkg", dpkg); + } + case StandardPackageType.LINUX_RPM -> { + succeedCommandNames = rpmCommandNames; + // Simulate "rpmbuild --version" prints the minimal acceptable version. + var rpmbuild = CommandActionSpecs.build() + .stdout("RPM version 4.10") + .exit(CommandMockExit.SUCCEED) + .toCommandMockBuilder().name("rpmbuild-mock").create(); + mocks.put("rpmbuild", rpmbuild); + } + default -> { + throw new IllegalArgumentException(); + } + } + + script.map(Script.cmdlineStartsWith("ldd"), succeed("ldd-mock")); + + for (var commandName : succeedCommandNames) { + if (!mocks.containsKey(commandName)) { + mocks.put(commandName, succeed(commandName + "-mock")); + } + } + + Stream.of(debCommandNames, rpmCommandNames).flatMap(Set::stream).forEach(commandName -> { + var mock = Optional.ofNullable(mocks.get(commandName)).orElseGet(() -> { + return ioerror(commandName + "-mock"); + }); + script.map(Script.cmdlineStartsWith(commandName), mock); + }); + + return script.createLoop(); + } } diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/ExecutorTest.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/ExecutorTest.java new file mode 100644 index 00000000000..551ef15e991 --- /dev/null +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/ExecutorTest.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2026, 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. + */ + +package jdk.jpackage.internal; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Supplier; +import java.util.stream.Stream; +import jdk.jpackage.internal.util.CommandOutputControl.UnexpectedResultException; +import jdk.jpackage.test.mock.CommandActionSpecs; +import jdk.jpackage.test.mock.CommandMockExit; +import jdk.jpackage.test.mock.CompletableCommandMock; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +public class ExecutorTest { + + @ParameterizedTest + @MethodSource + public void test_retryOnKnownErrorMessage(RetryOnKnownErrorMessageTestSpec test) { + test.run(); + } + + private static Stream test_retryOnKnownErrorMessage() { + var data = new ArrayList(); + + final var subject = "French fries"; + + Supplier build = () -> { + return RetryOnKnownErrorMessageTestSpec.build().subject(subject); + }; + + for (var exit : Stream.of(CommandMockExit.values()).filter(CommandMockExit::exitNormally).toList()) { + // These should succeed as there is no "French fries" in stderr. + Stream.of( + build.get().mock(CommandActionSpecs.build().stderr("Coleslaw").exit(exit)), + build.get().mock(CommandActionSpecs.build().stdout(subject).exit(exit)), + build.get() + // Fail in the first attempt (triggering text in the stderr) + .mock(CommandActionSpecs.build().stderr(subject).exit()) + // Fail in the second attempt (same reason) + .repeatLastMoc() + // Pass in the next attempt (no triggering text in the stderr) + .mock(CommandActionSpecs.build().stderr("Coleslaw").exit(exit)), + build.get() + // Fail in the first attempt (triggering text in the stderr) + .mock(CommandActionSpecs.build().stderr(subject)) + // Fail in the second attempt (error running the command) + .mock(CommandActionSpecs.build().exit(CommandMockExit.THROW_MOCK_IO_EXCEPTION)) + // Pass in the next attempt (no triggering text in the stderr) + .mock(CommandActionSpecs.build().exit(exit)) + ).map(RetryOnKnownErrorMessageTestSpec.Builder::success).forEach(data::add); + } + + // These should fail as there is "French fries" in stderr. + data.addAll(List.of( + // Try once and fail. + build.get().mock(CommandActionSpecs.build().stderr(subject).exit()), + // Try twice and fail. + build.get().mock(CommandActionSpecs.build().stderr(subject).exit()).repeatLastMoc() + )); + + return data.stream().map(RetryOnKnownErrorMessageTestSpec.Builder::create); + } + + record RetryOnKnownErrorMessageTestSpec(List mockSpecs, String subject, boolean success) { + + RetryOnKnownErrorMessageTestSpec { + Objects.requireNonNull(mockSpecs); + Objects.requireNonNull(subject); + + if (mockSpecs.isEmpty()) { + throw new IllegalArgumentException(); + } + } + + void run() { + var mock = mockSpecs.stream() + .reduce(CommandActionSpecs::andThen) + .orElseThrow().toCommandMockBuilder() + // Ensure attempts to run the command more times than expected will fail. + .noRepeats().create(); + + var retry = new Executor().toolProvider(mock).retryOnKnownErrorMessage(subject) + .setAttemptTimeout(null) + .setMaxAttemptsCount(mockSpecs.size()); + + if (success) { + assertDoesNotThrow(retry::execute); + } else { + assertThrowsExactly(UnexpectedResultException.class, retry::execute); + } + + assertTrue(((CompletableCommandMock)mock).completed()); + } + + static Builder build() { + return new Builder(); + } + + static final class Builder { + + RetryOnKnownErrorMessageTestSpec create() { + return new RetryOnKnownErrorMessageTestSpec(mockSpecs, subject, success); + } + + public Builder mock(CommandActionSpecs v) { + mockSpecs.add(Objects.requireNonNull(v)); + return this; + } + + public Builder mock(CommandActionSpecs.Builder v) { + return mock(v.create()); + } + + public Builder repeatLastMoc() { + return mock(mockSpecs.getLast()); + } + + public Builder subject(String v) { + subject = v; + return this; + } + + public Builder success(boolean v) { + success = v; + return this; + } + + public Builder success() { + return success(true); + } + + private final List mockSpecs = new ArrayList<>(); + private String subject; + private boolean success; + } + } +} diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/MockUtils.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/MockUtils.java new file mode 100644 index 00000000000..e88077a6c9d --- /dev/null +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/MockUtils.java @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2026, 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. + */ + +package jdk.jpackage.internal; + +import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; + +import java.io.PrintWriter; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.UnaryOperator; +import java.util.spi.ToolProvider; +import jdk.internal.util.OperatingSystem; +import jdk.jpackage.internal.cli.CliBundlingEnvironment; +import jdk.jpackage.internal.cli.Main; +import jdk.jpackage.internal.util.function.ExceptionBox; +import jdk.jpackage.test.mock.Script; +import jdk.jpackage.test.mock.ToolProviderCommandMock; +import jdk.jpackage.test.mock.VerbatimCommandMock; + +/** + * Bridges "jdk.jpackage.internal" and "jdk.jpackage.test.mock" packages. + */ +public final class MockUtils { + + private MockUtils() { + } + + public static JPackageToolProviderBuilder buildJPackage() { + return new JPackageToolProviderBuilder(); + } + + public static final class JPackageToolProviderBuilder { + + public ToolProvider create() { + return createJPackageToolProvider(os(), createObjectFactory()); + } + + public Consumer createGlobalsMutator() { + var objectFactory = createObjectFactory(); + return globals -> { + globals.objectFactory(objectFactory); + }; + } + + public void applyToGlobals() { + createGlobalsMutator().accept(Globals.instance()); + } + + ExecutorFactory createExecutorFactory() { + var commandMocksExecutorFactory = Optional.ofNullable(script).map(MockUtils::withCommandMocks).map(mapper -> { + return mapper.apply(ExecutorFactory.DEFAULT); + }).orElse(ExecutorFactory.DEFAULT); + + var recordingExecutorFactory = Optional.ofNullable(listener).map(MockUtils::withCommandListener).map(mapper -> { + return mapper.apply(commandMocksExecutorFactory); + }).orElse(commandMocksExecutorFactory); + + return recordingExecutorFactory; + } + + ObjectFactory createObjectFactory() { + var executorFactory = createExecutorFactory(); + if (executorFactory == ExecutorFactory.DEFAULT) { + return ObjectFactory.DEFAULT; + } else { + return ObjectFactory.build().executorFactory(executorFactory).create(); + } + } + + public JPackageToolProviderBuilder listener(Consumer> v) { + listener = v; + return this; + } + + public JPackageToolProviderBuilder script(Script v) { + script = v; + return this; + } + + public JPackageToolProviderBuilder os(OperatingSystem v) { + os = v; + return this; + } + + private OperatingSystem os() { + return Optional.ofNullable(os).orElseGet(OperatingSystem::current); + } + + private Consumer> listener; + private OperatingSystem os; + private Script script; + } + + public static ToolProvider createJPackageToolProvider(OperatingSystem os, Script script) { + return buildJPackage() + .os(Objects.requireNonNull(os)) + .script(Objects.requireNonNull(script)) + .create(); + } + + public static ToolProvider createJPackageToolProvider(Script script) { + return createJPackageToolProvider(OperatingSystem.current(), script); + } + + private static UnaryOperator withCommandListener(Consumer> listener) { + Objects.requireNonNull(listener); + return executorFactory -> { + Objects.requireNonNull(executorFactory); + return () -> { + var executor = executorFactory.executor(); + + Optional> oldMapper = executor.mapper(); + + UnaryOperator newMapper = exec -> { + listener.accept(exec.commandLine()); + return exec; + }; + + return executor.mapper(oldMapper.map(newMapper::compose).orElse(newMapper)::apply); + }; + }; + } + + private static UnaryOperator withCommandMocks(Script script) { + return executorFactory -> { + Objects.requireNonNull(executorFactory); + return () -> { + var executor = executorFactory.executor(); + + Optional> oldMapper = executor.mapper(); + + UnaryOperator newMapper = exec -> { + var commandLine = exec.commandLine(); + var mock = Objects.requireNonNull(script.map(commandLine)); + switch (mock) { + case VerbatimCommandMock.INSTANCE -> { + // No mock for this command line. + return exec; + } + case ToolProviderCommandMock tp -> { + // Create a copy of the executor with the old mapper to prevent further recursion. + var copy = exec.copy().mapper(oldMapper.orElse(null)); + copy.toolProvider(tp); + copy.args().clear(); + copy.args(commandLine.subList(1, commandLine.size())); + return copy; + } + default -> { + // Unreachable because there are no other cases for this switch. + throw ExceptionBox.reachedUnreachable(); + } + } + }; + + return executor.mapper(oldMapper.map(newMapper::compose).orElse(newMapper)::apply); + }; + }; + } + + public static CliBundlingEnvironment createBundlingEnvironment(OperatingSystem os) { + Objects.requireNonNull(os); + + String bundlingEnvironmentClassName; + switch (os) { + case WINDOWS -> { + bundlingEnvironmentClassName = "WinBundlingEnvironment"; + } + case LINUX -> { + bundlingEnvironmentClassName = "LinuxBundlingEnvironment"; + } + case MACOS -> { + bundlingEnvironmentClassName = "MacBundlingEnvironment"; + } + default -> { + throw new IllegalArgumentException(); + } + } + + return toSupplier(() -> { + var ctor = Class.forName(String.join(".", + DefaultBundlingEnvironment.class.getPackageName(), + bundlingEnvironmentClassName + )).getConstructor(); + return (CliBundlingEnvironment)ctor.newInstance(); + }).get(); + } + + static ToolProvider createJPackageToolProvider(OperatingSystem os, ObjectFactory of) { + Objects.requireNonNull(os); + Objects.requireNonNull(of); + + var impl = new Main.Provider(DefaultBundlingEnvironment.runOnce(() -> { + return createBundlingEnvironment(os); + })); + + return new ToolProvider() { + + @Override + public int run(PrintWriter out, PrintWriter err, String... args) { + return Globals.main(() -> { + Globals.instance().objectFactory(of); + return impl.run(out, err, args); + }); + } + + @Override + public String name() { + return impl.name(); + } + }; + } +} diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.excludes b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.excludes index 0e7545bd83d..07757211927 100644 --- a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.excludes +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.excludes @@ -4,7 +4,6 @@ ErrorTest.test(IMAGE; app-desc=Hello; args-add=[--app-version, 1.]; errors=[mess ErrorTest.test(IMAGE; app-desc=Hello; args-add=[--app-version, 1.b.3]; errors=[message.error-header+[error.version-string-invalid-component, 1.b.3, b.3]]) ErrorTest.test(IMAGE; app-desc=Hello; args-add=[--app-version, ]; errors=[message.error-header+[error.version-string-empty]]) ErrorTest.test(IMAGE; app-desc=Hello; args-add=[--jlink-options, --add-modules]; errors=[message.error-header+[error.blocked.option, --add-modules]]) -ErrorTest.test(IMAGE; app-desc=Hello; args-add=[--jlink-options, --foo]; errors=[message.error-header+[error.jlink.failed, Error: unknown option: --foo]]) ErrorTest.test(IMAGE; app-desc=Hello; args-add=[--jlink-options, --module-path]; errors=[message.error-header+[error.blocked.option, --module-path]]) ErrorTest.test(IMAGE; app-desc=Hello; args-add=[--jlink-options, --output]; errors=[message.error-header+[error.blocked.option, --output]]) ErrorTest.test(IMAGE; app-desc=Hello; args-add=[--main-jar, non-existent.jar]; errors=[message.error-header+[error.main-jar-does-not-exist, non-existent.jar]]) diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.java index a85b5015e73..e15d5130d43 100644 --- a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.java +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.java @@ -200,13 +200,13 @@ public class OptionsValidationFailTest { Stream.of("--jpt-run=ErrorTest") ).flatMap(x -> x).toArray(String[]::new)).map(dynamicTest -> { return DynamicTest.dynamicTest(dynamicTest.getDisplayName(), () -> { - JPackageCommand.withToolProvider(jpackageToolProviderMock, () -> { + JPackageCommand.withToolProvider(() -> { try { dynamicTest.getExecutable().execute(); } catch (Throwable t) { throw ExceptionBox.toUnchecked(ExceptionBox.unbox(t)); } - }); + }, jpackageToolProviderMock); }); }); } diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/StandardOptionTest.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/StandardOptionTest.java index b786f484cb4..4aa3d5f72c1 100644 --- a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/StandardOptionTest.java +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/StandardOptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -341,9 +341,33 @@ public class StandardOptionTest extends JUnitAdapter.TestSrcInitializer { Arguments.of("abc", List.of("abc")), Arguments.of("a b c", List.of("a", "b", "c")), Arguments.of("a=10 -Dorg.acme.name='John Smith' c=\\\"foo\\\"", List.of("a=10", "-Dorg.acme.name=John Smith", "c=\"foo\"")), + Arguments.of(" foo \"a b c\" v=' John Smith ' 'H e ll o' ", List.of("foo", "a b c", "v= John Smith ", "H e ll o")), Arguments.of("\"\"", List.of("")), Arguments.of(" ", List.of()), - Arguments.of("", List.of()) + Arguments.of(" ", List.of()), + Arguments.of(" foo ", List.of("foo")), + Arguments.of("", List.of()), + Arguments.of("'fo\"o'\\ buzz \"b a r\"", List.of("fo\"o\\ buzz", "b a r")), + Arguments.of("a\\ 'b\"c'\\ d", List.of("a\\ b\"c\\ d")), + Arguments.of("\"a 'bc' d\"", List.of("a 'bc' d")), + Arguments.of("\'a 'bc' d\'", List.of("a bc d")), + Arguments.of("\"a \\'bc\\' d\"", List.of("a 'bc' d")), + Arguments.of("\'a \\'bc\\' d\'", List.of("a 'bc' d")), + Arguments.of("'a b c' 'd e f'", List.of("a b c", "d e f")), + Arguments.of("'a b c' \"'d e f' h", List.of("a b c", "'d e f' h")), + Arguments.of("'a b c' \"'d e f' \t ", List.of("a b c", "'d e f'")), + Arguments.of(" a='' '' \t '\\'\\'' \"\" \"\\\"\\\"\" ", List.of("a=", "", "\'\'", "", "\"\"")), + Arguments.of("' \'foo '", List.of(" foo", "")), + Arguments.of("' \'foo ' bar", List.of(" foo", " bar")), + Arguments.of("' \'foo\\ '", List.of(" foo\\ ")), + Arguments.of("'fo\"o buzz \"b a r\"", List.of("fo\"o buzz \"b a r\"")), + Arguments.of("'", List.of("")), + Arguments.of("' f g ", List.of(" f g")), + Arguments.of("' f g", List.of(" f g")), + Arguments.of("'\\'", List.of("'")), + Arguments.of("'\\' ", List.of("'")), + Arguments.of("'\\' a ", List.of("' a")), + Arguments.of("\"" + "\\\"".repeat(10000) + "A", List.of("\"".repeat(10000) + "A")) ); } diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTest.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTest.java new file mode 100644 index 00000000000..f1d8c142eb9 --- /dev/null +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTest.java @@ -0,0 +1,1846 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.internal.util; + +import static java.util.stream.Collectors.joining; +import static jdk.jpackage.internal.util.CommandOutputControlTestUtils.isInterleave; +import static jdk.jpackage.internal.util.function.ThrowingConsumer.toConsumer; +import static jdk.jpackage.internal.util.function.ThrowingRunnable.toRunnable; +import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; +import static jdk.jpackage.test.JUnitUtils.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.UncheckedIOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.spi.ToolProvider; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import jdk.internal.util.OperatingSystem; +import jdk.jpackage.internal.util.function.ExceptionBox; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIf; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.EnabledIf; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.EnumSource.Mode; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +public class CommandOutputControlTest { + + @DisabledIf("cherryPickSavedOutputTestCases") + @ParameterizedTest + @MethodSource + public void testSavedOutput(OutputTestSpec spec) { + spec.test(); + } + + /** + * Runs cherry-picked {@link OutputTestSpec} test cases. + *

    + * This test method is mutual exclusive with + * {@link #testSavedOutput(OutputTestSpec)} and is aimed for debugging + * {@code OutputTestSpec} test cases. + *

    + * It is disabled by default. To enable it, manually edit {@link #testSomeSavedOutput()}. + * + * @see #testSomeSavedOutput() + * + * @param spec the test case + */ + @EnabledIf("cherryPickSavedOutputTestCases") + @ParameterizedTest + @MethodSource + public void testSomeSavedOutput(OutputTestSpec spec) { + System.out.println(spec); + spec.test(); + } + + @ParameterizedTest + @MethodSource + public void testDumpStreams(OutputTestSpec spec) { + spec.test(); + } + + @ParameterizedTest + @MethodSource + public void testCharset(CharsetTestSpec spec) throws IOException, InterruptedException { + spec.test(); + } + + @ParameterizedTest + @MethodSource + public void test_description(CommandOutputControlSpec spec) { + // This test is mostly for coverage. + var desc = spec.create().description(); + assertFalse(desc.isBlank()); + } + + @Test + public void test_copy() { + var orig = new CommandOutputControl(); + var copy = orig.copy(); + assertNotSame(orig, copy); + } + + @ParameterizedTest + @EnumSource(names = "SAVE_NOTHING", mode = Mode.EXCLUDE) + public void test_flag(OutputControl flag) { + var coc = new CommandOutputControl(); + assertFalse(flag.get(coc)); + flag.set(coc); + assertTrue(flag.get(coc)); + if (flag.canUnset()) { + flag.unset(coc); + assertFalse(flag.get(coc)); + } + } + + @ParameterizedTest + @MethodSource + public void test_mutual_exclusive_flags(List controls) { + if (controls.isEmpty()) { + throw new IllegalArgumentException(); + } + + var coc = new CommandOutputControl(); + for (var c : controls) { + c.set(coc); + } + + for (var c : controls.subList(0, controls.size() - 1)) { + assertFalse(c.get(coc)); + } + assertTrue(controls.getLast().get(coc)); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_ExecutableAttributes(boolean toolProvider) { + var coc = new CommandOutputControl(); + CommandOutputControl.Executable exec; + if (toolProvider) { + exec = coc.createExecutable(new ToolProvider() { + + @Override + public String name() { + return "runme"; + } + + @Override + public int run(PrintWriter out, PrintWriter err, String... args) { + fail("Should never be called"); + return 0; + } + + }, "--foo", "--baz=10"); + } else { + exec = coc.createExecutable(new ProcessBuilder("runme", "--foo", "--baz=10")); + } + + assertEquals("runme --foo --baz=10", exec.attributes().toString()); + } + + @Test + public void test_Result_no_args_ctor() { + var result = new CommandOutputControl.Result(7); + assertFalse(result.findContent().isPresent()); + assertFalse(result.findStdout().isPresent()); + assertFalse(result.findStderr().isPresent()); + assertEquals(7, result.getExitCode()); + assertSame(Objects.requireNonNull(CommandOutputControl.EMPTY_EXECUTABLE_ATTRIBUTES), result.execAttrs()); + } + + @Test + public void test_Result_expectExitCode() throws IOException { + var result = new CommandOutputControl.Result(7); + + assertSame(result, result.expectExitCode(7)); + assertSame(result, result.expectExitCode(7, 2)); + assertSame(result, result.expectExitCode(2, 7)); + + assertSame(result, result.expectExitCode(List.of(7))); + assertSame(result, result.expectExitCode(Set.of(7, 2))); + assertSame(result, result.expectExitCode(List.of(2, 7))); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_Result_expectExitCode_negative(boolean collection) { + var result = new CommandOutputControl.Result(3); + + var ex = assertThrowsExactly(CommandOutputControl.UnexpectedExitCodeException.class, () -> { + if (collection) { + result.expectExitCode(List.of(17, 12)); + } else { + result.expectExitCode(17, 12); + } + }); + + assertNull(ex.getCause()); + assertSame(result, ex.getResult()); + assertEquals("Unexpected exit code 3 from executing the command ", ex.getMessage()); + } + + @ParameterizedTest + @MethodSource + public void test_Result_toCharacterResult(ToCharacterResultTestSpec spec) throws IOException, InterruptedException { + spec.test(); + } + + @Test + public void test_Result_toCharacterResult_nop() throws IOException, InterruptedException { + + var charset = StandardCharsets.UTF_8; + + var emptyResult = new CommandOutputControl.Result(7); + assertSame(emptyResult, emptyResult.toCharacterResult(charset, true)); + assertSame(emptyResult, emptyResult.toCharacterResult(charset, false)); + + var coc = new CommandOutputControl().saveOutput(true); + + var result = coc.createExecutable(new Command(List.of("foo"), List.of()).asToolProvider()).execute(); + + assertSame(result, result.toCharacterResult(charset, true)); + assertSame(result, result.toCharacterResult(charset, false)); + } + + @Test + public void test_Result_toCharacterResult_copyWithExecutableAttributes() { + + var empty = new CommandOutputControl.Result(0); + + var execAttrs = new CommandOutputControl.ExecutableAttributes() { + @Override + public String toString() { + return "foo"; + } + + @Override + public List commandLine() { + return List.of(); + } + }; + + var copy = empty.copyWithExecutableAttributes(execAttrs); + + assertSame(empty.exitCode(), copy.exitCode()); + assertSame(empty.output(), copy.output()); + assertSame(empty.byteOutput(), copy.byteOutput()); + assertSame(execAttrs, copy.execAttrs()); + } + + @ParameterizedTest + @EnumSource(ExecutableType.class) + public void test_timeout_expires(ExecutableType mode) throws InterruptedException, IOException { + + final var toolProvider = (mode == ExecutableType.TOOL_PROVIDER); + final var storeOutputInFiles = (mode == ExecutableType.PROCESS_BUILDER_WITH_STREAMS_IN_FILES); + + var actions = List.of( + CommandAction.echoStdout("The quick brown fox jumps"), + CommandAction.sleep(5), + CommandAction.echoStdout("over the lazy dog") + ); + + var coc = new CommandOutputControl().saveOutput(true).dumpOutput(true).storeOutputInFiles(storeOutputInFiles); + + CommandOutputControl.Executable exec; + + InterruptibleToolProvider tp; + + if (toolProvider) { + tp = new InterruptibleToolProvider(Command.createToolProvider(actions)); + exec = coc.createExecutable(tp); + } else { + var cmdline = Command.createShellCommandLine(actions); + tp = null; + exec = coc.createExecutable(new ProcessBuilder(cmdline)); + } + + var result = exec.execute(1, TimeUnit.SECONDS); + assertFalse(result.exitCode().isPresent()); + + var getExitCodeEx = assertThrowsExactly(IllegalStateException.class, result::getExitCode); + assertEquals(("Exit code is unavailable for timed-out command"), getExitCodeEx.getMessage()); + + // We want to check that the saved output contains only the text emitted before the "sleep" action. + // It works for a subprocess, but in the case of a ToolProvider, sometimes the timing is such + // that it gets interrupted before having written anything to the stdout, and the saved output is empty. + // This happens when the test case is executed together with other test cases + // and never when it is executed individually. + if (!toolProvider || !result.content().isEmpty()) { + assertEquals(List.of("The quick brown fox jumps"), result.content()); + } + + if (toolProvider) { + assertTrue(tp.interrupted()); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_timeout(boolean toolProvider) throws InterruptedException, IOException { + + var actions = List.of( + CommandAction.echoStdout("Sphinx of black quartz,"), + CommandAction.echoStdout("judge my vow") + ); + + var coc = new CommandOutputControl().saveOutput(true).dumpOutput(true); + + CommandOutputControl.Executable exec; + + if (toolProvider) { + var tp = Command.createToolProvider(actions); + exec = coc.createExecutable(tp); + } else { + var cmdline = Command.createShellCommandLine(actions); + exec = coc.createExecutable(new ProcessBuilder(cmdline)); + } + + var result = exec.execute(10, TimeUnit.SECONDS); + assertTrue(result.exitCode().isPresent()); + assertEquals(List.of("Sphinx of black quartz,", "judge my vow"), result.content()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_passthrough_exceptions(boolean withTimeout) throws IOException { + + var expected = new RuntimeException("Kaput!"); + + var exec = new CommandOutputControl().createExecutable(new ToolProvider() { + + @Override + public String name() { + return "foo"; + } + + @Override + public int run(PrintWriter out, PrintWriter err, String... args) { + throw expected; + } + }); + + var actual = assertThrowsExactly(expected.getClass(), () -> { + if (withTimeout) { + exec.execute(10, TimeUnit.SECONDS); + } else { + exec.execute(); + } + }); + + assertSame(expected, actual); + } + + @Test + public void test_externally_terminated() throws InterruptedException, IOException { + var cmdline = Command.createShellCommandLine(List.of( + CommandAction.echoStderr("The five boxing wizards"), + CommandAction.sleep(10), + CommandAction.echoStderr("jump quickly") + )); + + var processDestroyer = Slot.>createEmpty(); + + var coc = new CommandOutputControl().saveOutput(true).dumpOutput(true).processListener(process -> { + // Once we are notified the process has been started, schedule its destruction. + // Give it a second to warm up and print some output and then destroy it. + processDestroyer.set(CompletableFuture.runAsync(toRunnable(() -> { + Thread.sleep(Duration.ofSeconds(1)); + // On Windows, CommandAction#sleep is implemented with the "ping" command. + // By some reason, when the parent "cmd" process is destroyed, + // the child "ping" command stays alive, and the test waits when it completes, + // making it last for at least 10 seconds. + // To optimize the test work time, destroy the entire subprocess tree. + // Even though this is essential on Windows keep this logic on all platforms for simplicity. + var descendants = List.of(); + try (var descendantsStream = process.descendants()) { + descendants = descendantsStream.toList(); + } finally { + process.destroyForcibly(); + } + descendants.forEach(ProcessHandle::destroyForcibly); + }))); + }); + var exec = coc.createExecutable(new ProcessBuilder(cmdline)); + + var result = exec.execute(); + assertNotEquals(0, result.getExitCode()); + assertEquals(List.of("The five boxing wizards"), result.content()); + processDestroyer.get().join(); + } + + @DisabledOnOs(value = OS.MAC, disabledReason = "Closing a stream doesn't consistently cause a trouble as it should") + @ParameterizedTest + @EnumSource(OutputStreams.class) + public void test_close_streams(OutputStreams action) throws InterruptedException, IOException { + var cmdline = Command.createShellCommandLine(List.of( + CommandAction.echoStdout("Hello stdout"), + CommandAction.echoStderr("Bye stderr") + )); + + var coc = new CommandOutputControl().saveOutput(true).dumpOutput(true).processListener(toConsumer(process -> { + // Close process output stream(s). This should make corresponding stream gobbler(s) throw IOException. + switch (action) { + case STDOUT -> { + process.getInputStream().close(); + } + case STDERR -> { + process.getErrorStream().close(); + } + case STDOUT_AND_STDERR -> { + process.getInputStream().close(); + process.getErrorStream().close(); + } + } + })); + var exec = coc.createExecutable(new ProcessBuilder(cmdline)); + + var ex = assertThrows(IOException.class, exec::execute); + System.out.println("test_close_streams: " + action); + ex.printStackTrace(System.out); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_interleaved(boolean customDumpStreams) throws IOException, InterruptedException { + var cmdline = Command.createShellCommandLine(List.of( + CommandAction.echoStdout("Eat some more"), + CommandAction.echoStderr("of these"), + CommandAction.echoStdout("soft French pastries"), + CommandAction.echoStderr("and drink some tea") + )); + + var coc = new CommandOutputControl(); + var exec = coc.createExecutable(new ProcessBuilder(cmdline)); + + coc.saveOutput(true).dumpOutput(true); + + CommandOutputControl.Result result; + + if (customDumpStreams) { + // Execute the command so that its stdout and stderr are dumped to the same sink. + var sink = new ByteArrayOutputStream(); + var ps = new PrintStream(sink); + + coc.dumpStdout(ps).dumpStderr(ps); + + result = exec.execute(); + + var commandStdout = List.of("Eat some more", "soft French pastries"); + var commandStderr = List.of("of these", "and drink some tea"); + + var sinkContent = toStringList(sink.toByteArray(), StandardCharsets.US_ASCII); + + if (!isInterleave(sinkContent, commandStdout, commandStderr)) { + fail(String.format("Unexpected combined output=%s; stdout=%s; stderr=%s", + sinkContent, commandStdout, commandStderr)); + } + + // CommandOutputControl was not configured to redirect stderr in stdout, + // hence the output is ordered: stdout goes first, stderr follows. + assertEquals(Stream.of(commandStdout, commandStderr).flatMap(List::stream).toList(), result.content()); + + // Saved stdout an stderr can be accessed individually. + assertEquals(commandStdout, result.stdout()); + assertEquals(commandStderr, result.stderr()); + } else { + // Execute the command so that its stdout and stderr are dumped into System.out. + coc.redirectStderr(true); + result = exec.execute(); + + // CommandOutputControl was configured to redirect stderr in stdout, + // hence the output is interleaved. + assertEquals(List.of("Eat some more", "of these", "soft French pastries", "and drink some tea"), result.content()); + + // Saved stdout an stderr can NOT be accessed individually because they are interleaved. + assertTrue(result.findStdout().isEmpty()); + assertTrue(result.findStderr().isEmpty()); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true}) + public void stressTest(boolean binaryOutput, @TempDir Path workDir) throws Exception { + + // Execute multiple subprocesses asynchronously. + // Each subprocess writes a few chunks of data each larger than the default buffer size (8192 bytes) + + final var chunkCount = 5; + final var subprocessCount = 100; + final var subprocessExecutor = Executors.newVirtualThreadPerTaskExecutor(); + + final var md = MessageDigest.getInstance("MD5"); + + var cmdline = Command.createShellCommandLine(IntStream.range(0, chunkCount).mapToObj(chunk -> { + byte[] bytes = new byte[10 * 1024]; // 10K to exceed the default BufferedOutputStream's buffer size of 8192. + new Random().nextBytes(bytes); + md.update(bytes); + var path = workDir.resolve(Integer.toString(chunk)); + try { + Files.write(path, bytes); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + return path; + }).map(CommandAction::cat).toList()); + + final var digest = HexFormat.of().formatHex(md.digest()); + + // Schedule to start every subprocess in a separate virtual thread. + // Start and suspend threads, waiting until all scheduled threads have started. + // After all scheduled threads start, resume them. + // This should result in starting all scheduled subprocesses simultaneously. + + var readyLatch = new CountDownLatch(subprocessCount); + var startLatch = new CountDownLatch(1); + + var futures = IntStream.range(0, subprocessCount).mapToObj(_ -> { + return CompletableFuture.supplyAsync(toSupplier(() -> { + + var exec = new CommandOutputControl() + .saveOutput(true) + .binaryOutput(binaryOutput) + .createExecutable(new ProcessBuilder(cmdline)); + + readyLatch.countDown(); + startLatch.await(); + + var result = exec.execute(); + + var localMd = MessageDigest.getInstance("MD5"); + localMd.update(result.byteContent()); + + return HexFormat.of().formatHex(localMd.digest()); + + }), subprocessExecutor); + }).toList(); + + readyLatch.await(); + startLatch.countDown(); + + CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join(); + + futures.forEach(future -> { + var actualDigest = future.join(); + assertEquals(digest, actualDigest); + }); + } + + public enum OutputStreams { + STDOUT, + STDERR, + STDOUT_AND_STDERR + } + + private static List test_description() { + List testCases = new ArrayList<>(); + testCases.add(new CommandOutputControlSpec(Set.of())); + for (var outputControl : OutputControl.variants()) { + testCases.add(new CommandOutputControlSpec(outputControl)); + } + return testCases; + } + + private static List> test_mutual_exclusive_flags() { + List> data = new ArrayList<>(); + + var flags = List.of(OutputControl.SAVE_ALL, OutputControl.SAVE_FIRST_LINE, OutputControl.SAVE_NOTHING); + + List seq = new ArrayList<>(); + for (var _1 : flags) { + seq.add(_1); + var flags2 = flags.stream().filter(Predicate.isEqual(_1).negate()).toList(); + for (var _2 : flags2) { + seq.add(_2); + var flags3 = flags2.stream().filter(Predicate.isEqual(_2).negate()).toList(); + for (var _3 : flags3) { + seq.add(_3); + data.add(List.copyOf(seq)); + seq.removeLast(); + } + seq.removeLast(); + } + seq.removeLast(); + } + + return data; + } + + public record ToCharacterResultTestSpec(OutputTestSpec execSpec, boolean keepByteContent) { + + public ToCharacterResultTestSpec { + Objects.requireNonNull(execSpec); + } + + @Override + public String toString() { + final List tokens = new ArrayList<>(); + + tokens.add(execSpec.toString()); + if (keepByteContent) { + tokens.add("keepByteContent"); + } + + return String.join(", ", tokens.toArray(String[]::new)); + } + + void test() throws IOException, InterruptedException { + var coc = execSpec.cocSpec().create(); + + var command = execSpec.commandSpec().command().asToolProvider(); + + var expected = coc.binaryOutput(false).createExecutable(command).execute(); + + var byteResult = coc.binaryOutput(true).createExecutable(command).execute(); + + var actual = byteResult.toCharacterResult(coc.charset(), keepByteContent); + + CommandOutputControl.Result expectedByteContent; + if (keepByteContent) { + expectedByteContent = byteResult; + } else { + expectedByteContent = expected; + } + + assertArrayEquals(expectedByteContent.findByteContent().orElse(null), actual.findByteContent().orElse(null)); + assertArrayEquals(expectedByteContent.findByteStdout().orElse(null), actual.findByteStdout().orElse(null)); + assertArrayEquals(expectedByteContent.findByteStderr().orElse(null), actual.findByteStderr().orElse(null)); + + assertEquals(expected.findContent(), actual.findContent()); + assertEquals(expected.findStdout(), actual.findStdout()); + assertEquals(expected.findStderr(), actual.findStderr()); + + assertSame(byteResult.execAttrs(), actual.execAttrs()); + assertEquals(expected.exitCode(), actual.exitCode()); + } + } + + private static Stream test_Result_toCharacterResult() { + List testCases = new ArrayList<>(); + + var skip = Set.of(OutputControl.BINARY_OUTPUT, OutputControl.DUMP, OutputControl.SAVE_FIRST_LINE); + + for (var outputControl : OutputControl.variants().stream().filter(spec -> { + return !skip.stream().anyMatch(spec::contains); + }).toList()) { + for (var stdoutContent : List.of(OutputData.EMPTY, OutputData.MANY)) { + for (var stderrContent : List.of(OutputData.EMPTY, OutputData.MANY)) { + var commandSpec = new CommandSpec(stdoutContent, stderrContent); + testCases.add(new OutputTestSpec(false, new CommandOutputControlSpec(outputControl), commandSpec)); + } + } + } + + return testCases.stream().flatMap(execSpec -> { + return Stream.of(true, false).map(keepByteContent -> { + return new ToCharacterResultTestSpec(execSpec, keepByteContent); + }); + }); + } + + private static boolean cherryPickSavedOutputTestCases() { + return !testSomeSavedOutput().isEmpty(); + } + + /** + * Returns test cases for {@link #testSomeSavedOutput(OutputTestSpec)}. + *

    + * Aimed to simplify debugging of {@link #OutputTestSpec} test cases. + *

    + * The total number of {@code #OutputTestSpec} test cases is ~1500. When some + * fail and need debugging, it is a waste of time to run them all. This method + * allows running only selected test cases. It works this way: + *

      + *
    • Run CommandOutputControlTest test. + *
    • If some {@linke #testSavedOutput(OutputTestSpec)} invocations fail, + * capture their IDs (test case ID is an index starting from 1). + *
    • Replace "/* 10, 67, 456 */" comment in the body of this method with + * the captured test case IDs. + *
    • Rerun CommandOutputControlTest test. This time, it will run + * {@link #testSomeSavedOutput(OutputTestSpec)} method instead of + * {@link #testSavedOutput(OutputTestSpec)} with the list of the captured test + * case IDs. + *
    + */ + private static List testSomeSavedOutput() { + var testIds = List.of(/* 10, 67, 456 */); + if (testIds.isEmpty()) { + return List.of(); + } else { + var allTestCases = testSavedOutput(); + return testIds.stream().map(testId -> { + return allTestCases.get(testId - 1); + }).toList(); + } + } + + private static List testSavedOutput() { + List testCases = new ArrayList<>(); + for (final var executableType : List.of(ExecutableType.values())) { + for (var outputControl : OutputControl.variants()) { + for (final var stdoutContent : List.of(OutputData.values())) { + for (final var stderrContent : List.of(OutputData.values())) { + + if (outputControl.contains(OutputControl.BINARY_OUTPUT) + && (stdoutContent == OutputData.ONE_LINE || stderrContent == OutputData.ONE_LINE)) { + // Skip a test case if it runs a command writing + // a single line in stdout or stderr, and handles command output as a byte stream. + // It duplicates test cases that write multiple lines in stdout or stderr. + continue; + } + + final var commandSpec = new CommandSpec(stdoutContent, stderrContent); + boolean toolProvider; + switch (executableType) { + case PROCESS_BUILDER -> { + toolProvider = false; + } + case PROCESS_BUILDER_WITH_STREAMS_IN_FILES -> { + outputControl = new SetBuilder() + .add(outputControl) + .add(OutputControl.STORE_STREAMS_IN_FILES) + .create(); + toolProvider = false; + } + case TOOL_PROVIDER -> { + toolProvider = true; + } + default -> { + // Unreachable + throw ExceptionBox.reachedUnreachable(); + } + } + testCases.add(new OutputTestSpec( + toolProvider, + new CommandOutputControlSpec(outputControl), + commandSpec)); + } + } + } + } + return testCases; + } + + private static List testDumpStreams() { + List testCases = new ArrayList<>(); + final var commandSpec = new CommandSpec(OutputData.MANY, OutputData.MANY); + for (var discardStdout : withAndWithout(OutputControl.DISCARD_STDOUT)) { + for (var discardStderr : withAndWithout(OutputControl.DISCARD_STDERR)) { + for (var redirectStderr : withAndWithout(OutputControl.REDIRECT_STDERR)) { + for (var binaryOutput : withAndWithout(OutputControl.BINARY_OUTPUT)) { + for (var dumpStdout : withAndWithout(OutputControl.DUMP_STDOUT_IN_SYSTEM_OUT)) { + for (var dumpStderr : withAndWithout(OutputControl.DUMP_STDERR_IN_SYSTEM_ERR)) { + + if (dumpStderr.isEmpty() && dumpStdout.isEmpty()) { + // Output dumping disabled + continue; + } + + if (discardStderr.isPresent() && discardStdout.isPresent()) { + // Output dumping enabled, but all stream discarded + continue; + } + + if (dumpStderr.isPresent() == discardStderr.isPresent() && dumpStdout.isEmpty()) { + // Stderr dumping enabled but discarded, stdout dumping disabled + continue; + } + + if (dumpStdout.isPresent() == discardStdout.isPresent() && dumpStderr.isEmpty()) { + // Stdout dumping enabled but discarded, stderr dumping disabled + continue; + } + + final var outputControl = new HashSet(); + outputControl.add(OutputControl.DUMP); + discardStdout.ifPresent(outputControl::add); + discardStderr.ifPresent(outputControl::add); + redirectStderr.ifPresent(outputControl::add); + binaryOutput.ifPresent(outputControl::add); + dumpStdout.ifPresent(outputControl::add); + dumpStderr.ifPresent(outputControl::add); + + testCases.add(new OutputTestSpec( + false, + new CommandOutputControlSpec(outputControl), + commandSpec)); + } + } + } + } + } + } + return testCases; + } + + private static List testCharset() { + List testCases = new ArrayList<>(); + + for (boolean toolProvider : BOOLEAN_VALUES) { + for (var redirectStderr : withAndWithout(OutputControl.REDIRECT_STDERR)) { + for (var charset : withAndWithout(OutputControl.CHARSET_UTF16LE)) { + var stdoutSink = new CharsetTestSpec.DumpOutputSink(StandardCharsets.US_ASCII, OutputStreams.STDOUT); + var stderrSink = new CharsetTestSpec.DumpOutputSink(StandardCharsets.UTF_32LE, OutputStreams.STDERR); + var outputControl = new HashSet(); + redirectStderr.ifPresent(outputControl::add); + charset.ifPresent(outputControl::add); + outputControl.add(stdoutSink); + outputControl.add(stderrSink); + testCases.add(new CharsetTestSpec(toolProvider, new CommandOutputControlSpec(outputControl))); + } + } + } + + return testCases; + } + + private enum ExecutableType { + TOOL_PROVIDER, + PROCESS_BUILDER, + PROCESS_BUILDER_WITH_STREAMS_IN_FILES, + ; + } + + private sealed interface CommandAction { + static SleepCommandAction sleep(int seconds) { + return new SleepCommandAction(seconds); + } + + static EchoCommandAction echoStdout(String str) { + return new EchoCommandAction(str, false); + } + + static EchoCommandAction echoStderr(String str) { + return new EchoCommandAction(str, true); + } + + static WriteCommandAction writeStdout(byte[] binary) { + return new WriteCommandAction(binary, false); + } + + static WriteCommandAction writeStderr(byte[] binary) { + return new WriteCommandAction(binary, true); + } + + static CatCommandAction cat(Path file) { + return new CatCommandAction(file); + } + } + + private record EchoCommandAction(String value, boolean stderr) implements CommandAction { + EchoCommandAction { + Objects.requireNonNull(value); + } + } + + private record WriteCommandAction(byte[] value, boolean stderr) implements CommandAction { + WriteCommandAction { + Objects.requireNonNull(value); + } + } + + private record CatCommandAction(Path file) implements CommandAction { + CatCommandAction { + Objects.requireNonNull(file); + } + } + + private record SleepCommandAction(int seconds) implements CommandAction { + SleepCommandAction { + if (seconds < 0) { + throw new IllegalArgumentException(); + } + } + } + + private record Command(List stdout, List stderr) { + Command { + stdout.forEach(Objects::requireNonNull); + stderr.forEach(Objects::requireNonNull); + } + + List asExecutable() { + return createShellCommandLine(actions()); + } + + ToolProvider asToolProvider() { + return createToolProvider(actions()); + } + + // + // Type of shell for which to create a command line. + // On Unix it is always the "sh". + // On Windows, it is "cmd" by default and "powershell" when a command needs to write binary data to output stream(s). + // Extra complexity on Windows is because "powershell" is times slower than "cmd", + // and the latter doesn't support binary output. + // + private enum ShellType { + SH(OperatingSystem.LINUX, OperatingSystem.MACOS), + CMD(OperatingSystem.WINDOWS), + POWERSHELL(OperatingSystem.WINDOWS), + ; + + ShellType(OperatingSystem... os) { + if (os.length == 0) { + throw new IllegalArgumentException(); + } + this.os = Set.of(os); + } + + boolean isSupportedOnCurrentOS() { + return os.contains(OperatingSystem.current()); + } + + private final Set os; + } + + private List actions() { + return Stream.concat( + stdout.stream().map(CommandAction::echoStdout), + stderr.stream().map(CommandAction::echoStderr) + ).toList(); + } + + static List createShellCommandLine(List actions) { + final var shellType = detectShellType(actions); + final List commandline = new ArrayList<>(); + final String commandSeparator; + switch (shellType) { + case SH -> { + commandline.addAll(List.of("sh", "-c")); + commandSeparator = " && "; + } + case CMD -> { + commandline.addAll(List.of("cmd", "/C")); + commandSeparator = " && "; + } + case POWERSHELL -> { + commandline.addAll(List.of("powershell", "-NoProfile", "-Command")); + commandSeparator = "; "; + } + default -> { + // Unreachable + throw ExceptionBox.reachedUnreachable(); + } + } + commandline.add(actions.stream().map(action -> { + return Command.toString(action, shellType); + }).collect(joining(commandSeparator))); + return commandline; + } + + static ToolProvider createToolProvider(List actions) { + var copiedActions = List.copyOf(actions); + return new ToolProvider() { + + @Override + public int run(PrintWriter out, PrintWriter err, String... args) { + throw new UnsupportedOperationException(); + } + + @Override + public int run(PrintStream out, PrintStream err, String... args) { + for (var action : copiedActions) { + switch (action) { + case EchoCommandAction echo -> { + if (echo.stderr()) { + err.println(echo.value()); + } else { + out.println(echo.value()); + } + } + case WriteCommandAction write -> { + try { + if (write.stderr()) { + err.write(write.value()); + } else { + out.write(write.value()); + } + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + case SleepCommandAction sleep -> { + toRunnable(() -> { + synchronized (this) { + var millis = Duration.ofSeconds(sleep.seconds()).toMillis(); + this.wait(millis); + } + }).run(); + } + case CatCommandAction _ -> { + // Not used, no point to implement. + throw new UnsupportedOperationException(); + } + } + } + return 0; + } + + @Override + public String name() { + return "test"; + } + }; + } + + private static ShellType detectShellType(List actions) { + var supportedShellTypes = Stream.of(ShellType.values()) + .filter(ShellType::isSupportedOnCurrentOS) + .collect(Collectors.toCollection(HashSet::new)); + for (var action : actions) { + if (action instanceof WriteCommandAction) { + supportedShellTypes.remove(ShellType.CMD); + } + } + return supportedShellTypes.stream() + .sorted(Comparator.comparingInt(Enum::ordinal)) + .findFirst().orElseThrow(); + } + + private static String toString(CommandAction action, ShellType shellType) { + switch (action) { + case EchoCommandAction a -> { + return toString(a, shellType); + } + case WriteCommandAction a -> { + return toString(a, shellType); + } + case SleepCommandAction a -> { + return toString(a, shellType); + } + case CatCommandAction a -> { + return toString(a, shellType); + } + } + } + + private static String toString(EchoCommandAction echo, ShellType shellType) { + String str; + switch (shellType) { + case SH -> { + str = "echo " + echo.value(); + if (echo.stderr()) { + str += ">&2"; + } + } + case CMD -> { + str = "(echo " + echo.value() + ")"; + if (echo.stderr()) { + str += ">&2"; + } + } + case POWERSHELL -> { + str = String.format("[Console]::%s.WriteLine(\\\"%s\\\")", + echo.stderr() ? "Error" : "Out", echo.value()); + } + default -> { + // Unreachable + throw ExceptionBox.reachedUnreachable(); + } + } + return str; + } + + private static String toString(WriteCommandAction write, ShellType shellType) { + String str; + switch (shellType) { + case SH -> { + // Convert byte[] to octal string to make it work with POSIX printf. + // POSIX printf doesn't recognize hex strings, so can't use handy HexFormat. + var sb = new StringBuilder(); + sb.append("printf "); + for (var b : write.value()) { + sb.append("\\\\").append(Integer.toOctalString(b & 0xFF)); + } + if (write.stderr()) { + sb.append(">&2"); + } + str = sb.toString(); + } + case CMD -> { + throw new UnsupportedOperationException("Can't output binary data with 'cmd'"); + } + case POWERSHELL -> { + var base64 = Base64.getEncoder().encodeToString(write.value()); + str = String.format( + "$base64 = '%s'; " + + "$bytes = [Convert]::FromBase64String($base64); " + + "[Console]::%s().Write($bytes, 0, $bytes.Length)", + base64, write.stderr() ? "OpenStandardError" : "OpenStandardOutput"); + } + default -> { + // Unreachable + throw ExceptionBox.reachedUnreachable(); + } + } + return str; + } + + private static String toString(SleepCommandAction sleep, ShellType shellType) { + switch (shellType) { + case SH -> { + return "sleep " + sleep.seconds(); + } + case CMD -> { + // The standard way to sleep in "cmd" is to use the "ping" command. + // It sends packets every second. + // To wait N seconds, it should send N+1 packets. + // The "timeout" command works only in a console. + return String.format("(ping -n %d localhost > nul)", sleep.seconds() + 1); + } + case POWERSHELL -> { + return "Start-Sleep -Seconds " + sleep.seconds(); + } + default -> { + // Unreachable + throw ExceptionBox.reachedUnreachable(); + } + } + } + + private static String toString(CatCommandAction cat, ShellType shellType) { + switch (shellType) { + case SH -> { + return "cat " + cat.file(); + } + case CMD -> { + return "type " + cat.file(); + } + case POWERSHELL -> { + // Not used, no point to implement. + throw new UnsupportedOperationException(); + } + default -> { + // Unreachable + throw ExceptionBox.reachedUnreachable(); + } + } + } + + } + + private enum OutputData { + EMPTY(List.of()), + ONE_LINE(List.of("Jupiter")), + MANY(List.of("Uranus", "Saturn", "Earth")); + + OutputData(List data) { + data.forEach(Objects::requireNonNull); + this.data = data; + } + + final List data; + } + + private record CommandSpec(OutputData stdout, OutputData stderr) { + CommandSpec { + Objects.requireNonNull(stdout); + Objects.requireNonNull(stderr); + } + + @Override + public String toString() { + return String.format("[stdout=%s, stderr=%s]", stdout, stderr); + } + + Command command() { + return new Command(stdout.data.stream().map(line -> { + return "stdout." + line; + }).toList(), stderr.data.stream().map(line -> { + return "stderr." + line; + }).toList()); + } + } + + public interface CommandOutputControlMutator { + String name(); + void mutate(CommandOutputControl coc); + + static Function> addToSet(Set set) { + return m -> { + return new SetBuilder().add(set).add(m).create(); + }; + } + } + + public enum OutputControl implements CommandOutputControlMutator { + DUMP(CommandOutputControl::dumpOutput, CommandOutputControl::isDumpOutput), + SAVE_ALL(CommandOutputControl::saveOutput, CommandOutputControl::isSaveOutput), + SAVE_FIRST_LINE(CommandOutputControl::saveFirstLineOfOutput, CommandOutputControl::isSaveFirstLineOfOutput), + SAVE_NOTHING(coc -> { + coc.saveOutput(false); + }, coc -> { + return !coc.isSaveOutput() && !coc.isSaveFirstLineOfOutput(); + }), + DISCARD_STDOUT(CommandOutputControl::discardStdout, CommandOutputControl::isDiscardStdout), + DISCARD_STDERR(CommandOutputControl::discardStderr, CommandOutputControl::isDiscardStderr), + REDIRECT_STDERR(CommandOutputControl::redirectStderr, CommandOutputControl::isRedirectStderr), + STORE_STREAMS_IN_FILES(CommandOutputControl::storeOutputInFiles, CommandOutputControl::isStoreOutputInFiles), + BINARY_OUTPUT(CommandOutputControl::binaryOutput, CommandOutputControl::isBinaryOutput), + DUMP_STDOUT_IN_SYSTEM_OUT(coc -> { + coc.dumpStdout(new PrintStreamWrapper(System.out)); + }, coc -> { + return coc.dumpStdout() instanceof PrintStreamWrapper; + }), + DUMP_STDERR_IN_SYSTEM_ERR(coc -> { + coc.dumpStderr(new PrintStreamWrapper(System.err)); + }, coc -> { + return coc.dumpStderr() instanceof PrintStreamWrapper; + }), + CHARSET_UTF16LE(coc -> { + coc.charset(StandardCharsets.UTF_16LE); + }, coc -> { + return coc.charset() == StandardCharsets.UTF_16LE; + }), + ; + + OutputControl(Consumer setter, Function getter) { + this.setter = Objects.requireNonNull(setter); + this.unsetter = null; + this.getter = Objects.requireNonNull(getter); + } + + OutputControl(BiConsumer setter, Function getter) { + Objects.requireNonNull(setter); + this.setter = coc -> { + setter.accept(coc, true); + }; + this.unsetter = coc -> { + setter.accept(coc, false); + }; + this.getter = Objects.requireNonNull(getter); + } + + @Override + public void mutate(CommandOutputControl coc) { + set(coc); + } + + CommandOutputControl set(CommandOutputControl coc) { + setter.accept(coc); + return coc; + } + + CommandOutputControl unset(CommandOutputControl coc) { + Objects.requireNonNull(unsetter).accept(coc); + return coc; + } + + boolean canUnset() { + return unsetter != null; + } + + boolean get(CommandOutputControl coc) { + return getter.apply(coc); + } + + static List> variants() { + final List> variants = new ArrayList<>(); + for (final var binaryOutput : withAndWithout(BINARY_OUTPUT)) { + for (final var redirectStderr : withAndWithout(REDIRECT_STDERR)) { + for (final var withDump : withAndWithout(DUMP)) { + variants.addAll(Stream.of( + Set.of(), + Set.of(SAVE_ALL), + Set.of(SAVE_FIRST_LINE), + Set.of(DISCARD_STDOUT), + Set.of(DISCARD_STDERR), + Set.of(SAVE_ALL, DISCARD_STDOUT), + Set.of(SAVE_FIRST_LINE, DISCARD_STDOUT), + Set.of(SAVE_ALL, DISCARD_STDERR), + Set.of(SAVE_FIRST_LINE, DISCARD_STDERR), + Set.of(SAVE_ALL, DISCARD_STDOUT, DISCARD_STDERR), + Set.of(SAVE_FIRST_LINE, DISCARD_STDOUT, DISCARD_STDERR) + ).map(v -> { + return withDump.map(CommandOutputControlMutator.addToSet(v)).orElse(v); + }).map(v -> { + return redirectStderr.filter(_ -> { + return !v.containsAll(List.of(DISCARD_STDOUT, DISCARD_STDERR)); + }).map(CommandOutputControlMutator.addToSet(v)).orElse(v); + }).map(v -> { + return binaryOutput.map(CommandOutputControlMutator.addToSet(v)).orElse(v); + }).toList()); + } + } + } + return variants.stream().distinct().toList(); + } + + private static final class PrintStreamWrapper extends PrintStream { + PrintStreamWrapper(PrintStream out) { + super(out, true); + } + } + + private final Consumer setter; + private final Consumer unsetter; + private final Function getter; + + static final Set SAVE = Set.of(SAVE_ALL, SAVE_FIRST_LINE); + } + + public record CommandOutputControlSpec(Set outputControl) { + public CommandOutputControlSpec { + outputControl.forEach(Objects::requireNonNull); + if (outputControl.containsAll(OutputControl.SAVE)) { + throw new IllegalArgumentException(); + } + } + + @Override + public String toString() { + return outputControl.stream().map(CommandOutputControlMutator::name).sorted().collect(joining("+")); + } + + boolean contains(OutputControl v) { + return outputControl.contains(Objects.requireNonNull(v)); + } + + boolean dumpOutput() { + return contains(OutputControl.DUMP); + } + + boolean saveOutput() { + return !Collections.disjoint(outputControl, OutputControl.SAVE); + } + + boolean discardStdout() { + return contains(OutputControl.DISCARD_STDOUT); + } + + boolean discardStderr() { + return contains(OutputControl.DISCARD_STDERR); + } + + boolean redirectStderr() { + return contains(OutputControl.REDIRECT_STDERR); + } + + CommandOutputControl create() { + final CommandOutputControl coc = new CommandOutputControl(); + outputControl.forEach(control -> control.mutate(coc)); + return coc; + } + } + + public record OutputTestSpec(boolean toolProvider, CommandOutputControlSpec cocSpec, CommandSpec commandSpec) { + public OutputTestSpec { + Objects.requireNonNull(cocSpec); + Objects.requireNonNull(commandSpec); + } + + @Override + public String toString() { + final List tokens = new ArrayList<>(); + + if (toolProvider) { + tokens.add("tool-provider"); + } + + tokens.add("output=" + cocSpec.toString()); + tokens.add("command=" + commandSpec); + + return String.join(", ", tokens.toArray(String[]::new)); + } + + void test() { + final var command = commandSpec.command(); + + final Slot result = Slot.createEmpty(); + final var dumpCapture = DumpCapture.captureDump(toRunnable(() -> { + result.set(createExecutable(command).execute()); + })); + + assertEquals(0, result.get().getExitCode()); + + verifyDump(dumpCapture, command); + if (contains(OutputControl.BINARY_OUTPUT)) { + verifyByteResultContent(result.get(), command, StandardCharsets.UTF_8); + } else { + verifyResultContent(result.get(), command); + } + } + + private boolean contains(OutputControl v) { + return cocSpec.contains(v); + } + + private boolean dumpOutput() { + return cocSpec.dumpOutput(); + } + + private boolean saveOutput() { + return cocSpec.saveOutput(); + } + + private boolean discardStdout() { + return cocSpec.discardStdout(); + } + + private boolean discardStderr() { + return cocSpec.discardStderr(); + } + + private boolean redirectStderr() { + return cocSpec.redirectStderr(); + } + + private boolean replaceStdoutWithStderr() { + return redirectStderr() && discardStdout() && !discardStderr(); + } + + private boolean stdoutInherited() { + if (toolProvider || saveOutput() || replaceStdoutWithStderr()) { + return false; + } + return dumpOutput() && !discardStdout() && !contains(OutputControl.DUMP_STDOUT_IN_SYSTEM_OUT); + } + + private boolean stderrInherited() { + if (toolProvider || saveOutput() || redirectStderr()) { + return false; + } + return dumpOutput() && !discardStderr() && !contains(OutputControl.DUMP_STDERR_IN_SYSTEM_ERR); + } + + private void verifyDump(DumpCapture dumpCapture, Command command) { + if (!dumpOutput()) { + assertEquals(List.of(), dumpCapture.outLines()); + assertEquals(List.of(), dumpCapture.errLines()); + return; + } + + if (replaceStdoutWithStderr()) { + // STDERR replaces STDOUT + assertEquals(command.stderr(), dumpCapture.outLines()); + assertEquals(List.of(), dumpCapture.errLines()); + return; + } + + verifyDumpedStdout(dumpCapture, command); + verifyDumpedStderr(dumpCapture, command); + } + + private void verifyDumpedStdout(DumpCapture dumpCapture, Command command) { + if (stdoutInherited()) { + // A subprocess wrote its STDOUT into a file descriptor associated + // with the Java process's STDOUT, not into System.out. Can't capture it. + assertEquals(List.of(), dumpCapture.outLines()); + return; + } + + if (redirectStderr() && !discardStderr()) { + // Interleaved STDOUT and STDERR + if (!isInterleave(dumpCapture.outLines(), command.stdout(), command.stderr())) { + fail(String.format("Unexpected combined output=%s; stdout=%s; stderr=%s", + dumpCapture.outLines(), command.stdout(), command.stderr())); + } + } else if (discardStdout()) { + assertEquals(List.of(), dumpCapture.outLines()); + } else { + assertEquals(command.stdout(), dumpCapture.outLines()); + } + } + + private void verifyDumpedStderr(DumpCapture dumpCapture, Command command) { + if (stderrInherited()) { + // A subprocess wrote its STDERR into a file descriptor associated + // with the Java process's STDERR, not into System.err. Can't capture it. + assertEquals(List.of(), dumpCapture.errLines()); + return; + } + + if (redirectStderr() || discardStderr()) { + assertEquals(List.of(), dumpCapture.errLines()); + } else { + assertEquals(command.stderr(), dumpCapture.errLines()); + } + } + + private void verifyResultContent(CommandOutputControl.Result result, Command command) { + Objects.requireNonNull(result); + Objects.requireNonNull(command); + + assertTrue(result.findByteContent().isEmpty()); + assertTrue(result.findByteStdout().isEmpty()); + assertTrue(result.findByteStderr().isEmpty()); + + if (!saveOutput()) { + assertTrue(result.findContent().isEmpty()); + assertTrue(result.findStdout().isEmpty()); + assertTrue(result.findStderr().isEmpty()); + return; + } + + assertTrue(result.findContent().isPresent()); + + command = filterSavedStreams(command); + + var content = result.content(); + + if (contains(OutputControl.SAVE_FIRST_LINE)) { + assertTrue(content.size() <= 2, String.format("The number of saved lines must be less than or equal to two. Actual: %d", result.content().size())); + } + + if (!redirectStderr()) { + var stdout = result.stdout(); + var stderr = result.stderr(); + + assertEquals(command.stdout(), stdout); + assertEquals(command.stderr(), stderr); + assertEquals(Stream.of( + stdout, + stderr + ).flatMap(List::stream).toList(), content); + } else { + assertEquals(discardStderr(), result.findStdout().isPresent()); + assertTrue(result.findStderr().isEmpty()); + if (contains(OutputControl.SAVE_FIRST_LINE)) { + assertTrue(List.of(command.stdout(), command.stderr()).contains(result.content()), + String.format("Saved content %s is either %s or %s", + content, command.stdout(), command.stderr())); + } else if (contains(OutputControl.SAVE_ALL)) { + if (!isInterleave(content, command.stdout(), command.stderr())) { + fail(String.format("Unexpected combined saved content=%s; stdout=%s; stderr=%s", + content, command.stdout(), command.stderr())); + } + } else { + // Unreachable + throw ExceptionBox.reachedUnreachable(); + } + } + } + + private void verifyByteResultContent(CommandOutputControl.Result result, Command command, Charset charset) { + Objects.requireNonNull(result); + Objects.requireNonNull(command); + Objects.requireNonNull(charset); + + assertTrue(result.findContent().isEmpty()); + assertTrue(result.findStdout().isEmpty()); + assertTrue(result.findStderr().isEmpty()); + + if (!saveOutput()) { + assertTrue(result.findByteContent().isEmpty()); + assertTrue(result.findByteStdout().isEmpty()); + assertTrue(result.findByteStderr().isEmpty()); + return; + } + + assertTrue(result.findByteContent().isPresent()); + + command = filterSavedStreams(command); + + if (!redirectStderr()) { + assertEquals(command.stdout(), toStringList(result.byteStdout(), charset)); + assertEquals(command.stderr(), toStringList(result.byteStderr(), charset)); + assertEquals(Stream.of( + command.stdout(), + command.stderr() + ).flatMap(List::stream).toList(), toStringList(result.byteContent(), charset)); + } else { + assertEquals(discardStderr(), result.findByteStdout().isPresent()); + assertTrue(result.findByteStderr().isEmpty()); + + var combined = toStringList(result.byteContent(), charset); + if (!isInterleave(combined, command.stdout(), command.stderr())) { + fail(String.format("Unexpected combined saved content=%s; stdout=%s; stderr=%s", + combined, command.stdout(), command.stderr())); + } + } + } + + private List expectedSavedStream(List commandOutput) { + Objects.requireNonNull(commandOutput); + if (contains(OutputControl.SAVE_ALL) || (contains(OutputControl.SAVE_FIRST_LINE) && contains(OutputControl.BINARY_OUTPUT))) { + return commandOutput; + } else if (contains(OutputControl.SAVE_FIRST_LINE)) { + return commandOutput.stream().findFirst().map(List::of).orElseGet(List::of); + } else { + throw new IllegalStateException(); + } + } + + private Command filterSavedStreams(Command command) { + return new Command( + (discardStdout() ? List.of() : expectedSavedStream(command.stdout())), + (discardStderr() ? List.of() : expectedSavedStream(command.stderr()))); + } + + private record DumpCapture(byte[] out, byte[] err, Charset outCharset, Charset errCharset) { + DumpCapture { + Objects.requireNonNull(out); + Objects.requireNonNull(err); + Objects.requireNonNull(outCharset); + Objects.requireNonNull(errCharset); + } + + List outLines() { + return toStringList(out, outCharset); + } + + List errLines() { + return toStringList(err, errCharset); + } + + static DumpCapture captureDump(Runnable runnable) { + final var captureOut = new ByteArrayOutputStream(); + final var captureErr = new ByteArrayOutputStream(); + + final var out = System.out; + final var err = System.err; + try { + final var outCharset = System.out.charset(); + final var errCharset = System.err.charset(); + System.setOut(new PrintStream(captureOut, true, outCharset)); + System.setErr(new PrintStream(captureErr, true, errCharset)); + runnable.run(); + return new DumpCapture(captureOut.toByteArray(), captureErr.toByteArray(), outCharset, errCharset); + } finally { + try { + System.setOut(out); + } finally { + System.setErr(err); + } + } + } + } + + private CommandOutputControl.Executable createExecutable(Command command) { + final var coc = cocSpec.create(); + if (toolProvider) { + return coc.createExecutable(command.asToolProvider()); + } else { + return coc.createExecutable(new ProcessBuilder(command.asExecutable())); + } + } + } + + record CharsetTestSpec(boolean toolProvider, CommandOutputControlSpec cocSpec) { + + void test() throws IOException, InterruptedException { + if (cocSpec.outputControl().stream().noneMatch(DumpOutputSink.class::isInstance)) { + throw new IllegalArgumentException(); + } + + final var expectedString = "veni-vidi-vici"; + + var coc = cocSpec.create().dumpOutput(true); + + CommandOutputControl.Executable exec; + if (toolProvider) { + var tp = Command.createToolProvider(Stream.of(expectedString).mapMulti((str, sink) -> { + sink.accept(CommandAction.echoStdout(str)); + sink.accept(CommandAction.echoStderr(str)); + }).toList()); + exec = coc.createExecutable(tp); + } else { + var cmdline = Command.createShellCommandLine(Stream.of(expectedString).map(str -> { + return (str + System.lineSeparator()).getBytes(coc.charset()); + }).mapMulti((bytes, sink) -> { + sink.accept(CommandAction.writeStdout(bytes)); + sink.accept(CommandAction.writeStderr(bytes)); + }).toList()); + exec = coc.createExecutable(new ProcessBuilder(cmdline)); + } + + exec.execute(); + + for (var outputContolMutator : cocSpec.outputControl()) { + if (outputContolMutator instanceof DumpOutputSink sink) { + var actual = sink.lines(); + List expected; + if (cocSpec.redirectStderr()) { + switch (sink.streams()) { + case STDERR -> { + expected = List.of(); + } + default -> { + expected = List.of(expectedString, expectedString); + } + } + } else { + expected = List.of(expectedString); + } + assertEquals(expected, actual); + } + } + + } + + record DumpOutputSink(Charset charset, ByteArrayOutputStream buffer, OutputStreams streams) implements CommandOutputControlMutator { + DumpOutputSink { + Objects.requireNonNull(charset); + Objects.requireNonNull(buffer); + Objects.requireNonNull(streams); + } + + DumpOutputSink(Charset charset, OutputStreams streams) { + this(charset, new ByteArrayOutputStream(), streams); + } + + List lines() { + var str = buffer.toString(charset); + return new BufferedReader(new StringReader(str)).lines().toList(); + } + + @Override + public String name() { + return String.format("DUMP-%s-%s", streams, charset.name()); + } + + @Override + public void mutate(CommandOutputControl coc) { + var ps = new PrintStream(buffer, false, charset); + switch (streams) { + case STDOUT -> { + coc.dumpStdout(ps); + } + case STDERR -> { + coc.dumpStderr(ps); + } + case STDOUT_AND_STDERR -> { + // Easy to implement, but not used. + throw new IllegalArgumentException(); + } + default -> { + // Unreachable + throw ExceptionBox.reachedUnreachable(); + } + } + } + } + } + + private final static class InterruptibleToolProvider implements ToolProvider { + + InterruptibleToolProvider(ToolProvider impl) { + this.impl = impl; + } + + @Override + public String name() { + return impl.name(); + } + + @Override + public int run(PrintStream out, PrintStream err, String... args) { + return run(_ -> { + return impl.run(out, err, args); + }, args); + } + + @Override + public int run(PrintWriter out, PrintWriter err, String... args) { + return run(_ -> { + return impl.run(out, err, args); + }, args); + } + + boolean interrupted() { + return interrupted.join(); + } + + private int run(Function workload, String... args) { + boolean interruptedValue = false; + try { + return workload.apply(args); + } catch (ExceptionBox ex) { + if (ex.getCause() instanceof InterruptedException) { + interruptedValue = true; + return 1; + } else { + throw ex; + } + } finally { + interrupted.complete(interruptedValue); + } + } + + private final ToolProvider impl; + private final CompletableFuture interrupted = new CompletableFuture<>(); + } + + private static List toStringList(byte[] data, Charset charset) { + try (var bufReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data), charset))) { + return bufReader.lines().toList(); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + + private static List> withAndWithout (T value) { + return List.of(Optional.empty(), Optional.of(value)); + } + + private static final List BOOLEAN_VALUES = List.of(true, false); +} diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTestUtils.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTestUtils.java new file mode 100644 index 00000000000..dec0c5d6b0a --- /dev/null +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTestUtils.java @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.internal.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +public class CommandOutputControlTestUtils { + + @ParameterizedTest + @MethodSource + public void test_isInterleave(TestSpec test) { + test.run(); + } + + private static Stream test_isInterleave() { + var data = new ArrayList(); + + data.addAll(List.of( + interleaved("Toaday", "Today", "a"), + interleaved("Todanaay", "Today", "ana"), + interleaved("aaaababaaa", "aaaba", "aabaa"), + interleaved("xxxxxxxxxxxyxxyx", "xxxxxxxy", "xxxxxyxx"), + interleaved("xyxxxxyxxxxxxxxx", "yxxxxxxx", "xxxyxxxx"), + interleaved("xxxxxxxyxxxxyxxx", "xxxyxxxx", "xxxxxxyx"), + interleaved("cbdddcdaadacdbddbdcdddccdabbadba", "cdddaaddbcdcdbab", "bdcadcbddddcabda"), + interleaved("ddbdcacddddbddbdbddadcaaccdcabab", "dbccdddbbddacdaa", "ddaddbdddacaccbb"), + interleaved("adccbacbacaacddadddcdbbddbbddddd", "acbcaacddddbdbdd", "dcabcadadcbdbddd"), + interleaved("abdbdabdaacdcdbddddadbbccddcddac", "addbaccbdddbcdda", "bbadaddddabcdcdc"), + interleaved("cdaacbddaabdddbddbddbddadbacccdc", "dabdadddbddabccc", "cacdabdbddbddacd"), + notInterleaved("Toady", "Today", "a"), + notInterleaved("", "Today", "a") + )); + + data.addAll(generateTestData("abcdefghijklmnopqrstuvwxyz", 10)); + data.addAll(generateTestData("xxxxxxxy", 8)); + data.addAll(generateTestData("aaabbbcccddddddd", 50)); + + return data.stream().flatMap(test -> { + return Stream.of(test, test.flip()); + }); + } + + private static List generateTestData(String src, int iteration) { + + var srcCodePoints = new ArrayList(); + src.codePoints().mapToObj(Integer::valueOf).forEach(srcCodePoints::add); + + var data = new ArrayList(); + + Function, String> toString = codePoints -> { + var arr = codePoints.stream().mapToInt(Integer::intValue).toArray(); + return new String(arr, 0, arr.length); + }; + + for (int i = 0; i < 10; i++) { + Collections.shuffle(srcCodePoints); + var a = List.copyOf(srcCodePoints); + + Collections.shuffle(srcCodePoints); + var b = List.copyOf(srcCodePoints); + + var zip = new int[srcCodePoints.size() * 2]; + for (int codePointIdx = 0; codePointIdx != a.size(); codePointIdx++) { + var dstIdx = codePointIdx * 2; + zip[dstIdx] = a.get(codePointIdx); + zip[dstIdx + 1] = b.get(codePointIdx); + } + + data.add(interleaved(toString.apply(Arrays.stream(zip).boxed().toList()), toString.apply(a), toString.apply(b))); + } + + return data; + } + + public record TestSpec(String combined, String a, String b, boolean expected) { + + public TestSpec { + Objects.requireNonNull(combined); + Objects.requireNonNull(a); + Objects.requireNonNull(b); + } + + TestSpec flip() { + return new TestSpec(combined, b, a, expected); + } + + void run() { + assertEquals(expected, isInterleave( + combined.chars().mapToObj(Integer::valueOf).toList(), + a.chars().mapToObj(Integer::valueOf).toList(), + b.chars().mapToObj(Integer::valueOf).toList()), + String.format("combined: %s; a=%s; b=%s", combined, a, b)); + } + } + + private static TestSpec interleaved(String combined, String a, String b) { + return new TestSpec(combined, a, b, true); + } + + private static TestSpec notInterleaved(String combined, String a, String b) { + return new TestSpec(combined, a, b, false); + } + + // Solves the standard "Find if a string C is an interleave of strings A and B." + // problem but use containers instead of strings. + static boolean isInterleave(List combined, List a, List b) { + + if (a.size() + b.size() != combined.size()) { + return false; + } + + final var n = a.size(); + final var m = b.size(); + + var prev = new boolean[m + 1]; + final var cur = new boolean[m + 1]; + + prev[0] = true; + + for (int j = 1; j <= m; j++) { + prev[j] = prev[j - 1] && Objects.equals(b.get(j - 1), combined.get(j - 1)); + } + + for (int i = 1; i <= n; i++) { + cur[0] = prev[0] && Objects.equals(a.get(i - 1), combined.get(i - 1)); + + for (int j = 1; j <= m; j++) { + int k = i + j; + cur[j] = (prev[j] && Objects.equals(a.get(i - 1), combined.get(k - 1))) + || (cur[j - 1] && Objects.equals(b.get(j - 1), combined.get(k - 1))); + } + + prev = cur.clone(); + } + + return prev[m]; + } +} diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/EnquoterTest.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/EnquoterTest.java similarity index 57% rename from test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/EnquoterTest.java rename to test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/EnquoterTest.java index 95b0e54a0cd..8dc44f3f2fd 100644 --- a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/EnquoterTest.java +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/EnquoterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, 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,11 +21,13 @@ * questions. */ -package jdk.jpackage.internal; +package jdk.jpackage.internal.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -45,27 +47,41 @@ public class EnquoterTest { assertEquals(expected, actual); } - private static Stream testForShellLiterals() { + @ParameterizedTest + @MethodSource + public void testIdentity(String input) { + var actual = Enquoter.identity().applyTo(input); + assertEquals(input, actual); + } + + @ParameterizedTest + @MethodSource("testIdentity") + public void testNoEscaper(String input) { + var actual = Enquoter.identity().setEnquotePredicate(_ -> true).applyTo(input); + assertEquals('"' + input + '"', actual); + } + + private static Stream testForShellLiterals() { return Stream.of( - makeArguments("''", ""), - makeArguments("'foo'", "foo"), - makeArguments("' foo '", " foo "), - makeArguments("'foo bar'", "foo bar"), - makeArguments("'foo\\' bar'", "foo' bar") + Arguments.of("''", ""), + Arguments.of("'foo'", "foo"), + Arguments.of("' foo '", " foo "), + Arguments.of("'foo bar'", "foo bar"), + Arguments.of("'foo\\' bar'", "foo' bar") ); } - private static Stream testForPropertyValues() { + private static Stream testForPropertyValues() { return Stream.of( - makeArguments("", ""), - makeArguments("foo", "foo"), - makeArguments("\" foo \"", " foo "), - makeArguments("\"foo bar\"", "foo bar"), - makeArguments("\"foo' bar\"", "foo' bar") + Arguments.of("", ""), + Arguments.of("foo", "foo"), + Arguments.of("\" foo \"", " foo "), + Arguments.of("\"foo bar\"", "foo bar"), + Arguments.of("\"foo' bar\"", "foo' bar") ); } - static org.junit.jupiter.params.provider.Arguments makeArguments(Object ... args) { - return org.junit.jupiter.params.provider.Arguments.of(args); + private static Stream testIdentity() { + return Stream.of("", "foo", " foo ", "foo bar", "foo' bar"); } } diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/RetryExecutorTest.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/RetryExecutorTest.java new file mode 100644 index 00000000000..abb0363da80 --- /dev/null +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/RetryExecutorTest.java @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2026, 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. + */ +package jdk.jpackage.internal.util; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.time.Duration; +import java.util.Objects; +import jdk.jpackage.internal.util.RetryExecutor.Context; +import jdk.jpackage.internal.util.function.ExceptionBox; +import jdk.jpackage.internal.util.function.ThrowingFunction; +import jdk.jpackage.internal.util.function.ThrowingSupplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +public class RetryExecutorTest { + + @Test + public void test_defaults() { + + var executor = new AttemptCounter(context -> { + throw new AttemptFailedException(); + }); + + var defaultTimeout = Duration.ofSeconds(2); + var defaultAttemptCount = 5; + + var timeout = Slot.createEmpty(); + + assertThrowsExactly(AttemptFailedException.class, new RetryExecutor(Exception.class) + .setExecutable(executor) + .setSleepFunction(t -> { + assertEquals(defaultTimeout, t); + timeout.set(t); + return; + })::execute); + + assertEquals(defaultTimeout, timeout.get()); + assertEquals(defaultAttemptCount, executor.count()); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 2, 3, -4}) + public void test_N_attempts_fail(int maxAttemptsCount) throws AttemptFailedException { + + var retry = new RetryExecutor(AttemptFailedException.class) + .setMaxAttemptsCount(maxAttemptsCount) + .setAttemptTimeout(null) + .setExecutable(context -> { + if (context.attempt() == (maxAttemptsCount - 1)) { + assertTrue(context.isLastAttempt()); + } else { + assertFalse(context.isLastAttempt()); + } + throw new AttemptFailedException("Attempt: " + context.attempt()); + }); + + if (maxAttemptsCount <= 0) { + assertNull(retry.execute()); + } else { + var ex = assertThrowsExactly(AttemptFailedException.class, retry::execute); + assertEquals("Attempt: " + (maxAttemptsCount - 1), ex.getMessage()); + } + } + + @ParameterizedTest + @ValueSource(ints = {1, 2, 3}) + public void test_N_attempts_last_succeed(int maxAttemptsCount) throws AttemptFailedException { + test_N_attempts_M_succeed(maxAttemptsCount, maxAttemptsCount - 1, false); + } + + @ParameterizedTest + @ValueSource(ints = {2, 3}) + public void test_N_attempts_first_succeed(int maxAttemptsCount) throws AttemptFailedException { + test_N_attempts_M_succeed(maxAttemptsCount, 0, false); + } + + @Test + public void test_N_attempts_2nd_succeed() throws AttemptFailedException { + test_N_attempts_M_succeed(4, 1, false); + } + + @Test + public void test_N_attempts_2nd_succeed_unchecked() throws AttemptFailedException { + test_N_attempts_M_succeed(4, 1, true); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_null_executor(boolean dynamic) { + var retry = new RetryExecutor(AttemptFailedException.class) + .setAttemptTimeout(null).setMaxAttemptsCount(1000); + + if (dynamic) { + int maxAttemptsCount = 3; + var executor = new AttemptCounter(context -> { + assertTrue(context.attempt() <= (maxAttemptsCount - 1)); + if (context.attempt() == (maxAttemptsCount - 1)) { + context.executor().setExecutable((ThrowingSupplier)null); + } + throw new AttemptFailedException("foo"); + }); + + retry.setExecutable(executor); + + var ex = assertThrowsExactly(IllegalStateException.class, retry::execute); + assertEquals("No executable", ex.getMessage()); + assertEquals(3, executor.count()); + } else { + var ex = assertThrowsExactly(IllegalStateException.class, retry::execute); + assertEquals("No executable", ex.getMessage()); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_unexpected_exception(boolean executeUnchecked) { + var cause = new UnsupportedOperationException("foo"); + + var executor = new AttemptCounter(context -> { + assertEquals(0, context.attempt()); + throw cause; + }); + + var retry = new RetryExecutor(IOException.class).setExecutable(executor) + .setMaxAttemptsCount(10).setAttemptTimeout(null); + + UnsupportedOperationException ex; + if (executeUnchecked) { + ex = assertThrowsExactly(UnsupportedOperationException.class, retry::executeUnchecked); + } else { + ex = assertThrowsExactly(UnsupportedOperationException.class, retry::execute); + } + assertSame(cause, ex); + assertEquals(1, executor.count()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_dynamic(boolean abort) { + int maxAttemptsCount = 4; + + var secondExecutor = new AttemptCounter(context -> { + throw new AttemptFailedException("bar"); + }); + + var firstExecutor = new AttemptCounter(context -> { + assertTrue(context.attempt() <= (maxAttemptsCount - 1)); + if (context.attempt() == (maxAttemptsCount - 1)) { + if (abort) { + context.executor().setMaxAttemptsCount(maxAttemptsCount); + } else { + // Let it go two more times. + context.executor().setMaxAttemptsCount(maxAttemptsCount + 2); + } + context.executor().setExecutable(secondExecutor); + } + throw new AttemptFailedException("foo"); + }); + + var retry = new RetryExecutor(AttemptFailedException.class) + .setExecutable(firstExecutor) + .setMaxAttemptsCount(1000000) + .setAttemptTimeout(null); + + var ex = assertThrowsExactly(AttemptFailedException.class, retry::execute); + if (abort) { + assertEquals("foo", ex.getMessage()); + assertEquals(0, secondExecutor.count()); + } else { + assertEquals("bar", ex.getMessage()); + assertEquals(2, secondExecutor.count()); + } + assertEquals(maxAttemptsCount, firstExecutor.count()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_supplier_executor(boolean isNull) throws Exception { + var retry = new RetryExecutor(Exception.class).setMaxAttemptsCount(1); + if (isNull) { + retry.setExecutable((ThrowingSupplier)null); + var ex = assertThrowsExactly(IllegalStateException.class, retry::execute); + assertEquals("No executable", ex.getMessage()); + } else { + retry.setExecutable(() -> "Hello"); + assertEquals("Hello", retry.execute()); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_executeUnchecked_fail(boolean withExceptionMapper) throws AttemptFailedException { + var retry = new RetryExecutor(AttemptFailedException.class).setExecutable(() -> { + throw new AttemptFailedException("kaput!"); + }).setMaxAttemptsCount(1); + + Class expectedExceptionType; + if (withExceptionMapper) { + retry.setExceptionMapper((AttemptFailedException ex) -> { + assertEquals("kaput!", ex.getMessage()); + return new UncheckedAttemptFailedException(ex); + }); + expectedExceptionType = UncheckedAttemptFailedException.class; + } else { + expectedExceptionType = ExceptionBox.class; + } + + var ex = assertThrowsExactly(expectedExceptionType, retry::executeUnchecked); + assertEquals(AttemptFailedException.class, ex.getCause().getClass()); + assertEquals("kaput!", ex.getCause().getMessage()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void test_setSleepFunction(boolean withTimeout) { + + var timeout = Slot.createEmpty(); + + assertDoesNotThrow(new RetryExecutor(AttemptFailedException.class) + .setMaxAttemptsCount(2) + .mutate(retry -> { + if (withTimeout) { + retry.setAttemptTimeout(Duration.ofDays(100)); + } else { + retry.setAttemptTimeout(null); + } + }) + .setExecutable(context -> { + if (context.isLastAttempt()) { + return null; + } else { + throw new AttemptFailedException(); + } + }) + .setSleepFunction(timeout::set)::execute); + + assertEquals(withTimeout, timeout.find().isPresent()); + if (withTimeout) { + assertEquals(Duration.ofDays(100), timeout.get()); + } + } + + private static void test_N_attempts_M_succeed(int maxAttempts, int failedAttempts, boolean unchecked) throws AttemptFailedException { + + var countingExecutor = new AttemptCounter(context -> { + if (context.attempt() == failedAttempts) { + return "You made it!"; + } else { + throw new AttemptFailedException(); + } + }); + + var retry = new RetryExecutor(AttemptFailedException.class) + .setMaxAttemptsCount(maxAttempts) + .setAttemptTimeout(null) + .setExecutable(countingExecutor); + + assertEquals("You made it!", unchecked ? retry.execute() : retry.executeUnchecked()); + assertEquals(failedAttempts, countingExecutor.count() - 1); + } + + private static final class AttemptCounter implements ThrowingFunction>, T, E> { + + AttemptCounter(ThrowingFunction>, T, E> impl) { + this.impl = Objects.requireNonNull(impl); + } + + @Override + public T apply(Context> context) throws E { + counter++; + return impl.apply(context); + } + + int count() { + return counter; + } + + private int counter; + private final ThrowingFunction>, T, E> impl; + } + + private static final class AttemptFailedException extends Exception { + + AttemptFailedException(String msg) { + super(msg); + } + + AttemptFailedException() { + } + + private static final long serialVersionUID = 1L; + } + + private static final class UncheckedAttemptFailedException extends RuntimeException { + + UncheckedAttemptFailedException(AttemptFailedException ex) { + super(ex); + } + + private static final long serialVersionUID = 1L; + } +} diff --git a/test/jdk/tools/jpackage/macosx/HostArchPkgTest.java b/test/jdk/tools/jpackage/macosx/HostArchPkgTest.java index 7498043c14f..7aebff7cb00 100644 --- a/test/jdk/tools/jpackage/macosx/HostArchPkgTest.java +++ b/test/jdk/tools/jpackage/macosx/HostArchPkgTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, 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 @@ -64,8 +64,7 @@ public class HostArchPkgTest { dbf.setFeature("http://apache.org/xml/features/" + "nonvalidating/load-external-dtd", false); DocumentBuilder b = dbf.newDocumentBuilder(); - org.w3c.dom.Document doc - = b.parse(Files.newInputStream(distributionFile)); + org.w3c.dom.Document doc = b.parse(distributionFile.toFile()); XPath xPath = XPathFactory.newInstance().newXPath(); diff --git a/test/jdk/tools/jpackage/share/ErrorTest.java b/test/jdk/tools/jpackage/share/ErrorTest.java index 955c17e6043..ca1189a191e 100644 --- a/test/jdk/tools/jpackage/share/ErrorTest.java +++ b/test/jdk/tools/jpackage/share/ErrorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2026, 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 @@ -441,10 +441,7 @@ public final class ErrorTest { .error("error.no-module-in-path", "com.foo.bar"), // non-existing argument file testSpec().noAppDesc().notype().addArgs("@foo") - .error("ERR_CannotParseOptions", "foo"), - // invalid jlink option - testSpec().addArgs("--jlink-options", "--foo") - .error("error.jlink.failed", "Error: unknown option: --foo") + .error("ERR_CannotParseOptions", "foo") ).map(TestSpec.Builder::create).toList()); // --main-jar and --module-name @@ -707,12 +704,6 @@ public final class ErrorTest { final List errorMessages = new ArrayList<>(); errorMessages.add(makeError(JPackageStringBundle.MAIN.cannedFormattedString( "error.cert.not.found", "Developer ID Application: " + signingId, ""))); - errorMessages.addAll(Stream.of( - Map.>entry("error.explicit-sign-no-cert", JPackageCommand::makeError), - Map.>entry("error.explicit-sign-no-cert.advice", JPackageCommand::makeAdvice) - ).map(e -> { - return e.getValue().apply(JPackageStringBundle.MAIN.cannedFormattedString(e.getKey())); - }).toList()); final var cmd = JPackageCommand.helloAppImage() .ignoreDefaultVerbose(true) diff --git a/test/jdk/tools/jpackage/share/PostImageScriptTest.java b/test/jdk/tools/jpackage/share/PostImageScriptTest.java index 655658f036d..81cdfffbf46 100644 --- a/test/jdk/tools/jpackage/share/PostImageScriptTest.java +++ b/test/jdk/tools/jpackage/share/PostImageScriptTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -229,7 +229,7 @@ public class PostImageScriptTest { cmd.saveConsoleOutput(true); }).addBundleVerifier((cmd, result) -> { - final var imageDir = result.stdout().getOutput().stream().map(String::stripLeading).filter(str -> { + final var imageDir = result.stdout().stream().map(String::stripLeading).filter(str -> { return str.startsWith(imageDirOutputPrefix); }).map(str -> { return str.substring(imageDirOutputPrefix.length()); diff --git a/test/jdk/tools/jpackage/windows/WinLongVersionTest.java b/test/jdk/tools/jpackage/windows/WinLongVersionTest.java index 2ee76bcaa15..13650b2dfd3 100644 --- a/test/jdk/tools/jpackage/windows/WinLongVersionTest.java +++ b/test/jdk/tools/jpackage/windows/WinLongVersionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, 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 @@ -180,9 +180,8 @@ public class WinLongVersionTest { cmd.setFakeRuntime(); // Create package without Upgrade table - Document doc = XmlUtils.initDocumentBuilder().parse( - Files.newInputStream(TKit.SRC_ROOT.resolve( - "windows/classes/jdk/jpackage/internal/resources/main.wxs"))); + Document doc = XmlUtils.initDocumentBuilder().parse(TKit.SRC_ROOT.resolve( + "windows/classes/jdk/jpackage/internal/resources/main.wxs").toFile()); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.evaluate("/Wix/Product/Upgrade", doc, XPathConstants.NODESET); diff --git a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java index 2a415141229..a4fd5e3f68e 100644 --- a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java +++ b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2026, 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 @@ -221,10 +221,7 @@ public class TestRedirectLinks extends JavadocTester { out.println("Starting old server (" + oldServer.getClass().getSimpleName() + ") on " + oldURL); oldServer.start(); - SSLContext sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Could not create a SSLContext"); - } + SSLContext sslContext = SimpleSSLContext.findSSLContext(); newServer = HttpsServer.create(new InetSocketAddress(loopback, 0), 0); String newURL = URIBuilder.newBuilder() .scheme("https") diff --git a/test/langtools/jdk/jshell/ErrorTranslationTest.java b/test/langtools/jdk/jshell/ErrorTranslationTest.java index 1aa1b2c41dd..235f4443004 100644 --- a/test/langtools/jdk/jshell/ErrorTranslationTest.java +++ b/test/langtools/jdk/jshell/ErrorTranslationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, 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 @@ -149,7 +149,6 @@ public class ErrorTranslationTest extends ReplToolTesting { return sb.toString(); } - @Test public String getKind(Diagnostic.Kind kind) { switch (kind) { case WARNING: diff --git a/test/langtools/jdk/jshell/IdGeneratorTest.java b/test/langtools/jdk/jshell/IdGeneratorTest.java index 6c7f6177e03..521c87b0265 100644 --- a/test/langtools/jdk/jshell/IdGeneratorTest.java +++ b/test/langtools/jdk/jshell/IdGeneratorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, 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 @@ -44,7 +44,6 @@ import org.junit.jupiter.api.Test; public class IdGeneratorTest { - @Test public JShell.Builder getBuilder() { TestingInputStream inStream = new TestingInputStream(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); diff --git a/test/langtools/jdk/jshell/KullaCompletenessStressTest.java b/test/langtools/jdk/jshell/KullaCompletenessStressTest.java index 69830880dcb..16274fa924e 100644 --- a/test/langtools/jdk/jshell/KullaCompletenessStressTest.java +++ b/test/langtools/jdk/jshell/KullaCompletenessStressTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, 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,13 +32,11 @@ import java.io.File; import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class KullaCompletenessStressTest extends CompletenessStressTest { @Override - @Test public File[] getDirectoriesToTest() { String src = System.getProperty("test.src"); File file; diff --git a/test/lib/jdk/test/lib/cds/CDSAppTester.java b/test/lib/jdk/test/lib/cds/CDSAppTester.java index fd244c6acc6..18356dd8aa9 100644 --- a/test/lib/jdk/test/lib/cds/CDSAppTester.java +++ b/test/lib/jdk/test/lib/cds/CDSAppTester.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, 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 @@ -57,6 +57,8 @@ abstract public class CDSAppTester { private int numProductionRuns = 0; private String whiteBoxJar = null; private boolean inOneStepTraining = false; + private boolean generateBaseArchive = false; + private String[] baseArchiveOptions = new String[0]; /** * All files created in the CDS/AOT workflow will be name + extension. E.g. @@ -343,7 +345,7 @@ abstract public class CDSAppTester { // VM options used by this test, we need to create a temporary static archive to be used with -XX:ArchiveClassesAtExit. private String getBaseArchiveForDynamicArchive() throws Exception { WhiteBox wb = WhiteBox.getWhiteBox(); - if (wb.isSharingEnabled()) { + if (wb.isSharingEnabled() && !generateBaseArchive) { // This current JVM is able to use a default CDS archive included by the JDK, so // if we launch a JVM child process (with the same set of options as the current JVM), // that process is also able to use the same default CDS archive for creating @@ -356,6 +358,7 @@ abstract public class CDSAppTester { if (!f.exists()) { CDSOptions opts = new CDSOptions(); opts.setArchiveName(tempBaseArchiveFile); + opts.addSuffix(baseArchiveOptions); opts.addSuffix("-Djava.class.path="); OutputAnalyzer out = CDSTestUtils.createArchive(opts); CDSTestUtils.checkBaseDump(out); @@ -364,6 +367,16 @@ abstract public class CDSAppTester { } } + public CDSAppTester setGenerateBaseArchive(boolean b) { + this.generateBaseArchive = b; + return this; + } + + public CDSAppTester setBaseArchiveOptions(String... opts) { + this.baseArchiveOptions = opts; + return this; + } + private OutputAnalyzer dumpDynamicArchive() throws Exception { RunMode runMode = RunMode.DUMP_DYNAMIC; String[] cmdLine = new String[0]; diff --git a/test/lib/jdk/test/lib/cds/SimpleCDSAppTester.java b/test/lib/jdk/test/lib/cds/SimpleCDSAppTester.java index c869cfa366b..a8bba9c76e2 100644 --- a/test/lib/jdk/test/lib/cds/SimpleCDSAppTester.java +++ b/test/lib/jdk/test/lib/cds/SimpleCDSAppTester.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, 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 @@ -58,9 +58,11 @@ public class SimpleCDSAppTester { private String modulepath; private String[] appCommandLine; private String[] vmArgs = new String[] {}; + private Tester tester; private SimpleCDSAppTester(String name) { this.name = name; + this.tester = new Tester(name); } public static SimpleCDSAppTester of(String name) { @@ -101,6 +103,16 @@ public class SimpleCDSAppTester { return this; } + public SimpleCDSAppTester setGenerateBaseArchive(boolean b) { + tester.setGenerateBaseArchive(b); + return this; + } + + public SimpleCDSAppTester setBaseArchiveOptions(String... opts) { + tester.setBaseArchiveOptions(opts); + return this; + } + public SimpleCDSAppTester setTrainingChecker(BiConsumer checker) { this.trainingChecker = checker; return this; @@ -181,17 +193,22 @@ public class SimpleCDSAppTester { } public SimpleCDSAppTester runStaticWorkflow() throws Exception { - (new Tester(name)).runStaticWorkflow(); + tester.runStaticWorkflow(); + return this; + } + + public SimpleCDSAppTester runDynamicWorkflow() throws Exception { + tester.runDynamicWorkflow(); return this; } public SimpleCDSAppTester runAOTWorkflow() throws Exception { - (new Tester(name)).runAOTWorkflow(); + tester.runAOTWorkflow(); return this; } public SimpleCDSAppTester run(String args[]) throws Exception { - (new Tester(name)).run(args); + tester.run(args); return this; } } diff --git a/test/lib/jdk/test/lib/jvmti/jvmti_common.hpp b/test/lib/jdk/test/lib/jvmti/jvmti_common.hpp index 11600bd524b..3832d934b1e 100644 --- a/test/lib/jdk/test/lib/jvmti/jvmti_common.hpp +++ b/test/lib/jdk/test/lib/jvmti/jvmti_common.hpp @@ -123,6 +123,12 @@ char* julong_to_string(julong value, char *string) { return string; } +static void +fatal(const char* msg) { + LOG("FATAL ERROR: %s\n", msg); + abort(); +} + static void fatal(JNIEnv* jni, const char* msg) { jni->FatalError(msg); @@ -313,6 +319,17 @@ get_thread_name(jvmtiEnv *jvmti, JNIEnv* jni, jthread thread) { return tname; } +static char* +get_method_name(jvmtiEnv *jvmti, jmethodID method) { + char* mname = nullptr; + jvmtiError err; + + err = jvmti->GetMethodName(method, &mname, nullptr, nullptr); + check_jvmti_error(err, "get_method_name: error in JVMTI GetMethodName call"); + + return mname; +} + static char* get_method_name(jvmtiEnv *jvmti, JNIEnv* jni, jmethodID method) { char* mname = nullptr; diff --git a/test/lib/jdk/test/lib/net/SimpleSSLContext.java b/test/lib/jdk/test/lib/net/SimpleSSLContext.java index 3e0d362cc23..ae2b479c271 100644 --- a/test/lib/jdk/test/lib/net/SimpleSSLContext.java +++ b/test/lib/jdk/test/lib/net/SimpleSSLContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, 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,12 +23,16 @@ package jdk.test.lib.net; +import java.io.File; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; -import java.io.*; -import java.security.*; -import javax.net.ssl.*; +import java.security.KeyStore; +import java.util.Collections; +import java.util.Objects; +import java.util.StringTokenizer; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; /** * Utility for creating a simple usable {@link SSLContext} for testing purposes. @@ -39,17 +43,7 @@ public final class SimpleSSLContext { private static final String DEFAULT_KEY_STORE_FILE_REL_PATH = "jdk/test/lib/net/testkeys"; - private final SSLContext ssl; - - // Made `public` for backward compatibility - public SimpleSSLContext() throws IOException { - this.ssl = findSSLContext(DEFAULT_KEY_STORE_FILE_REL_PATH, DEFAULT_PROTOCOL); - } - - // Kept for backward compatibility - public SimpleSSLContext(String keyStoreFileRelPath) throws IOException { - this.ssl = findSSLContext(Objects.requireNonNull(keyStoreFileRelPath), DEFAULT_PROTOCOL); - } + private SimpleSSLContext() {} /** * {@return a new {@link SSLContext} instance by searching for a key store @@ -136,20 +130,4 @@ public final class SimpleSSLContext { } } - // Kept for backward compatibility - public static SSLContext getContext(String protocol) throws IOException { - try { - return protocol == null || protocol.isEmpty() - ? findSSLContext() - : findSSLContext(protocol); - } catch (RuntimeException re) { - throw new IOException(re); - } - } - - // Kept for backward compatibility - public SSLContext get() { - return ssl; - } - } diff --git a/test/micro/org/openjdk/bench/java/awt/image/PNGImageDecoder_8bit_uninterlaced.java b/test/micro/org/openjdk/bench/java/awt/image/PNGImageDecoder_8bit_uninterlaced.java new file mode 100644 index 00000000000..c91b3e24ba7 --- /dev/null +++ b/test/micro/org/openjdk/bench/java/awt/image/PNGImageDecoder_8bit_uninterlaced.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2026, 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. + */ +package org.openjdk.bench.java.awt.image; + +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +import javax.imageio.ImageIO; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.Toolkit; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.ImageConsumer; +import java.awt.image.IndexColorModel; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.Hashtable; +import java.util.Random; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 5, time = 20) +@Fork(3) +@State(Scope.Thread) +public class PNGImageDecoder_8bit_uninterlaced { + + byte[] pngImageData; + + @Setup + public void setup() throws Exception { + pngImageData = createImageData(2_500); + } + + @Benchmark + public void measurePNGImageDecoder(Blackhole bh) throws Exception { + Image img = Toolkit.getDefaultToolkit().createImage(pngImageData); + BufferedImage bi = createBufferedImage(img); + bi.flush(); + bh.consume(bi); + } + + /** + * Create a large sample image stored as an 8-bit PNG. + * + * @return the byte representation of the PNG image. + */ + private static byte[] createImageData(int squareSize) throws Exception { + BufferedImage bi = new BufferedImage(squareSize, squareSize, + BufferedImage.TYPE_BYTE_INDEXED); + Random r = new Random(0); + Graphics2D g = bi.createGraphics(); + for (int a = 0; a < 20000; a++) { + g.setColor(new Color(r.nextInt(0xffffff))); + int radius = 10 + r.nextInt(90); + g.fillOval(r.nextInt(bi.getWidth()), r.nextInt(bi.getHeight()), + radius, radius); + } + g.dispose(); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + ImageIO.write(bi, "png", out); + return out.toByteArray(); + } + } + + static BufferedImage createBufferedImage(Image img) + throws ExecutionException, InterruptedException { + CompletableFuture future = new CompletableFuture<>(); + img.getSource().startProduction(new ImageConsumer() { + private int imageWidth, imageHeight; + private BufferedImage bi; + + @Override + public void setDimensions(int width, int height) { + imageWidth = width; + imageHeight = height; + } + + @Override + public void setProperties(Hashtable props) { + // intentionally empty + } + + @Override + public void setColorModel(ColorModel model) { + // intentionally empty + } + + @Override + public void setHints(int hintflags) { + // intentionally empty + } + + @Override + public void setPixels(int x, int y, int w, int h, ColorModel model, + byte[] pixels, int off, int scansize) { + if (bi == null) { + bi = new BufferedImage(imageWidth, imageHeight, + BufferedImage.TYPE_BYTE_INDEXED, + (IndexColorModel) model); + } + if (h != 1) + throw new UnsupportedOperationException( + "this test expects sequential rows of pixels"); + if (off != 0) + throw new UnsupportedOperationException( + "this test expects the incoming pixels to start " + + "at index zero"); + + bi.getRaster().setDataElements(x, y, w, 1, pixels); + } + + @Override + public void setPixels(int x, int y, int w, int h, ColorModel model, + int[] pixels, int off, int scansize) { + throw new UnsupportedOperationException(); + } + + @Override + public void imageComplete(int status) { + future.complete(bi); + } + }); + return future.get(); + } +} \ No newline at end of file diff --git a/test/micro/org/openjdk/bench/java/io/FileWrite.java b/test/micro/org/openjdk/bench/java/io/FileWrite.java index 21b0c2f8f54..c5a5aee70d8 100644 --- a/test/micro/org/openjdk/bench/java/io/FileWrite.java +++ b/test/micro/org/openjdk/bench/java/io/FileWrite.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, 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 @@ package org.openjdk.bench.java.io; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; +import java.io.RandomAccessFile; import java.io.IOException; import java.util.concurrent.TimeUnit; @@ -81,4 +82,29 @@ public class FileWrite { } } + @State(Scope.Benchmark) + @Warmup(iterations = 3, time = 2) + @Measurement(iterations = 5, time = 5) + @BenchmarkMode(Mode.SampleTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Threads(1) + @Fork(value = 10) + public static class OpenFileForWritingBench { + final byte[] payload = "something".getBytes(); + final String path = System.getProperty("os.name", "unknown").toLowerCase().contains("win") ? "NUL" : "/dev/null"; + + @Benchmark + public void testFileOutputStream() throws IOException { + try (FileOutputStream f = new FileOutputStream(path)) { + f.write(payload); + } + } + + @Benchmark + public void testRandomAccessFile() throws IOException { + try (RandomAccessFile f = new RandomAccessFile(path, "rw")) { + f.write(payload); + } + } + } }