diff --git a/.github/actions/build-jtreg/action.yml b/.github/actions/build-jtreg/action.yml index 0ba9937fb45..a9c046e9dd9 100644 --- a/.github/actions/build-jtreg/action.yml +++ b/.github/actions/build-jtreg/action.yml @@ -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 diff --git a/.github/actions/get-bundles/action.yml b/.github/actions/get-bundles/action.yml index 270d15159a0..a356aa9fd8d 100644 --- a/.github/actions/get-bundles/action.yml +++ b/.github/actions/get-bundles/action.yml @@ -1,5 +1,5 @@ # -# Copyright (c) 2022, 2024, 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 diff --git a/.github/actions/get-gtest/action.yml b/.github/actions/get-gtest/action.yml index d38d33eabd8..7a329460a6e 100644 --- a/.github/actions/get-gtest/action.yml +++ b/.github/actions/get-gtest/action.yml @@ -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 diff --git a/.github/actions/get-jtreg/action.yml b/.github/actions/get-jtreg/action.yml index 4bb671d25d1..36c895fc59d 100644 --- a/.github/actions/get-jtreg/action.yml +++ b/.github/actions/get-jtreg/action.yml @@ -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 diff --git a/.github/actions/get-msys2/action.yml b/.github/actions/get-msys2/action.yml index d93b6e3763b..308230ebf2e 100644 --- a/.github/actions/get-msys2/action.yml +++ b/.github/actions/get-msys2/action.yml @@ -1,5 +1,5 @@ # -# Copyright (c) 2022, 2024, 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 diff --git a/.github/actions/upload-bundles/action.yml b/.github/actions/upload-bundles/action.yml index ca5366f3d6c..78fb0a94bfd 100644 --- a/.github/actions/upload-bundles/action.yml +++ b/.github/actions/upload-bundles/action.yml @@ -1,5 +1,5 @@ # -# Copyright (c) 2022, 2024, 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 diff --git a/.github/workflows/build-alpine-linux.yml b/.github/workflows/build-alpine-linux.yml index 0d366a4bdd0..c39962fa07f 100644 --- a/.github/workflows/build-alpine-linux.yml +++ b/.github/workflows/build-alpine-linux.yml @@ -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 @@ -59,7 +59,7 @@ on: jobs: build-linux: name: build - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 container: image: alpine:3.20 @@ -96,6 +96,8 @@ jobs: --with-boot-jdk=${{ steps.bootjdk.outputs.path }} --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 b3c63f488a0..a0642d469aa 100644 --- a/.github/workflows/build-cross-compile.yml +++ b/.github/workflows/build-cross-compile.yml @@ -1,5 +1,5 @@ # -# Copyright (c) 2022, 2024, 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 @@ -48,7 +48,7 @@ on: jobs: build-cross-compile: name: build - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false @@ -179,6 +179,8 @@ jobs: --openjdk-target=${{ matrix.gnu-arch }}-linux-gnu${{ matrix.gnu-abi}} --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 f398625cb2c..791b53a3f04 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -1,5 +1,5 @@ # -# Copyright (c) 2022, 2024, 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 @@ -75,7 +75,7 @@ on: jobs: build-linux: name: build - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false @@ -115,9 +115,21 @@ jobs: if [[ '${{ inputs.apt-architecture }}' != '' ]]; then sudo dpkg --add-architecture ${{ inputs.apt-architecture }} fi - sudo apt-get update - sudo apt-get install --only-upgrade apt - sudo apt-get install gcc-${{ inputs.gcc-major-version }}${{ inputs.gcc-package-suffix }} g++-${{ inputs.gcc-major-version }}${{ inputs.gcc-package-suffix }} libxrandr-dev${{ steps.arch.outputs.suffix }} libxtst-dev${{ steps.arch.outputs.suffix }} libcups2-dev${{ steps.arch.outputs.suffix }} libasound2-dev${{ steps.arch.outputs.suffix }} ${{ inputs.apt-extra-packages }} + sudo apt update + sudo apt install --only-upgrade apt + sudo apt install \ + gcc-${{ inputs.gcc-major-version }}${{ inputs.gcc-package-suffix }} \ + g++-${{ inputs.gcc-major-version }}${{ inputs.gcc-package-suffix }} \ + libasound2-dev${{ steps.arch.outputs.suffix }} \ + libcups2-dev${{ steps.arch.outputs.suffix }} \ + libfontconfig1-dev${{ steps.arch.outputs.suffix }} \ + libx11-dev${{ steps.arch.outputs.suffix }} \ + libxext-dev${{ steps.arch.outputs.suffix }} \ + libxrandr-dev${{ steps.arch.outputs.suffix }} \ + libxrender-dev${{ steps.arch.outputs.suffix }} \ + libxt-dev${{ steps.arch.outputs.suffix }} \ + libxtst-dev${{ steps.arch.outputs.suffix }} \ + ${{ inputs.apt-extra-packages }} sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-${{ inputs.gcc-major-version }} 100 --slave /usr/bin/g++ g++ /usr/bin/g++-${{ inputs.gcc-major-version }} - name: 'Configure' @@ -131,6 +143,8 @@ jobs: --with-gtest=${{ steps.gtest.outputs.path }} --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 0a12df668e5..484e616fad7 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -1,5 +1,5 @@ # -# Copyright (c) 2022, 2024, 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 @@ -110,6 +110,8 @@ jobs: --with-gtest=${{ steps.gtest.outputs.path }} --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-windows.yml b/.github/workflows/build-windows.yml index a3091b94cef..4dafc016a99 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -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 @@ -134,6 +134,7 @@ jobs: --with-gtest=${{ steps.gtest.outputs.path }} --with-msvc-toolset-version=${{ inputs.msvc-toolset-version }} --with-jmod-compress=zip-1 + --with-external-symbols-in-bundles=none ${{ inputs.extra-conf-options }} ${{ inputs.configure-arguments }} || ( echo "Dumping config.log:" && cat config.log && diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 4d1e8a8be3d..85ec75f343c 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -1,5 +1,5 @@ # -# Copyright (c) 2022, 2024, 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 @@ -57,7 +57,7 @@ jobs: prepare: name: 'Prepare the run' - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 env: # List of platforms to exclude by default EXCLUDED_PLATFORMS: 'alpine-linux-x64' @@ -405,7 +405,7 @@ jobs: with: platform: linux-x64 bootjdk-platform: linux-x64 - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 dry-run: ${{ needs.prepare.outputs.dry-run == 'true' }} debug-suffix: -debug @@ -419,7 +419,7 @@ jobs: with: platform: linux-x64 bootjdk-platform: linux-x64 - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 dry-run: ${{ needs.prepare.outputs.dry-run == 'true' }} static-suffix: "-static" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f2c8916a369..8f33454305e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,5 +1,5 @@ # -# Copyright (c) 2022, 2024, 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 diff --git a/.jcheck/conf b/.jcheck/conf index 60881e74d2a..25af49f8ef8 100644 --- a/.jcheck/conf +++ b/.jcheck/conf @@ -1,7 +1,7 @@ [general] project=jdk jbs=JDK -version=26 +version=27 [checks] error=author,committer,reviewers,merge,issues,executable,symlink,message,hg-tag,whitespace,problemlists,copyright diff --git a/README.md b/README.md index b3f30676b3c..e939f6a9ca4 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Welcome to the JDK! For build instructions please see the -[online documentation](https://openjdk.org/groups/build/doc/building.html), +[online documentation](https://git.openjdk.org/jdk/blob/master/doc/building.md), or either of these files: - [doc/building.html](doc/building.html) (html version) diff --git a/bin/generate-symbol-data.sh b/bin/generate-symbol-data.sh index 283757a6918..14d8763ad81 100644 --- a/bin/generate-symbol-data.sh +++ b/bin/generate-symbol-data.sh @@ -38,7 +38,7 @@ # directory. # - open a terminal program and run these commands: # cd "${JDK_CHECKOUT}"/src/jdk.compiler/share/data/symbols -# bash ../../../../../make/scripts/generate-symbol-data.sh "${JDK_N_INSTALL}" +# bash ../../../../../bin/generate-symbol-data.sh "${JDK_N_INSTALL}" # - this command will generate or update data for "--release N" into the ${JDK_CHECKOUT}/src/jdk.compiler/share/data/symbols # directory, updating all registration necessary. If the goal was to update the data, and there are no # new or changed files in the ${JDK_CHECKOUT}/src/jdk.compiler/share/data/symbols directory after running this script, diff --git a/doc/building.html b/doc/building.html index 19313ebf43a..8e5a7625371 100644 --- a/doc/building.html +++ b/doc/building.html @@ -541,6 +541,11 @@ href="#apple-xcode">Apple Xcode on some strategies to deal with this.

It is recommended that you use at least macOS 14 and Xcode 15.4, but earlier versions may also work.

+

Starting with Xcode 26, introduced in macOS 26, the Metal toolchain +no longer comes bundled with Xcode, so it needs to be installed +separately. This can either be done via the Xcode's Settings/Components +UI, or in the command line calling +xcodebuild -downloadComponent metalToolchain.

The standard macOS environment contains the basic tooling needed to build, but for external libraries a package manager is recommended. The JDK uses homebrew in the examples, but diff --git a/doc/building.md b/doc/building.md index 1fbd395a9d1..b626027f101 100644 --- a/doc/building.md +++ b/doc/building.md @@ -352,6 +352,11 @@ on some strategies to deal with this. It is recommended that you use at least macOS 14 and Xcode 15.4, but earlier versions may also work. +Starting with Xcode 26, introduced in macOS 26, the Metal toolchain no longer +comes bundled with Xcode, so it needs to be installed separately. This can +either be done via the Xcode's Settings/Components UI, or in the command line +calling `xcodebuild -downloadComponent metalToolchain`. + The standard macOS environment contains the basic tooling needed to build, but for external libraries a package manager is recommended. The JDK uses [homebrew](https://brew.sh/) in the examples, but feel free to use whatever diff --git a/doc/hotspot-style.html b/doc/hotspot-style.html index a2ffb57e5a3..362245cd00a 100644 --- a/doc/hotspot-style.html +++ b/doc/hotspot-style.html @@ -1037,8 +1037,8 @@ running destructors at exit can lead to problems.

Some of the approaches used in HotSpot to avoid dynamic initialization include:

diff --git a/doc/starting-next-release.md b/doc/starting-next-release.md index 10bc364a3e4..5bb9c5839a4 100644 --- a/doc/starting-next-release.md +++ b/doc/starting-next-release.md @@ -65,4 +65,4 @@ to be updated for a particular release. * `test/langtools/tools/javac/lib/JavacTestingAbstractProcessor.java` update annotation processor extended by `javac` tests to cover the new source version * `test/langtools/tools/javac/preview/classReaderTest/Client.nopreview.out` and `test/langtools/tools/javac/preview/classReaderTest/Client.preview.out`: update expected messages for preview errors and warnings - +* `test/langtools/tools/javac/versions/Versions.java`: add new source version to the set of valid sources and add new enum constant for the new class file version. diff --git a/make/Bundles.gmk b/make/Bundles.gmk index cf3b77e4e52..0b324e7e3f3 100644 --- a/make/Bundles.gmk +++ b/make/Bundles.gmk @@ -125,13 +125,6 @@ define SetupBundleFileBody && $(TAR) cf - -$(TAR_INCLUDE_PARAM) $$($1_$$d_LIST_FILE) \ $(TAR_IGNORE_EXIT_VALUE) ) \ | ( $(CD) $(SUPPORT_OUTPUTDIR)/bundles/$1/$$($1_SUBDIR) && $(TAR) xf - )$$(NEWLINE) ) - # Rename stripped pdb files - ifeq ($(call isTargetOs, windows)+$(SHIP_DEBUG_SYMBOLS), true+public) - for f in `$(FIND) $(SUPPORT_OUTPUTDIR)/bundles/$1/$$($1_SUBDIR) -name "*.stripped.pdb"`; do \ - $(ECHO) Renaming $$$${f} to $$$${f%stripped.pdb}pdb $(LOG_INFO); \ - $(MV) $$$${f} $$$${f%stripped.pdb}pdb; \ - done - endif # Unzip any zipped debuginfo files ifeq ($$($1_UNZIP_DEBUGINFO), true) for f in `$(FIND) $(SUPPORT_OUTPUTDIR)/bundles/$1/$$($1_SUBDIR) -name "*.diz"`; do \ @@ -192,96 +185,30 @@ endif ifneq ($(filter product-bundles% legacy-bundles, $(MAKECMDGOALS)), ) - SYMBOLS_EXCLUDE_PATTERN := %.debuginfo %.diz %.map - - # There may be files with spaces in the names, so use ShellFindFiles - # explicitly. + # There may be files with spaces in the names, so use ShellFindFiles explicitly. ALL_JDK_FILES := $(call ShellFindFiles, $(JDK_IMAGE_DIR)) - ifneq ($(JDK_IMAGE_DIR), $(JDK_SYMBOLS_IMAGE_DIR)) - ALL_JDK_SYMBOLS_FILES := $(call ShellFindFiles, $(JDK_SYMBOLS_IMAGE_DIR)) - else - ALL_JDK_SYMBOLS_FILES := $(ALL_JDK_FILES) - endif ifneq ($(JDK_IMAGE_DIR), $(JDK_DEMOS_IMAGE_DIR)) ALL_JDK_DEMOS_FILES := $(call ShellFindFiles, $(JDK_DEMOS_IMAGE_DIR)) else ALL_JDK_DEMOS_FILES := $(ALL_JDK_FILES) endif - # Create special filter rules when dealing with unzipped .dSYM directories on - # macosx - ifeq ($(call isTargetOs, macosx), true) - ifeq ($(ZIP_EXTERNAL_DEBUG_SYMBOLS), false) - JDK_SYMBOLS_EXCLUDE_PATTERN := $(addprefix %, \ - $(call containing, .dSYM/, $(patsubst $(JDK_IMAGE_DIR)/%, %, \ - $(ALL_JDK_SYMBOLS_FILES)))) - endif - endif - - # Create special filter rules when dealing with debug symbols on windows - ifeq ($(call isTargetOs, windows), true) - ifeq ($(SHIP_DEBUG_SYMBOLS), ) - JDK_SYMBOLS_EXCLUDE_PATTERN := %.pdb - else - ifeq ($(SHIP_DEBUG_SYMBOLS), public) - JDK_SYMBOLS_EXCLUDE_PATTERN := \ - $(filter-out \ - %.stripped.pdb, \ - $(filter %.pdb, $(ALL_JDK_FILES)) \ - ) - endif - endif - endif - JDK_BUNDLE_FILES := \ $(filter-out \ - $(JDK_SYMBOLS_EXCLUDE_PATTERN) \ $(JDK_EXTRA_EXCLUDES) \ - $(SYMBOLS_EXCLUDE_PATTERN) \ $(JDK_IMAGE_HOMEDIR)/demo/% \ , \ $(ALL_JDK_FILES) \ ) - JDK_SYMBOLS_BUNDLE_FILES := \ - $(filter-out \ - %.stripped.pdb, \ - $(call FindFiles, $(SYMBOLS_IMAGE_DIR)) \ - ) + JDK_SYMBOLS_BUNDLE_FILES := $(call FindFiles, $(SYMBOLS_IMAGE_DIR)) TEST_DEMOS_BUNDLE_FILES := $(filter $(JDK_DEMOS_IMAGE_HOMEDIR)/demo/%, \ $(ALL_JDK_DEMOS_FILES)) ALL_JRE_FILES := $(call ShellFindFiles, $(JRE_IMAGE_DIR)) - # Create special filter rules when dealing with unzipped .dSYM directories on - # macosx - ifeq ($(OPENJDK_TARGET_OS), macosx) - ifeq ($(ZIP_EXTERNAL_DEBUG_SYMBOLS), false) - JRE_SYMBOLS_EXCLUDE_PATTERN := $(addprefix %, \ - $(call containing, .dSYM/, $(patsubst $(JRE_IMAGE_DIR)/%, %, $(ALL_JRE_FILES)))) - endif - endif - - # Create special filter rules when dealing with debug symbols on windows - ifeq ($(call isTargetOs, windows), true) - ifeq ($(SHIP_DEBUG_SYMBOLS), ) - JRE_SYMBOLS_EXCLUDE_PATTERN := %.pdb - else - ifeq ($(SHIP_DEBUG_SYMBOLS), public) - JRE_SYMBOLS_EXCLUDE_PATTERN := \ - $(filter-out \ - %.stripped.pdb, \ - $(filter %.pdb, $(ALL_JRE_FILES)) \ - ) - endif - endif - endif - - JRE_BUNDLE_FILES := $(filter-out \ - $(JRE_SYMBOLS_EXCLUDE_PATTERN) \ - $(SYMBOLS_EXCLUDE_PATTERN), \ - $(ALL_JRE_FILES)) + JRE_BUNDLE_FILES := $(ALL_JRE_FILES) ifeq ($(MACOSX_CODESIGN_MODE), hardened) # Macosx release build and code signing available. diff --git a/make/CreateJmods.gmk b/make/CreateJmods.gmk index 3280b24924a..32f107b6bb6 100644 --- a/make/CreateJmods.gmk +++ b/make/CreateJmods.gmk @@ -218,10 +218,14 @@ ifeq ($(call isTargetOs, windows), true) ifeq ($(SHIP_DEBUG_SYMBOLS), ) JMOD_FLAGS += --exclude '**{_the.*,_*.marker*,*.diz,*.pdb,*.map}' else - JMOD_FLAGS += --exclude '**{_the.*,_*.marker*,*.diz,*.map}' + JMOD_FLAGS += --exclude '**{_the.*,_*.marker*,*.map}' endif else - JMOD_FLAGS += --exclude '**{_the.*,_*.marker*,*.diz,*.debuginfo,*.dSYM/**,*.dSYM}' + ifeq ($(SHIP_DEBUG_SYMBOLS), ) + JMOD_FLAGS += --exclude '**{_the.*,_*.marker*,*.diz,*.debuginfo,*.dSYM/**,*.dSYM}' + else + JMOD_FLAGS += --exclude '**{_the.*,_*.marker*}' + endif endif # Unless we are creating a very large module, use the small tool JVM options diff --git a/make/Docs.gmk b/make/Docs.gmk index b105e1d8683..a8d40e078e2 100644 --- a/make/Docs.gmk +++ b/make/Docs.gmk @@ -93,16 +93,19 @@ JAVADOC_DISABLED_DOCLINT_WARNINGS := missing JAVADOC_DISABLED_DOCLINT_PACKAGES := org.w3c.* javax.smartcardio # The initial set of options for javadoc +# -XDaccessInternalAPI is a temporary workaround, see 8373909 JAVADOC_OPTIONS := -use -keywords -notimestamp \ -serialwarn -encoding utf-8 -docencoding utf-8 -breakiterator \ -splitIndex --system none -javafx --expand-requires transitive \ - --override-methods=summary + --override-methods=summary \ + -XDaccessInternalAPI # The reference options must stay stable to allow for comparisons across the # development cycle. REFERENCE_OPTIONS := -XDignore.symbol.file=true -use -keywords -notimestamp \ -serialwarn -encoding utf-8 -breakiterator -splitIndex --system none \ - -html5 -javafx --expand-requires transitive + -html5 -javafx --expand-requires transitive \ + -XDaccessInternalAPI # Should we add DRAFT stamps to the generated javadoc? ifeq ($(VERSION_IS_GA), true) diff --git a/make/Images.gmk b/make/Images.gmk index c5877e44c22..89c0a834477 100644 --- a/make/Images.gmk +++ b/make/Images.gmk @@ -282,29 +282,33 @@ else endif CMDS_TARGET_SUBDIR := bin -# Param 1 - either JDK or JRE +# Copy debug info files into symbols bundle. +# In case of Windows and --with-external-symbols-in-bundles=public, take care to remove *.stripped.pdb files SetupCopyDebuginfo = \ $(foreach m, $(ALL_$1_MODULES), \ + $(eval dbgfiles := $(call FindDebuginfoFiles, $(SUPPORT_OUTPUTDIR)/modules_libs/$m)) \ + $(eval dbgfiles := $(if $(filter true+public,$(call isTargetOs,windows)+$(SHIP_DEBUG_SYMBOLS)), \ + $(filter-out %.stripped.pdb,$(dbgfiles)),$(dbgfiles)) \ + ) \ $(eval $(call SetupCopyFiles, COPY_$1_LIBS_DEBUGINFO_$m, \ SRC := $(SUPPORT_OUTPUTDIR)/modules_libs/$m, \ DEST := $($1_IMAGE_DIR)/$(LIBS_TARGET_SUBDIR), \ - FILES := $(call FindDebuginfoFiles, \ - $(SUPPORT_OUTPUTDIR)/modules_libs/$m), \ + FILES := $(dbgfiles), \ )) \ $(eval $1_TARGETS += $$(COPY_$1_LIBS_DEBUGINFO_$m)) \ + $(eval dbgfiles := $(call FindDebuginfoFiles, $(SUPPORT_OUTPUTDIR)/modules_cmds/$m)) \ + $(eval dbgfiles := $(if $(filter true+public,$(call isTargetOs,windows)+$(SHIP_DEBUG_SYMBOLS)), \ + $(filter-out %.stripped.pdb,$(dbgfiles)),$(dbgfiles)) \ + ) \ $(eval $(call SetupCopyFiles, COPY_$1_CMDS_DEBUGINFO_$m, \ SRC := $(SUPPORT_OUTPUTDIR)/modules_cmds/$m, \ DEST := $($1_IMAGE_DIR)/$(CMDS_TARGET_SUBDIR), \ - FILES := $(call FindDebuginfoFiles, \ - $(SUPPORT_OUTPUTDIR)/modules_cmds/$m), \ + FILES := $(dbgfiles), \ )) \ $(eval $1_TARGETS += $$(COPY_$1_CMDS_DEBUGINFO_$m)) \ ) -# No space before argument to avoid having to put $(strip ) everywhere in -# implementation above. -$(call SetupCopyDebuginfo,JDK) -$(call SetupCopyDebuginfo,JRE) +# No space before argument to avoid having to put $(strip ) everywhere in implementation above. $(call SetupCopyDebuginfo,SYMBOLS) ################################################################################ diff --git a/make/RunTests.gmk b/make/RunTests.gmk index 1f50b97531b..946b1332edc 100644 --- a/make/RunTests.gmk +++ b/make/RunTests.gmk @@ -873,7 +873,7 @@ define SetupRunJtregTestBody $1_JTREG_BASIC_OPTIONS += -testThreadFactoryPath:$$(JTREG_TEST_THREAD_FACTORY_JAR) $1_JTREG_BASIC_OPTIONS += -testThreadFactory:$$(JTREG_TEST_THREAD_FACTORY) $1_JTREG_BASIC_OPTIONS += $$(addprefix $$(JTREG_PROBLEM_LIST_PREFIX), $$(wildcard \ - $$(addprefix $$($1_TEST_ROOT)/, ProblemList-$$(JTREG_TEST_THREAD_FACTORY).txt) \ + $$(addprefix $$($1_TEST_ROOT)/, ProblemList-$$(JTREG_TEST_THREAD_FACTORY).txt) \ )) endif @@ -881,8 +881,8 @@ define SetupRunJtregTestBody AGENT := $$(LIBRARY_PREFIX)JvmtiStressAgent$$(SHARED_LIBRARY_SUFFIX)=$$(JTREG_JVMTI_STRESS_AGENT) $1_JTREG_BASIC_OPTIONS += -javaoption:'-agentpath:$(TEST_IMAGE_DIR)/hotspot/jtreg/native/$$(AGENT)' $1_JTREG_BASIC_OPTIONS += $$(addprefix $$(JTREG_PROBLEM_LIST_PREFIX), $$(wildcard \ - $$(addprefix $$($1_TEST_ROOT)/, ProblemList-jvmti-stress-agent.txt) \ - )) + $$(addprefix $$($1_TEST_ROOT)/, ProblemList-jvmti-stress-agent.txt) \ + )) endif @@ -1092,7 +1092,7 @@ define SetupRunJtregTestBody $$(call MakeDir, $$($1_TEST_RESULTS_DIR) $$($1_TEST_SUPPORT_DIR) \ $$($1_TEST_TMP_DIR)) $$(call ExecuteWithLog, $$($1_TEST_SUPPORT_DIR)/jtreg, \ - $$(COV_ENVIRONMENT) $$($1_COMMAND_LINE) \ + $$(COV_ENVIRONMENT) $$($1_COMMAND_LINE) \ ) $1_RESULT_FILE := $$($1_TEST_RESULTS_DIR)/text/stats.txt @@ -1102,11 +1102,11 @@ define SetupRunJtregTestBody $$(call LogWarn, Test report is stored in $$(strip \ $$(subst $$(TOPDIR)/, , $$($1_TEST_RESULTS_DIR)))) - # Read jtreg documentation to learn on the test stats categories: - # https://github.com/openjdk/jtreg/blob/master/src/share/doc/javatest/regtest/faq.md#what-do-all-those-numbers-in-the-test-results-line-mean - # In jtreg, "skipped:" category accounts for tests that threw jtreg.SkippedException at runtime. - # At the same time these tests contribute to "passed:" tests. - # In here we don't want that and so we substract number of "skipped:" from "passed:". + # Read jtreg documentation to learn on the test stats categories: + # https://github.com/openjdk/jtreg/blob/master/src/share/doc/javatest/regtest/faq.md#what-do-all-those-numbers-in-the-test-results-line-mean + # In jtreg, "skipped:" category accounts for tests that threw jtreg.SkippedException at runtime. + # At the same time these tests contribute to "passed:" tests. + # In here we don't want that and so we substract number of "skipped:" from "passed:". $$(if $$(wildcard $$($1_RESULT_FILE)), \ $$(eval $1_PASSED_AND_RUNTIME_SKIPPED := $$(shell $$(AWK) '{ gsub(/[,;]/, ""); \ diff --git a/make/RunTestsPrebuiltSpec.gmk b/make/RunTestsPrebuiltSpec.gmk index e9fd901c9e1..5fe559eafad 100644 --- a/make/RunTestsPrebuiltSpec.gmk +++ b/make/RunTestsPrebuiltSpec.gmk @@ -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 diff --git a/make/ToolsJdk.gmk b/make/ToolsJdk.gmk index 629cadbf83a..b04d7820c91 100644 --- a/make/ToolsJdk.gmk +++ b/make/ToolsJdk.gmk @@ -79,7 +79,7 @@ TOOL_GENERATEEXTRAPROPERTIES = $(JAVA_SMALL) -cp $(BUILDTOOLS_OUTPUTDIR)/jdk_too build.tools.generateextraproperties.GenerateExtraProperties TOOL_GENERATECASEFOLDING = $(JAVA_SMALL) -cp $(BUILDTOOLS_OUTPUTDIR)/jdk_tools_classes \ - build.tools.generatecharacter.CaseFolding + build.tools.generatecharacter.GenerateCaseFolding TOOL_MAKEZIPREPRODUCIBLE = $(JAVA_SMALL) -cp $(BUILDTOOLS_OUTPUTDIR)/jdk_tools_classes \ build.tools.makezipreproducible.MakeZipReproducible diff --git a/make/autoconf/basic.m4 b/make/autoconf/basic.m4 index 316bfc5037d..bb6908d9194 100644 --- a/make/autoconf/basic.m4 +++ b/make/autoconf/basic.m4 @@ -353,7 +353,12 @@ AC_DEFUN_ONCE([BASIC_SETUP_DEVKIT], [set up toolchain on Mac OS using a path to an Xcode installation])]) UTIL_DEPRECATED_ARG_WITH(sys-root) - UTIL_DEPRECATED_ARG_WITH(tools-dir) + + AC_ARG_WITH([tools-dir], [AS_HELP_STRING([--with-tools-dir], + [Point to a nonstandard Visual Studio installation location on Windows by + specifying any existing directory 2 or 3 levels below the installation + root.])] + ) if test "x$with_xcode_path" != x; then if test "x$OPENJDK_BUILD_OS" = "xmacosx"; then diff --git a/make/autoconf/bootcycle-spec.gmk.template b/make/autoconf/bootcycle-spec.gmk.template index d17a95e190a..eb564f40e3f 100644 --- a/make/autoconf/bootcycle-spec.gmk.template +++ b/make/autoconf/bootcycle-spec.gmk.template @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 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 diff --git a/make/autoconf/buildjdk-spec.gmk.template b/make/autoconf/buildjdk-spec.gmk.template index 924389b94e8..bb020842d59 100644 --- a/make/autoconf/buildjdk-spec.gmk.template +++ b/make/autoconf/buildjdk-spec.gmk.template @@ -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 diff --git a/make/autoconf/compare.sh.template b/make/autoconf/compare.sh.template index 84421035ab9..b17ddc16827 100644 --- a/make/autoconf/compare.sh.template +++ b/make/autoconf/compare.sh.template @@ -1,6 +1,6 @@ #!/bin/bash # -# 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 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/autoconf/flags-ldflags.m4 b/make/autoconf/flags-ldflags.m4 index 572790b567b..466ff1beaf4 100644 --- a/make/autoconf/flags-ldflags.m4 +++ b/make/autoconf/flags-ldflags.m4 @@ -34,7 +34,7 @@ AC_DEFUN([FLAGS_SETUP_LDFLAGS], FLAGS_SETUP_LDFLAGS_CPU_DEP([TARGET]) # Setup the build toolchain - FLAGS_SETUP_LDFLAGS_CPU_DEP([BUILD], [OPENJDK_BUILD_]) + FLAGS_SETUP_LDFLAGS_CPU_DEP([BUILD], [OPENJDK_BUILD_], [BUILD_]) AC_SUBST(ADLC_LDFLAGS) ]) @@ -52,11 +52,6 @@ AC_DEFUN([FLAGS_SETUP_LDFLAGS_HELPER], # add --no-as-needed to disable default --as-needed link flag on some GCC toolchains # add --icf=all (Identical Code Folding — merges identical functions) BASIC_LDFLAGS="-Wl,-z,defs -Wl,-z,relro -Wl,-z,now -Wl,--no-as-needed -Wl,--exclude-libs,ALL" - if test "x$LINKER_TYPE" = "xgold"; then - if test x$DEBUG_LEVEL = xrelease; then - BASIC_LDFLAGS="$BASIC_LDFLAGS -Wl,--icf=all" - fi - fi # Linux : remove unused code+data in link step if test "x$ENABLE_LINKTIME_GC" = xtrue; then @@ -68,7 +63,7 @@ AC_DEFUN([FLAGS_SETUP_LDFLAGS_HELPER], fi BASIC_LDFLAGS_JVM_ONLY="" - LDFLAGS_LTO="-flto=auto -fuse-linker-plugin -fno-strict-aliasing" + LDFLAGS_LTO="-flto=auto -fuse-linker-plugin -fno-strict-aliasing $DEBUG_PREFIX_CFLAGS" LDFLAGS_CXX_PARTIAL_LINKING="$MACHINE_FLAG -r" @@ -76,7 +71,7 @@ AC_DEFUN([FLAGS_SETUP_LDFLAGS_HELPER], BASIC_LDFLAGS_JVM_ONLY="-mno-omit-leaf-frame-pointer -mstack-alignment=16 \ -fPIC" - LDFLAGS_LTO="-flto=auto -fuse-linker-plugin -fno-strict-aliasing" + LDFLAGS_LTO="-flto=auto -fuse-linker-plugin -fno-strict-aliasing $DEBUG_PREFIX_CFLAGS" LDFLAGS_CXX_PARTIAL_LINKING="$MACHINE_FLAG -r" if test "x$OPENJDK_TARGET_OS" = xlinux; then @@ -108,6 +103,9 @@ AC_DEFUN([FLAGS_SETUP_LDFLAGS_HELPER], # Setup OS-dependent LDFLAGS if test "x$OPENJDK_TARGET_OS" = xmacosx && test "x$TOOLCHAIN_TYPE" = xclang; then + if test x$DEBUG_LEVEL = xrelease; then + BASIC_LDFLAGS_JDK_ONLY="$BASIC_LDFLAGS_JDK_ONLY -Wl,-dead_strip" + fi # FIXME: We should really generalize SetSharedLibraryOrigin instead. OS_LDFLAGS_JVM_ONLY="-Wl,-rpath,@loader_path/. -Wl,-rpath,@loader_path/.." OS_LDFLAGS="-mmacosx-version-min=$MACOSX_VERSION_MIN -Wl,-reproducible" @@ -166,7 +164,8 @@ AC_DEFUN([FLAGS_SETUP_LDFLAGS_HELPER], ################################################################################ # $1 - Either BUILD or TARGET to pick the correct OS/CPU variables to check # conditionals against. -# $2 - Optional prefix for each variable defined. +# $2 - Optional prefix for each variable defined (OPENJDK_BUILD_ or nothing). +# $3 - Optional prefix for toolchain variables (BUILD_ or nothing). AC_DEFUN([FLAGS_SETUP_LDFLAGS_CPU_DEP], [ # Setup CPU-dependent basic LDFLAGS. These can differ between the target and @@ -200,6 +199,12 @@ AC_DEFUN([FLAGS_SETUP_LDFLAGS_CPU_DEP], fi fi + if test "x${$3LD_TYPE}" = "xgold"; then + if test x$DEBUG_LEVEL = xrelease; then + $1_CPU_LDFLAGS="${$1_CPU_LDFLAGS} -Wl,--icf=all" + fi + fi + # Export variables according to old definitions, prefix with $2 if present. LDFLAGS_JDK_COMMON="$BASIC_LDFLAGS $BASIC_LDFLAGS_JDK_ONLY \ $OS_LDFLAGS $DEBUGLEVEL_LDFLAGS_JDK_ONLY ${$2EXTRA_LDFLAGS}" diff --git a/make/autoconf/hotspot.m4 b/make/autoconf/hotspot.m4 index 6dc46d17aa3..3adb1333fe5 100644 --- a/make/autoconf/hotspot.m4 +++ b/make/autoconf/hotspot.m4 @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 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 diff --git a/make/autoconf/jdk-options.m4 b/make/autoconf/jdk-options.m4 index bb188778001..87d147d4f07 100644 --- a/make/autoconf/jdk-options.m4 +++ b/make/autoconf/jdk-options.m4 @@ -316,23 +316,36 @@ AC_DEFUN_ONCE([JDKOPT_SETUP_DEBUG_SYMBOLS], AC_MSG_CHECKING([if we should add external native debug symbols to the shipped bundles]) AC_ARG_WITH([external-symbols-in-bundles], [AS_HELP_STRING([--with-external-symbols-in-bundles], - [which type of external native debug symbol information shall be shipped in product bundles (none, public, full) - (e.g. ship full/stripped pdbs on Windows) @<:@none@:>@])]) + [which type of external native debug symbol information shall be shipped with bundles/images (none, public, full). + @<:@none in release builds, full otherwise. --with-native-debug-symbols=external/zipped is a prerequisite. public is only supported on Windows@:>@])], + [], + [with_external_symbols_in_bundles=default]) if test "x$with_external_symbols_in_bundles" = x || test "x$with_external_symbols_in_bundles" = xnone ; then AC_MSG_RESULT([no]) elif test "x$with_external_symbols_in_bundles" = xfull || test "x$with_external_symbols_in_bundles" = xpublic ; then - if test "x$OPENJDK_TARGET_OS" != xwindows ; then - AC_MSG_ERROR([--with-external-symbols-in-bundles currently only works on windows!]) - elif test "x$COPY_DEBUG_SYMBOLS" != xtrue ; then - AC_MSG_ERROR([--with-external-symbols-in-bundles only works when --with-native-debug-symbols=external is used!]) - elif test "x$with_external_symbols_in_bundles" = xfull ; then + if test "x$COPY_DEBUG_SYMBOLS" != xtrue ; then + AC_MSG_ERROR([--with-external-symbols-in-bundles only works when --with-native-debug-symbols=external/zipped is used!]) + elif test "x$with_external_symbols_in_bundles" = xpublic && test "x$OPENJDK_TARGET_OS" != xwindows ; then + AC_MSG_ERROR([--with-external-symbols-in-bundles=public is only supported on Windows!]) + fi + + if test "x$with_external_symbols_in_bundles" = xfull ; then AC_MSG_RESULT([full]) SHIP_DEBUG_SYMBOLS=full else AC_MSG_RESULT([public]) SHIP_DEBUG_SYMBOLS=public fi + elif test "x$with_external_symbols_in_bundles" = xdefault ; then + if test "x$DEBUG_LEVEL" = xrelease ; then + AC_MSG_RESULT([no (default)]) + elif test "x$COPY_DEBUG_SYMBOLS" = xtrue ; then + AC_MSG_RESULT([full (default)]) + SHIP_DEBUG_SYMBOLS=full + else + AC_MSG_RESULT([no (default, native debug symbols are not external/zipped)]) + fi else AC_MSG_ERROR([$with_external_symbols_in_bundles is an unknown value for --with-external-symbols-in-bundles]) fi diff --git a/make/autoconf/lib-bundled.m4 b/make/autoconf/lib-bundled.m4 index 3246697663c..a6266bec014 100644 --- a/make/autoconf/lib-bundled.m4 +++ b/make/autoconf/lib-bundled.m4 @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 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 diff --git a/make/autoconf/platform.m4 b/make/autoconf/platform.m4 index 31451d0c37f..1b247e159ac 100644 --- a/make/autoconf/platform.m4 +++ b/make/autoconf/platform.m4 @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 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 diff --git a/make/autoconf/toolchain.m4 b/make/autoconf/toolchain.m4 index 15210efe4a7..c882deb10a7 100644 --- a/make/autoconf/toolchain.m4 +++ b/make/autoconf/toolchain.m4 @@ -516,7 +516,7 @@ AC_DEFUN([TOOLCHAIN_EXTRACT_LD_VERSION], if [ [[ "$LINKER_VERSION_STRING" == *gold* ]] ]; then [ LINKER_VERSION_NUMBER=`$ECHO $LINKER_VERSION_STRING | \ $SED -e 's/.* \([0-9][0-9]*\(\.[0-9][0-9]*\)*\).*) .*/\1/'` ] - LINKER_TYPE=gold + $1_TYPE=gold else [ LINKER_VERSION_NUMBER=`$ECHO $LINKER_VERSION_STRING | \ $SED -e 's/.* \([0-9][0-9]*\(\.[0-9][0-9]*\)*\).*/\1/'` ] 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/common/native/Flags.gmk b/make/common/native/Flags.gmk index 843701cb4db..6353b490654 100644 --- a/make/common/native/Flags.gmk +++ b/make/common/native/Flags.gmk @@ -229,6 +229,14 @@ define SetupLinkerFlags # TOOLCHAIN_TYPE plus OPENJDK_TARGET_OS ifeq ($$($1_LINK_TIME_OPTIMIZATION), true) $1_EXTRA_LDFLAGS += $(LDFLAGS_LTO) + # Instruct the ld64 linker not to delete the temporary object file + # generated during Link Time Optimization + ifeq ($(call isTargetOs, macosx), true) + $1_EXTRA_LDFLAGS += -Wl,-object_path_lto,$$($1_OBJECT_DIR)/$$($1_NAME)_lto_helper.o + endif + ifeq ($(TOOLCHAIN_TYPE), microsoft) + $1_EXTRA_LDFLAGS += -LTCGOUT:$$($1_OBJECT_DIR)/$$($1_NAME).iobj + endif endif $1_EXTRA_LDFLAGS += $$($1_LDFLAGS_$(OPENJDK_TARGET_OS_TYPE)) $$($1_LDFLAGS_$(OPENJDK_TARGET_OS)) \ diff --git a/make/conf/jib-profiles.js b/make/conf/jib-profiles.js index 795335d7c3c..93aeebc0dd6 100644 --- a/make/conf/jib-profiles.js +++ b/make/conf/jib-profiles.js @@ -1192,8 +1192,8 @@ var getJibProfilesDependencies = function (input, common) { server: "jpg", product: "jcov", version: "3.0", - build_number: "3", - file: "bundles/jcov-3.0+3.zip", + build_number: "5", + file: "bundles/jcov-3.0+5.zip", environment_name: "JCOV_HOME", }, diff --git a/make/conf/version-numbers.conf b/make/conf/version-numbers.conf index 977809535ba..4392d86ac33 100644 --- a/make/conf/version-numbers.conf +++ b/make/conf/version-numbers.conf @@ -26,17 +26,17 @@ # Default version, product, and vendor information to use, # unless overridden by configure -DEFAULT_VERSION_FEATURE=26 +DEFAULT_VERSION_FEATURE=27 DEFAULT_VERSION_INTERIM=0 DEFAULT_VERSION_UPDATE=0 DEFAULT_VERSION_PATCH=0 DEFAULT_VERSION_EXTRA1=0 DEFAULT_VERSION_EXTRA2=0 DEFAULT_VERSION_EXTRA3=0 -DEFAULT_VERSION_DATE=2026-03-17 -DEFAULT_VERSION_CLASSFILE_MAJOR=70 # "`$EXPR $DEFAULT_VERSION_FEATURE + 44`" +DEFAULT_VERSION_DATE=2026-09-15 +DEFAULT_VERSION_CLASSFILE_MAJOR=71 # "`$EXPR $DEFAULT_VERSION_FEATURE + 44`" DEFAULT_VERSION_CLASSFILE_MINOR=0 DEFAULT_VERSION_DOCS_API_SINCE=11 -DEFAULT_ACCEPTABLE_BOOT_VERSIONS="25 26" -DEFAULT_JDK_SOURCE_TARGET_VERSION=26 +DEFAULT_ACCEPTABLE_BOOT_VERSIONS="25 26 27" +DEFAULT_JDK_SOURCE_TARGET_VERSION=27 DEFAULT_PROMOTED_VERSION_PRE=ea diff --git a/make/devkit/createWindowsDevkit.sh b/make/devkit/createWindowsDevkit.sh index 7c55605c776..b21557ed498 100644 --- a/make/devkit/createWindowsDevkit.sh +++ b/make/devkit/createWindowsDevkit.sh @@ -1,6 +1,6 @@ #!/bin/bash # -# 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 diff --git a/make/hotspot/lib/CompileJvm.gmk b/make/hotspot/lib/CompileJvm.gmk index b0ea27e5081..39a549b7db0 100644 --- a/make/hotspot/lib/CompileJvm.gmk +++ b/make/hotspot/lib/CompileJvm.gmk @@ -151,6 +151,12 @@ JVM_STRIPFLAGS ?= $(STRIPFLAGS) # This source set is reused so save in cache. $(call FillFindCache, $(JVM_SRC_DIRS)) +ifeq ($(SHIP_DEBUG_SYMBOLS), full) + CFLAGS_SHIP_DEBUGINFO := -DSHIP_DEBUGINFO_FULL +else ifeq ($(SHIP_DEBUG_SYMBOLS), public) + CFLAGS_SHIP_DEBUGINFO := -DSHIP_DEBUGINFO_PUBLIC +endif + ifeq ($(call isTargetOs, windows), true) ifeq ($(STATIC_LIBS), true) WIN_EXPORT_FILE := $(JVM_OUTPUTDIR)/static-win-exports.def @@ -158,10 +164,6 @@ ifeq ($(call isTargetOs, windows), true) WIN_EXPORT_FILE := $(JVM_OUTPUTDIR)/win-exports.def endif - ifeq ($(SHIP_DEBUG_SYMBOLS), public) - CFLAGS_STRIPPED_DEBUGINFO := -DHAS_STRIPPED_DEBUGINFO - endif - JVM_LDFLAGS += -def:$(WIN_EXPORT_FILE) endif @@ -187,7 +189,7 @@ $(eval $(call SetupJdkLibrary, BUILD_LIBJVM, \ CFLAGS := $(JVM_CFLAGS), \ abstract_vm_version.cpp_CXXFLAGS := $(CFLAGS_VM_VERSION), \ arguments.cpp_CXXFLAGS := $(CFLAGS_VM_VERSION), \ - whitebox.cpp_CXXFLAGS := $(CFLAGS_STRIPPED_DEBUGINFO), \ + whitebox.cpp_CXXFLAGS := $(CFLAGS_SHIP_DEBUGINFO), \ DISABLED_WARNINGS_gcc := $(DISABLED_WARNINGS_gcc), \ DISABLED_WARNINGS_gcc_ad_$(HOTSPOT_TARGET_CPU_ARCH).cpp := nonnull, \ DISABLED_WARNINGS_gcc_bytecodeInterpreter.cpp := unused-label, \ diff --git a/make/jdk/src/classes/build/tools/generatecharacter/CaseFolding.java b/make/jdk/src/classes/build/tools/generatecharacter/CaseFolding.java deleted file mode 100644 index 9abc2059b6a..00000000000 --- a/make/jdk/src/classes/build/tools/generatecharacter/CaseFolding.java +++ /dev/null @@ -1,73 +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. 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 build.tools.generatecharacter; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class CaseFolding { - - public static void main(String[] args) throws Throwable { - if (args.length != 3) { - System.err.println("Usage: java CaseFolding TemplateFile CaseFolding.txt CaseFolding.java"); - System.exit(1); - } - var templateFile = Paths.get(args[0]); - var caseFoldingTxt = Paths.get(args[1]); - var genSrcFile = Paths.get(args[2]); - var supportedTypes = "^.*; [CTS]; .*$"; - var caseFoldingEntries = Files.lines(caseFoldingTxt) - .filter(line -> !line.startsWith("#") && line.matches(supportedTypes)) - .map(line -> { - String[] cols = line.split("; "); - return new String[] {cols[0], cols[1], cols[2]}; - }) - .filter(cols -> { - // the folding case doesn't map back to the original char. - var cp1 = Integer.parseInt(cols[0], 16); - var cp2 = Integer.parseInt(cols[2], 16); - return Character.toUpperCase(cp2) != cp1 && Character.toLowerCase(cp2) != cp1; - }) - .map(cols -> String.format(" entry(0x%s, 0x%s)", cols[0], cols[2])) - .collect(Collectors.joining(",\n", "", "")); - - // hack, hack, hack! the logic does not pick 0131. just add manually to support 'I's. - // 0049; T; 0131; # LATIN CAPITAL LETTER I - final String T_0x0131_0x49 = String.format(" entry(0x%04x, 0x%04x),\n", 0x0131, 0x49); - - // Generate .java file - Files.write( - genSrcFile, - Files.lines(templateFile) - .map(line -> line.contains("%%%Entries") ? T_0x0131_0x49 + caseFoldingEntries : line) - .collect(Collectors.toList()), - StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); - } -} diff --git a/make/jdk/src/classes/build/tools/generatecharacter/GenerateCaseFolding.java b/make/jdk/src/classes/build/tools/generatecharacter/GenerateCaseFolding.java new file mode 100644 index 00000000000..2f6a9add5cb --- /dev/null +++ b/make/jdk/src/classes/build/tools/generatecharacter/GenerateCaseFolding.java @@ -0,0 +1,134 @@ +/* + * 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. 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 build.tools.generatecharacter; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.Arrays; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class GenerateCaseFolding { + + public static void main(String[] args) throws Throwable { + if (args.length != 3) { + System.err.println("Usage: java GenerateCaseFolding TemplateFile CaseFolding.txt CaseFolding.java"); + System.exit(1); + } + var templateFile = Paths.get(args[0]); + var caseFoldingTxt = Paths.get(args[1]); + var genSrcFile = Paths.get(args[2]); + + // java.lang + var supportedTypes = "^.*; [CF]; .*$"; // full/1:M case folding + String[][] caseFoldings = Files.lines(caseFoldingTxt) + .filter(line -> !line.startsWith("#") && line.matches(supportedTypes)) + .map(line -> { + var fields = line.split("; "); + var cp = fields[0]; + fields = fields[2].trim().split(" "); + var folding = new String[fields.length + 1]; + folding[0] = cp; + System.arraycopy(fields, 0, folding, 1, fields.length); + return folding; + }) + .toArray(size -> new String[size][]); + + // util.regex + var expandedSupportedTypes = "^.*; [CTS]; .*$"; + var expanded_caseFoldingEntries = Files.lines(caseFoldingTxt) + .filter(line -> !line.startsWith("#") && line.matches(expandedSupportedTypes)) + .map(line -> { + String[] cols = line.split("; "); + return new String[]{cols[0], cols[1], cols[2]}; + }) + .filter(cols -> { + // the folding case doesn't map back to the original char. + var cp1 = Integer.parseInt(cols[0], 16); + var cp2 = Integer.parseInt(cols[2], 16); + return Character.toUpperCase(cp2) != cp1 && Character.toLowerCase(cp2) != cp1; + }) + .map(cols -> String.format(" entry(0x%s, 0x%s)", cols[0], cols[2])) + .collect(Collectors.joining(",\n", "", "")); + + // hack, hack, hack! the logic does not pick 0131. just add manually to support 'I's. + // 0049; T; 0131; # LATIN CAPITAL LETTER I + final String T_0x0131_0x49 = String.format(" entry(0x%04x, 0x%04x),\n", 0x0131, 0x49); + + Files.write( + genSrcFile, + Files.lines(templateFile) + .map(line -> line.contains("%%%Entries") ? genFoldingEntries(caseFoldings) : line) + .map(line -> line.contains("%%%Expanded_Case_Map_Entries") ? T_0x0131_0x49 + expanded_caseFoldingEntries : line) + .collect(Collectors.toList()), + StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); + } + + private static long foldingToLong(String[] folding) { + int cp = Integer.parseInt(folding[0], 16); + long value = (long)Integer.parseInt(folding[1], 16); + if (!Character.isSupplementaryCodePoint(cp) && folding.length != 2) { + var shift = 16; + for (int j = 2; j < folding.length; j++) { + value |= (long)Integer.parseInt(folding[j], 16) << shift; + shift <<= 1; + } + value = value | (long) (folding.length - 1) << 48; + } + return value; + } + + private static String genFoldingEntries(String[][] foldings) { + StringBuilder sb = new StringBuilder(); + sb.append(" private static final int[] CASE_FOLDING_CPS = {\n"); + int width = 10; + for (int i = 0; i < foldings.length; i++) { + if (i % width == 0) + sb.append(" "); + sb.append(String.format("0X%s", foldings[i][0])); + if (i < foldings.length - 1) + sb.append(", "); + if (i % width == width - 1 || i == foldings.length - 1) + sb.append("\n"); + } + sb.append(" };\n\n"); + + sb.append(" private static final long[] CASE_FOLDING_VALUES = {\n"); + width = 6; + for (int i = 0; i < foldings.length; i++) { + if (i % width == 0) + sb.append(" "); // indent + sb.append(String.format("0x%013xL", foldingToLong(foldings[i]))); + if (i < foldings.length - 1) + sb.append(", "); + if (i % width == width - 1 || i == foldings.length - 1) { + sb.append("\n"); + } + } + sb.append(" };\n"); + return sb.toString(); + } +} diff --git a/make/jdk/src/classes/build/tools/pandocfilter/PandocFilter.java b/make/jdk/src/classes/build/tools/pandocfilter/PandocFilter.java index ebb49613e53..9f4d84ac95b 100644 --- a/make/jdk/src/classes/build/tools/pandocfilter/PandocFilter.java +++ b/make/jdk/src/classes/build/tools/pandocfilter/PandocFilter.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 diff --git a/make/jdk/src/classes/build/tools/taglet/JSpec.java b/make/jdk/src/classes/build/tools/taglet/JSpec.java index ca45104e086..1c301e94a8a 100644 --- a/make/jdk/src/classes/build/tools/taglet/JSpec.java +++ b/make/jdk/src/classes/build/tools/taglet/JSpec.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 @@ -31,10 +31,9 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import java.lang.reflect.Field; import javax.lang.model.element.Element; -import javax.lang.model.element.PackageElement; -import javax.lang.model.element.TypeElement; import com.sun.source.doctree.DocTree; import com.sun.source.doctree.LiteralTree; @@ -160,9 +159,10 @@ public class JSpec implements Taglet { if (m.find()) { String chapter = m.group("chapter"); String section = m.group("section"); + String rootParent = currentPath().replaceAll("[^/]+", ".."); - String url = String.format("%1$s/../specs/%2$s/%2$s-%3$s.html#%2$s-%3$s%4$s", - docRoot(elem), idPrefix, chapter, section); + String url = String.format("%1$s/specs/%2$s/%2$s-%3$s.html#%2$s-%3$s%4$s", + rootParent, idPrefix, chapter, section); sb.append(" CURRENT_PATH = null; + + private String currentPath() { + if (CURRENT_PATH == null) { + try { + Field f = Class.forName("jdk.javadoc.internal.doclets.formats.html.HtmlDocletWriter") + .getField("CURRENT_PATH"); + @SuppressWarnings("unchecked") + ThreadLocal tl = (ThreadLocal) f.get(null); + CURRENT_PATH = tl; + } catch (ReflectiveOperationException e) { + throw new RuntimeException("Cannot determine current path", e); + } + } + return CURRENT_PATH.get(); + } private String expand(List trees) { return (new SimpleDocTreeVisitor() { @@ -209,34 +225,4 @@ public class JSpec implements Taglet { }).visit(trees, new StringBuilder()).toString(); } - private String docRoot(Element elem) { - switch (elem.getKind()) { - case MODULE: - return ".."; - - case PACKAGE: - PackageElement pe = (PackageElement)elem; - String pkgPart = pe.getQualifiedName() - .toString() - .replace('.', '/') - .replaceAll("[^/]+", ".."); - return pe.getEnclosingElement() != null - ? "../" + pkgPart - : pkgPart; - - case CLASS, ENUM, RECORD, INTERFACE, ANNOTATION_TYPE: - TypeElement te = (TypeElement)elem; - return te.getQualifiedName() - .toString() - .replace('.', '/') - .replaceAll("[^/]+", ".."); - - default: - var enclosing = elem.getEnclosingElement(); - if (enclosing == null) - throw new IllegalArgumentException(elem.getKind().toString()); - return docRoot(enclosing); - } - } - } diff --git a/make/jdk/src/classes/build/tools/taglet/ToolGuide.java b/make/jdk/src/classes/build/tools/taglet/ToolGuide.java index 72a8ab05b3b..8db2aee3092 100644 --- a/make/jdk/src/classes/build/tools/taglet/ToolGuide.java +++ b/make/jdk/src/classes/build/tools/taglet/ToolGuide.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 @@ -31,10 +31,9 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import java.lang.reflect.Field; import javax.lang.model.element.Element; -import javax.lang.model.element.PackageElement; -import javax.lang.model.element.TypeElement; import com.sun.source.doctree.DocTree; import com.sun.source.doctree.UnknownBlockTagTree; @@ -68,7 +67,7 @@ public class ToolGuide implements Taglet { static final String TAG_NAME = "toolGuide"; - static final String BASE_URL = "../specs/man"; + static final String BASE_URL = "specs/man"; static final Pattern TAG_PATTERN = Pattern.compile("(?s)(?[A-Za-z0-9]+)\\s*(?

See CR6768230 for details and base class for test info. */ /* * @test @@ -117,6 +116,7 @@ public class JInternalFrameMoveOverlapping extends OverlappingTestBase { JFrame frame = new JFrame("Test Window"); frame.setSize(300, 300); frame.setContentPane(desktopPane); + frame.setLocationRelativeTo(null); frame.setVisible(true); locTopFrame = topFrame.getLocationOnScreen(); diff --git a/test/jdk/java/awt/Mixing/AWT_Mixing/JInternalFrameOverlapping.java b/test/jdk/java/awt/Mixing/AWT_Mixing/JInternalFrameOverlapping.java index 4cb9425abe7..8d619e34c35 100644 --- a/test/jdk/java/awt/Mixing/AWT_Mixing/JInternalFrameOverlapping.java +++ b/test/jdk/java/awt/Mixing/AWT_Mixing/JInternalFrameOverlapping.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, 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 @@ -75,6 +75,7 @@ public class JInternalFrameOverlapping extends OverlappingTestBase { JFrame frame = new JFrame("Test Window"); frame.setSize(300, 300); frame.setContentPane(desktopPane); + frame.setLocationRelativeTo(null); frame.setVisible(true); JInternalFrame bottomFrame = new JInternalFrame("bottom frame", false, false, false, false); bottomFrame.setSize(220, 220); diff --git a/test/jdk/java/awt/Mixing/AWT_Mixing/JMenuBarOverlapping.java b/test/jdk/java/awt/Mixing/AWT_Mixing/JMenuBarOverlapping.java index 792831c2d8d..f3a213e5144 100644 --- a/test/jdk/java/awt/Mixing/AWT_Mixing/JMenuBarOverlapping.java +++ b/test/jdk/java/awt/Mixing/AWT_Mixing/JMenuBarOverlapping.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, 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 @@ -22,7 +22,6 @@ */ -import java.awt.Color; import java.awt.GridLayout; import java.awt.Point; import java.awt.Robot; @@ -30,12 +29,14 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; + import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JSeparator; import javax.swing.SwingUtilities; + import test.java.awt.regtesthelpers.Util; /** @@ -72,7 +73,6 @@ public class JMenuBarOverlapping extends OverlappingTestBase { frame = new JFrame("Mixing : Dropdown Overlapping test"); frame.setLayout(new GridLayout(0,1)); frame.setSize(200, 200); - frame.setVisible(true); menuBar = new JMenuBar(); JMenu menu = new JMenu("Test Menu"); @@ -104,6 +104,7 @@ public class JMenuBarOverlapping extends OverlappingTestBase { frame.setJMenuBar(menuBar); propagateAWTControls(frame); + frame.setLocationRelativeTo(null); frame.setVisible(true); } diff --git a/test/jdk/java/awt/Mixing/AWT_Mixing/JPopupMenuOverlapping.java b/test/jdk/java/awt/Mixing/AWT_Mixing/JPopupMenuOverlapping.java index d4b50287dc6..e80475088ac 100644 --- a/test/jdk/java/awt/Mixing/AWT_Mixing/JPopupMenuOverlapping.java +++ b/test/jdk/java/awt/Mixing/AWT_Mixing/JPopupMenuOverlapping.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, 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 @@ -22,17 +22,18 @@ */ -import java.awt.Color; import java.awt.Point; import java.awt.Robot; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; + import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.SpringLayout; import javax.swing.SwingUtilities; + import test.java.awt.regtesthelpers.Util; /** @@ -82,6 +83,7 @@ public class JPopupMenuOverlapping extends OverlappingTestBase { item.addActionListener(menuListener); } propagateAWTControls(frame); + frame.setLocationRelativeTo(null); frame.setVisible(true); loc = frame.getContentPane().getLocationOnScreen(); } diff --git a/test/jdk/java/awt/Mixing/AWT_Mixing/JScrollPaneOverlapping.java b/test/jdk/java/awt/Mixing/AWT_Mixing/JScrollPaneOverlapping.java index f22eacba82d..91538b75c13 100644 --- a/test/jdk/java/awt/Mixing/AWT_Mixing/JScrollPaneOverlapping.java +++ b/test/jdk/java/awt/Mixing/AWT_Mixing/JScrollPaneOverlapping.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, 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 @@ -95,6 +95,7 @@ public class JScrollPaneOverlapping extends OverlappingTestBase { }); f.getContentPane().add(scrollPane); + f.setLocationRelativeTo(null); f.setVisible(true); propagateAWTControls(p); // JButton b = new JButton("Space extender"); diff --git a/test/jdk/java/awt/Mixing/AWT_Mixing/JSplitPaneOverlapping.java b/test/jdk/java/awt/Mixing/AWT_Mixing/JSplitPaneOverlapping.java index 7e1cb9434e4..5875a04b62b 100644 --- a/test/jdk/java/awt/Mixing/AWT_Mixing/JSplitPaneOverlapping.java +++ b/test/jdk/java/awt/Mixing/AWT_Mixing/JSplitPaneOverlapping.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, 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 @@ -89,6 +89,7 @@ public class JSplitPaneOverlapping extends OverlappingTestBase { frame.getContentPane().add(splitPane); frame.pack(); + frame.setLocationRelativeTo(null); frame.setVisible(true); } diff --git a/test/jdk/java/awt/Mixing/AWT_Mixing/MixingFrameResizing.java b/test/jdk/java/awt/Mixing/AWT_Mixing/MixingFrameResizing.java index 545566970f8..8c19a80bd43 100644 --- a/test/jdk/java/awt/Mixing/AWT_Mixing/MixingFrameResizing.java +++ b/test/jdk/java/awt/Mixing/AWT_Mixing/MixingFrameResizing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, 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 @@ -26,9 +26,11 @@ import java.awt.Dimension; import java.awt.Point; import java.awt.Robot; import java.awt.event.InputEvent; + import javax.swing.JFrame; import javax.swing.SpringLayout; import javax.swing.SwingUtilities; + import test.java.awt.regtesthelpers.Util; /** @@ -65,6 +67,7 @@ public class MixingFrameResizing extends OverlappingTestBase { frame = new JFrame("Mixing : Frame Resizing test"); frame.setLayout(new SpringLayout()); frame.setSize(50, 50); + frame.setLocationRelativeTo(null); frame.setVisible(true); propagateAWTControls(frame); Util.waitTillShown(frame); diff --git a/test/jdk/java/awt/Mixing/AWT_Mixing/MixingPanelsResizing.java b/test/jdk/java/awt/Mixing/AWT_Mixing/MixingPanelsResizing.java index 39a59dc2a5c..1bb9b442dd8 100644 --- a/test/jdk/java/awt/Mixing/AWT_Mixing/MixingPanelsResizing.java +++ b/test/jdk/java/awt/Mixing/AWT_Mixing/MixingPanelsResizing.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 @@ -22,10 +22,23 @@ */ -import java.awt.*; +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Color; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Robot; +import java.awt.Toolkit; import java.awt.event.InputEvent; -import javax.swing.*; -import java.io.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + import test.java.awt.regtesthelpers.Util; /** @@ -130,6 +143,7 @@ public class MixingPanelsResizing { frame.add(jPanel, BorderLayout.NORTH); frame.pack(); + frame.setLocationRelativeTo(null); frame.setVisible(true); } }); @@ -298,6 +312,7 @@ public class MixingPanelsResizing { failureMessage = whyFailed; mainThread.interrupt(); }//fail() + + static class TestPassedException extends RuntimeException { + } }// class JButtonInGlassPane -class TestPassedException extends RuntimeException { -} diff --git a/test/jdk/java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.java b/test/jdk/java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.java index 4975cc165c2..03abb58f673 100644 --- a/test/jdk/java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.java +++ b/test/jdk/java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.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 @@ -56,13 +56,13 @@ public class OpaqueOverlapping extends OverlappingTestBase { { useClickValidation = false; - failMessage = "Opacity test mismatchs"; + failMessage = "Opacity test mismatches"; // CR 6994264 (Choice autohides dropdown on Solaris 10) skipClassNames = new String[] { "Choice" }; } private String testSeq; - private final static String checkSeq = "010000101"; + private static final String checkSeq = "010000101"; private Point heavyLoc; private JButton light; private Frame frame = null; @@ -89,6 +89,7 @@ public class OpaqueOverlapping extends OverlappingTestBase { panel.add(light); frame.add(panel); frame.setBounds(50, 50, 400, 400); + frame.setLocationRelativeTo(null); frame.setVisible(true); currentAwtControl.addMouseListener(new MouseAdapter() { diff --git a/test/jdk/java/awt/Mixing/AWT_Mixing/OverlappingTestBase.java b/test/jdk/java/awt/Mixing/AWT_Mixing/OverlappingTestBase.java index 794578a5907..3d4adecbd17 100644 --- a/test/jdk/java/awt/Mixing/AWT_Mixing/OverlappingTestBase.java +++ b/test/jdk/java/awt/Mixing/AWT_Mixing/OverlappingTestBase.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 @@ -34,6 +34,7 @@ import java.awt.Robot; import java.awt.Scrollbar; import java.awt.TextField; import java.awt.Toolkit; +import java.awt.Window; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; @@ -171,6 +172,7 @@ public abstract class OverlappingTestBase { frame.getContentPane().setBackground(AWT_BACKGROUND_COLOR); frame.setSize(size, size); frame.setUndecorated(true); + frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); p[0] = frame.getLocation(); @@ -259,6 +261,9 @@ public abstract class OverlappingTestBase { embedder.setBackground(Color.RED); embedder.setPreferredSize(new Dimension(150, 150)); container.add(embedder); + if (container instanceof Window) { + ((Window) container).setLocationRelativeTo(null); + } container.setVisible(true); // create peer long frameWindow = 0; @@ -301,6 +306,7 @@ public abstract class OverlappingTestBase { EmbeddedFrame eframe = (EmbeddedFrame) eframeCtor.newInstance(frameWindow); setupControl(eframe); eframe.setSize(new Dimension(150, 150)); + eframe.setLocationRelativeTo(null); eframe.setVisible(true); // System.err.println(eframe.getSize()); } catch (Exception ex) { @@ -682,6 +688,7 @@ public abstract class OverlappingTestBase { failureMessage = whyFailed; mainThread.interrupt(); }//fail() + + static class TestPassedException extends RuntimeException { + } }// class LWComboBox -class TestPassedException extends RuntimeException { -} diff --git a/test/jdk/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java b/test/jdk/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java index 928a5c437cb..0dd42a36cd0 100644 --- a/test/jdk/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java +++ b/test/jdk/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.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 @@ -21,10 +21,21 @@ * questions. */ -import java.awt.*; -import java.awt.event.*; -import java.util.regex.*; -import javax.swing.*; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.SpringLayout; + import test.java.awt.regtesthelpers.Util; /** @@ -55,6 +66,10 @@ public abstract class SimpleOverlappingTestBase extends OverlappingTestBase { this.useDefaultClickValidation = defaultClickValidation; } + protected boolean isMultiFramesTest(){ + return true; + } + public SimpleOverlappingTestBase() { this(true); } @@ -114,6 +129,7 @@ public abstract class SimpleOverlappingTestBase extends OverlappingTestBase { propagateAWTControls(f); + f.setLocationRelativeTo(null); f.setVisible(true); } @@ -140,21 +156,29 @@ public abstract class SimpleOverlappingTestBase extends OverlappingTestBase { /* this is a workaround for certain jtreg(?) focus issue: tests fail starting after failing mixing tests but always pass alone. */ - JFrame ancestor = (JFrame)(testedComponent.getTopLevelAncestor()); - if( ancestor != null ) { - Point ancestorLoc = ancestor.getLocationOnScreen(); - ancestorLoc.translate(isOel7orLater() ? 5 : - ancestor.getWidth() / 2 - 15, 2); - robot.mouseMove(ancestorLoc.x, ancestorLoc.y); - Util.waitForIdle(robot); - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.delay(50); - robot.mouseRelease(InputEvent.BUTTON1_MASK); - Util.waitForIdle(robot); + JFrame ancestor = (JFrame) (testedComponent.getTopLevelAncestor()); + if (ancestor != null) { + final CountDownLatch latch = new CountDownLatch(1); + ancestor.addFocusListener(new FocusAdapter() { + @Override public void focusGained(FocusEvent e) { + latch.countDown(); + } + }); + ancestor.requestFocus(); + try { + if (!latch.await(1L, TimeUnit.SECONDS)) { + throw new RuntimeException( + "Ancestor frame didn't receive focus"); + } + } catch (InterruptedException e) { + throw new RuntimeException(e); + } } clickAndBlink(robot, lLoc); - Util.waitForIdle(robot); + if (ancestor != null && isMultiFramesTest()) { + ancestor.dispose(); + } return wasLWClicked; } @@ -172,5 +196,4 @@ public abstract class SimpleOverlappingTestBase extends OverlappingTestBase { } return false; } - } diff --git a/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.java b/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.java index e2b2d8cac78..0b2d430a150 100644 --- a/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.java +++ b/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -49,40 +49,35 @@ import java.awt.event.ActionListener; public class PrintDialogsTest extends Panel implements ActionListener { - static final String INSTRUCTIONS = """ - This test is free format, which means there is no enforced or guided sequence. - - Please select each of - (a) The dialog parent type. - (b) The dialog modality type - (c) The print dialog type (Print dialog or Page Setup dialog) - - Once the choices have been made click the "Start test" button. - - Three windows will appear - (1) A Frame or a Dialog - in the case you selected "Dialog" as the parent type - (2) a Window (ie an undecorated top-level) - (3) A dialog with two buttons "Open" and "Finish" - - Now check as follows whether modal blocking works as expected. - Windows (1) and (2) contain a button which you should be able to press - ONLY if you selected "Non-modal", or "Modeless" for modality type. - In other cases window (3) will block input to (1) and (2) - - Then push the "Open" button on the Dialog to show the printing dialog and check - if it blocks the rest of the application - ie all of windows (1), (2) and (3) - should ALWAYS be blocked when the print dialog is showing. - Now cancel the printing dialog and check the correctness of modal blocking - behavior for the Dialog again. - To close all the 3 test windows please push the "Finish" button. - - Repeat all the above for different combinations, which should include - using all of the Dialog parent choices and all of the Dialog Modality types. - - If any behave incorrectly, note the combination of choices and press Fail. - - If all behave correctly, press Pass. - """; + static final String INSTRUCTIONS = + "1. On the Test UI Select:\n" + + "\tThe dialog parent type. (e.g. Frame, Dialog, Hidden, Null)\n" + + "\tThe dialog modality type. (e.g. Modal, Non-Modal, Toolkit modal).\n" + + "\tThe print dialog type. (Print dialog or Page Setup dialog).\n\n" + + "2. Next, click on 'Start test' - Three windows will appear:\n" + + "\tWindow (1) -a Frame or Dialog (depending on selected parent type).\n" + + "\tWindow (2) -an undecorated top-level Window.\n" + + "\tWindow (3) -a Dialog containing two buttons: 'Open' and 'Finish'.\n" + + "\tWindows (1) & (2) have a Dummy button.\n\n" + + "3. Press the button on Window (1) & Window (2) \n" + + "Verification step:\n" + + "\tIf Modality is 'Non-modal' or 'Modeless', Button is pressed \n" + + "\tIf Modality is 'Document' & parent is not Frame/Dialog, Button is pressed \n" + + "\tIn all other cases, button is not pressed & Window (3) should \n" + + "\tblock input to Windows (1) & (2).\n\n" + + "4. Next, press the 'Open' button in Window (3) to open print dialog.\n\n" + + "5. Press the button on Window (1) & Window (2)\n" + + "Verification step:\n" + + "\tThe print dialog should block all three windows (1, 2, and 3).\n\n" + + "6. Cancel the print dialog, Check again if Window (3) " + + "blocks Windows (1) and (2) correctly.\n" + + "Verification step:\n" + + "\tConditions as seen in Verification step 3 " + + "should be seen, as before.\n" + + "To close all test windows, press 'Finish'.\n\n" + + "7. Repeat the steps for different combinations of Dialog Parent, Dialog Modality Type, Print Dialg Type.\n" + + "Try every dialog parent type and every dialog modality type.\n\n" + + "If any of the Verification step fails, note the combination and press 'Fail'.\n"; public static void main(String[] args) throws Exception { diff --git a/test/jdk/java/awt/Modal/PrintDialogsTest/Test.java b/test/jdk/java/awt/Modal/PrintDialogsTest/Test.java index 3c8faceb3a9..1afe44935d2 100644 --- a/test/jdk/java/awt/Modal/PrintDialogsTest/Test.java +++ b/test/jdk/java/awt/Modal/PrintDialogsTest/Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -191,6 +191,7 @@ public class Test { break; case DIALOG: dialog = new CustomDialog(parent); + break; case FRAME: dialog = new CustomDialog(frame); break; diff --git a/test/jdk/java/awt/Modal/ToFront/DialogToFrontModeless1Test.java b/test/jdk/java/awt/Modal/ToFront/DialogToFrontModeless1Test.java index 4faea19db2f..928bfd027ea 100644 --- a/test/jdk/java/awt/Modal/ToFront/DialogToFrontModeless1Test.java +++ b/test/jdk/java/awt/Modal/ToFront/DialogToFrontModeless1Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -34,12 +34,27 @@ * @build Flag * @build TestDialog * @build TestFrame + * @build jdk.test.lib.Platform * @run main DialogToFrontModeless1Test */ +import jdk.test.lib.Platform; +import jtreg.SkippedException; + public class DialogToFrontModeless1Test { public static void main(String[] args) throws Exception { + if (Platform.isOnWayland()) { + // Some tested systems are still use XTEST(X11 protocol) + // for key and mouse press emulation, but this will not work + // outside of X11. + // An emulated input event will reach X11 clients, but not the + // Wayland compositor, which is responsible for window restacking. + // + // This skip can be removed later once all systems switch to + // the default remote desktop XDG portal. + throw new SkippedException("SKIPPED: robot functionality is limited on the current platform."); + } (new DialogToFrontModelessTest()).doTest(); } } diff --git a/test/jdk/java/awt/Mouse/GetMousePositionTest/GetMousePositionWithOverlay.java b/test/jdk/java/awt/Mouse/GetMousePositionTest/GetMousePositionWithOverlay.java index fb3ea40a531..3c41ea3ed82 100644 --- a/test/jdk/java/awt/Mouse/GetMousePositionTest/GetMousePositionWithOverlay.java +++ b/test/jdk/java/awt/Mouse/GetMousePositionTest/GetMousePositionWithOverlay.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, 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 diff --git a/test/jdk/java/awt/Mouse/GetMousePositionTest/GetMousePositionWithPopup.java b/test/jdk/java/awt/Mouse/GetMousePositionTest/GetMousePositionWithPopup.java index 663942b7630..828a46072aa 100644 --- a/test/jdk/java/awt/Mouse/GetMousePositionTest/GetMousePositionWithPopup.java +++ b/test/jdk/java/awt/Mouse/GetMousePositionTest/GetMousePositionWithPopup.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 diff --git a/test/jdk/java/awt/PrintJob/PageSetupDlgBlockingTest/PageSetupDlgBlockingTest.java b/test/jdk/java/awt/PrintJob/PageSetupDlgBlockingTest/PageSetupDlgBlockingTest.java index bc392ab9efe..8ed878f201e 100644 --- a/test/jdk/java/awt/PrintJob/PageSetupDlgBlockingTest/PageSetupDlgBlockingTest.java +++ b/test/jdk/java/awt/PrintJob/PageSetupDlgBlockingTest/PageSetupDlgBlockingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 diff --git a/test/jdk/java/awt/TextArea/TextAreaCursorTest/HoveringAndDraggingTest.java b/test/jdk/java/awt/TextArea/TextAreaCursorTest/HoveringAndDraggingTest.java index 646bc6aa6b9..a9abe0ee23e 100644 --- a/test/jdk/java/awt/TextArea/TextAreaCursorTest/HoveringAndDraggingTest.java +++ b/test/jdk/java/awt/TextArea/TextAreaCursorTest/HoveringAndDraggingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/awt/TextArea/TextScrollTest.java b/test/jdk/java/awt/TextArea/TextScrollTest.java index fbd5c022580..a3e5266c62e 100644 --- a/test/jdk/java/awt/TextArea/TextScrollTest.java +++ b/test/jdk/java/awt/TextArea/TextScrollTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 diff --git a/test/jdk/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.java b/test/jdk/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.java index aa785f54733..c28a8388337 100644 --- a/test/jdk/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.java +++ b/test/jdk/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 diff --git a/test/jdk/java/awt/datatransfer/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java b/test/jdk/java/awt/datatransfer/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java index 3502cd4f9c5..37ce16a4a63 100644 --- a/test/jdk/java/awt/datatransfer/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java +++ b/test/jdk/java/awt/datatransfer/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, 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 diff --git a/test/jdk/java/awt/dnd/DnDFileGroupDescriptor/DnDFileGroupDescriptor.java b/test/jdk/java/awt/dnd/DnDFileGroupDescriptor/DnDFileGroupDescriptor.java index b106deac73c..84e0a2e68cb 100644 --- a/test/jdk/java/awt/dnd/DnDFileGroupDescriptor/DnDFileGroupDescriptor.java +++ b/test/jdk/java/awt/dnd/DnDFileGroupDescriptor/DnDFileGroupDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 diff --git a/test/jdk/java/awt/dnd/FileListBetweenJVMsTest/FileListBetweenJVMsTest.java b/test/jdk/java/awt/dnd/FileListBetweenJVMsTest/FileListBetweenJVMsTest.java index 102ff501040..bcdbe6d3258 100644 --- a/test/jdk/java/awt/dnd/FileListBetweenJVMsTest/FileListBetweenJVMsTest.java +++ b/test/jdk/java/awt/dnd/FileListBetweenJVMsTest/FileListBetweenJVMsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.java b/test/jdk/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.java index 6de649f846f..2f51948c4ee 100644 --- a/test/jdk/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.java +++ b/test/jdk/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 diff --git a/test/jdk/java/awt/dnd/URIListToFileListBetweenJVMsTest/URIListToFileListBetweenJVMsTest.java b/test/jdk/java/awt/dnd/URIListToFileListBetweenJVMsTest/URIListToFileListBetweenJVMsTest.java index d9b6bd5e87c..fafeb45332d 100644 --- a/test/jdk/java/awt/dnd/URIListToFileListBetweenJVMsTest/URIListToFileListBetweenJVMsTest.java +++ b/test/jdk/java/awt/dnd/URIListToFileListBetweenJVMsTest/URIListToFileListBetweenJVMsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, 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 diff --git a/test/jdk/java/awt/event/KeyEvent/KeyTyped/EscapeKeyTyped.java b/test/jdk/java/awt/event/KeyEvent/KeyTyped/EscapeKeyTyped.java index 51fb3fedaba..34c9dda5e5d 100644 --- a/test/jdk/java/awt/event/KeyEvent/KeyTyped/EscapeKeyTyped.java +++ b/test/jdk/java/awt/event/KeyEvent/KeyTyped/EscapeKeyTyped.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 diff --git a/test/jdk/java/awt/event/MouseEvent/MenuDragMouseEventAbsoluteCoordsTest/MenuDragMouseEventAbsoluteCoordsTest.java b/test/jdk/java/awt/event/MouseEvent/MenuDragMouseEventAbsoluteCoordsTest/MenuDragMouseEventAbsoluteCoordsTest.java index 41dc4709fc2..bfd436e062a 100644 --- a/test/jdk/java/awt/event/MouseEvent/MenuDragMouseEventAbsoluteCoordsTest/MenuDragMouseEventAbsoluteCoordsTest.java +++ b/test/jdk/java/awt/event/MouseEvent/MenuDragMouseEventAbsoluteCoordsTest/MenuDragMouseEventAbsoluteCoordsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 diff --git a/test/jdk/java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion_2.java b/test/jdk/java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion_2.java index 6022ed32094..39b0f08ebd5 100644 --- a/test/jdk/java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion_2.java +++ b/test/jdk/java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion_2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion_3.java b/test/jdk/java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion_3.java index e1f2991a2fb..d10dd6eab79 100644 --- a/test/jdk/java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion_3.java +++ b/test/jdk/java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion_3.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/awt/event/helpers/lwcomponents/LWButton.java b/test/jdk/java/awt/event/helpers/lwcomponents/LWButton.java index e45d3d5f430..8d132825de0 100644 --- a/test/jdk/java/awt/event/helpers/lwcomponents/LWButton.java +++ b/test/jdk/java/awt/event/helpers/lwcomponents/LWButton.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, 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 diff --git a/test/jdk/java/awt/font/GlyphVector/GetGlyphCharIndexTest.java b/test/jdk/java/awt/font/GlyphVector/GetGlyphCharIndexTest.java index 939643c7a45..e2b092c7392 100644 --- a/test/jdk/java/awt/font/GlyphVector/GetGlyphCharIndexTest.java +++ b/test/jdk/java/awt/font/GlyphVector/GetGlyphCharIndexTest.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 diff --git a/test/jdk/java/awt/font/GlyphVector/GlyphMetricsTest.java b/test/jdk/java/awt/font/GlyphVector/GlyphMetricsTest.java new file mode 100644 index 00000000000..415b840671c --- /dev/null +++ b/test/jdk/java/awt/font/GlyphVector/GlyphMetricsTest.java @@ -0,0 +1,72 @@ +/* + * 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 8167268 + * @summary Checks behavior of GlyphVector.getGlyphMetrics(int). + */ + +import java.awt.Font; +import java.awt.Rectangle; +import java.awt.font.FontRenderContext; +import java.awt.font.GlyphMetrics; +import java.awt.font.GlyphVector; +import java.awt.font.TextLayout; +import java.awt.geom.Rectangle2D; + +public class GlyphMetricsTest { + + public static void main(String[] args) { + + String text = "The quick brown \r\n fox JUMPS over \t the lazy dog."; + Font font = new Font(Font.DIALOG, Font.PLAIN, 60); + FontRenderContext frc = new FontRenderContext(null, true, true); + GlyphVector gv = font.createGlyphVector(frc, text); + + for (int i = 0; i < gv.getNumGlyphs(); i++) { + + GlyphMetrics gm = gv.getGlyphMetrics(i); + Rectangle2D bounds = gm.getBounds2D(); + assertEqual(gm.getAdvance(), gm.getAdvanceX(), 0, "advance x", i); + assertEqual(0, gm.getAdvanceY(), 0, "advance y", i); + + // assumes one glyph per char in the test text + String character = text.substring(i, i + 1); + TextLayout layout = new TextLayout(character, font, frc); + Rectangle pixelBounds = layout.getPixelBounds(frc, 0, 0); + assertEqual(pixelBounds.getWidth(), bounds.getWidth(), 2, "width", i); + assertEqual(pixelBounds.getHeight(), bounds.getHeight(), 2, "height", i); + assertEqual(pixelBounds.getX(), bounds.getX(), 2, "x", i); + assertEqual(pixelBounds.getY(), bounds.getY(), 2, "y", i); + } + } + + private static void assertEqual(double d1, double d2, double variance, + String scenario, int index) { + if (Math.abs(d1 - d2) > variance) { + String msg = String.format("%s for index %d: %f != %f", scenario, index, d1, d2); + throw new RuntimeException(msg); + } + } +} 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/awt/grab/EmbeddedFrameTest1/EmbeddedFrameTest1.java b/test/jdk/java/awt/grab/EmbeddedFrameTest1/EmbeddedFrameTest1.java index 7942402af4f..8d2fe217326 100644 --- a/test/jdk/java/awt/grab/EmbeddedFrameTest1/EmbeddedFrameTest1.java +++ b/test/jdk/java/awt/grab/EmbeddedFrameTest1/EmbeddedFrameTest1.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 diff --git a/test/jdk/java/awt/im/8041990/bug8041990.java b/test/jdk/java/awt/im/8041990/bug8041990.java index d4bf847592d..c5ddbac42ba 100644 --- a/test/jdk/java/awt/im/8041990/bug8041990.java +++ b/test/jdk/java/awt/im/8041990/bug8041990.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2017, 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 diff --git a/test/jdk/java/awt/im/PinyinIMCapsTest.java b/test/jdk/java/awt/im/PinyinIMCapsTest.java index 707f56c6651..d8451b33cbd 100644 --- a/test/jdk/java/awt/im/PinyinIMCapsTest.java +++ b/test/jdk/java/awt/im/PinyinIMCapsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2024, 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 diff --git a/test/jdk/java/awt/im/PinyinIMCommaTest.java b/test/jdk/java/awt/im/PinyinIMCommaTest.java index 4fccd47ea7c..a29dbee910d 100644 --- a/test/jdk/java/awt/im/PinyinIMCommaTest.java +++ b/test/jdk/java/awt/im/PinyinIMCommaTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2024, 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 diff --git a/test/jdk/java/awt/im/PinyinIMFullstopTest.java b/test/jdk/java/awt/im/PinyinIMFullstopTest.java index 2c8da202544..0371384cf9b 100644 --- a/test/jdk/java/awt/im/PinyinIMFullstopTest.java +++ b/test/jdk/java/awt/im/PinyinIMFullstopTest.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 diff --git a/test/jdk/java/awt/image/AffineTransformOp/AffineTxOpSizeTest.java b/test/jdk/java/awt/image/AffineTransformOp/AffineTxOpSizeTest.java new file mode 100644 index 00000000000..bc08116f0de --- /dev/null +++ b/test/jdk/java/awt/image/AffineTransformOp/AffineTxOpSizeTest.java @@ -0,0 +1,68 @@ +/* + * 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 + * 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 4690476 + * @summary Verify behaviour with transform which creates too large an image. + */ + +import java.awt.geom.AffineTransform; +import java.awt.image.AffineTransformOp; +import static java.awt.image.AffineTransformOp.*; +import java.awt.image.BufferedImage; +import java.awt.image.Raster; +import java.awt.image.RasterFormatException; + +public class AffineTxOpSizeTest { + + static final int W = 2552, H = 3300; + // This transform will require an approx 60_000 x 60_000 raster which is too large + static final AffineTransform AT = new AffineTransform(0.2, 23, 18, 0.24, -70.0, -90.0); + + public static void main(String[] args) { + BufferedImage src = new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB); + testAOP(src, TYPE_BICUBIC); + testAOP(src, TYPE_BILINEAR); + testAOP(src, TYPE_NEAREST_NEIGHBOR); + } + + static void testAOP(BufferedImage src, int iType) { + AffineTransformOp aop = new AffineTransformOp(AT, iType); + System.out.println("Bounds=" + aop.getBounds2D(src)); + + aop.filter(src, null); + aop.filter(src.getRaster(), null); + try { + aop.createCompatibleDestImage(src, src.getColorModel()); + throw new RuntimeException("No exception for image"); + } catch (RasterFormatException e) { + } + try { + aop.createCompatibleDestRaster(src.getRaster()); + throw new RuntimeException("No exception for raster"); + } catch (RasterFormatException e) { + } + } + +} diff --git a/test/jdk/java/awt/image/ConvolveOp/KernelInitialisationTest.java b/test/jdk/java/awt/image/ConvolveOp/KernelInitialisationTest.java index 607f0a7a8dc..0d58472385c 100644 --- a/test/jdk/java/awt/image/ConvolveOp/KernelInitialisationTest.java +++ b/test/jdk/java/awt/image/ConvolveOp/KernelInitialisationTest.java @@ -25,36 +25,49 @@ * @test * @bug 8368729 * @summary Tests that passing invalid values to Kernel constructor - * throws only IllegalArgumentException + * throws only IllegalArgumentException or NullPointerException */ import java.awt.image.Kernel; public class KernelInitialisationTest { - private static void expectIllegalArgumentException(Runnable code) { + + private static void test(int width, int height, float[] data, + Class expected) + { + System.out.printf("Testing for width: %d, height: %d, data: %s%n", + width, height, data == null ? "null" : "not null"); + Class actual = null; try { - code.run(); - throw new RuntimeException("Expected IllegalArgumentException" + - " but no exception was thrown"); - } catch (IllegalArgumentException e) { - // we expect IllegalArgumentException + new Kernel(width, height, data); + } catch (Exception e) { + actual = e.getClass(); + } + if (actual != expected) { + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + throw new RuntimeException("Test failed"); } } - private static void testKernel(int width, int height, float[] data) { - System.out.println("Testing for width: " + width + ", height: " - + height + ", data: " + (data == null ? "null" : "not null")); - expectIllegalArgumentException(() -> new Kernel(width, height, data)); + private static void testIAE(int width, int height, int len) { + test(width, height, new float[len], IllegalArgumentException.class); + } + + private static void testNPE(int width, int height) { + test(width, height, null, NullPointerException.class); } public static void main(String[] args) { - testKernel(-1, 1, new float[100]); - testKernel(1, -1, new float[100]); - testKernel(-1, -1, new float[100]); - testKernel(1, 1, null); - - int width = 50; - int height = Integer.MAX_VALUE; - testKernel(width, height, new float[100]); + int[][] sizes = {{-1, 1}, {1, -1}, {-1, -1}, {50, Integer.MAX_VALUE}}; + int[] lens = {1, 100}; + for (int[] kernelSize : sizes) { + for (int len : lens) { + testIAE(kernelSize[0], kernelSize[1], len); + } + testNPE(kernelSize[0], kernelSize[1]); + } + testNPE(10, 10); // NPE on valid width and height + testIAE(10, 10, 10); // IAE on valid width and height but small data } } diff --git a/test/jdk/java/awt/image/DrawImage/TiledImage.java b/test/jdk/java/awt/image/DrawImage/TiledImage.java index bd64edc37fd..e64267998da 100644 --- a/test/jdk/java/awt/image/DrawImage/TiledImage.java +++ b/test/jdk/java/awt/image/DrawImage/TiledImage.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 diff --git a/test/jdk/java/awt/image/SampleModelGetSamplesAndPixelsTest.java b/test/jdk/java/awt/image/SampleModelGetSamplesAndPixelsTest.java new file mode 100644 index 00000000000..483bbe43d9e --- /dev/null +++ b/test/jdk/java/awt/image/SampleModelGetSamplesAndPixelsTest.java @@ -0,0 +1,337 @@ +/* + * 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 6185110 + * @summary Verify get/set/Pixels/Samples APIs for bad parameters. + * + * @run main SampleModelGetSamplesAndPixelsTest + */ + +import java.awt.image.BandedSampleModel; +import java.awt.image.ComponentSampleModel; +import java.awt.image.DataBuffer; +import java.awt.image.MultiPixelPackedSampleModel; +import java.awt.image.PixelInterleavedSampleModel; +import java.awt.image.SampleModel; +import java.awt.image.SinglePixelPackedSampleModel; +import java.util.Vector; + +public class SampleModelGetSamplesAndPixelsTest { + + static final int WIDTH = 100; + static final int HEIGHT = 100; + static final int DATATYPE = DataBuffer.TYPE_BYTE; + static final int NUMBANDS = 4; + static final int[] INTS = new int[WIDTH * HEIGHT + NUMBANDS]; + static final float[] FLOATS = new float[WIDTH * HEIGHT + NUMBANDS]; + static final double[] DOUBLES = new double[WIDTH * HEIGHT + NUMBANDS]; + static final int[][] COORDS = { + { 1, 1, 1, 1, -1 }, // bad band + { 1, 1, 1, 1, NUMBANDS }, // bad band + { 1, 1, -1, 1, 0 }, // negative w + { 1, 1, -1, -1, 0 }, // negative w and h + { -4, 1, 1, 1, 0 }, // negative x + { -4, -4, 1, 1, 0 }, // negative x and y + { WIDTH+10, 0, 1, 1, 0 }, // x > width + { 0, HEIGHT+10, 1, 1, 0 }, // y > height + { WIDTH+10, HEIGHT+10, 1, 1, 0 }, // both x > width and y > height + }; + + public static void main(String[] args) { + Vector> classes = new Vector>(); + + classes.add(ComponentSampleModel.class); + classes.add(MultiPixelPackedSampleModel.class); + classes.add(SinglePixelPackedSampleModel.class); + classes.add(BandedSampleModel.class); + classes.add(PixelInterleavedSampleModel.class); + + for (Class c : classes) { + doTest(c); + } + } + + static void noException(SampleModel sm) { + System.err.println(sm); + throw new RuntimeException("No expected exception"); + } + + private static void doTest(Class c) { + System.out.println("Test for: " + c.getName()); + SampleModel sm = createSampleModel(c); + doTestNull(sm); + for (int i = 0; i < COORDS.length; i++) { + int x = COORDS[i][0]; + int y = COORDS[i][1]; + int w = COORDS[i][2]; + int h = COORDS[i][3]; + int b = COORDS[i][4]; + doTest(sm, x, y, w, h, b); + } + } + + private static void doTestNull(SampleModel sm) { + doTestNull(sm, INTS); + doTestNull(sm, FLOATS); + doTestNull(sm, DOUBLES); + } + + private static void doTestNull(SampleModel sm, int[] INTS) { + try { + sm.getSamples(1, 1, 1, 1, 0, INTS, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + + try { + sm.getSamples(1, 1, 1, 1, 0, INTS, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + + try { + sm.getPixels(1, 1, 1, 1, INTS, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + + try { + sm.setPixels(1, 1, 1, 1, INTS, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + } + + private static void doTestNull(SampleModel sm, float[] FLOATS) { + try { + sm.getSamples(1, 1, 1, 1, 0, FLOATS, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + + try { + sm.getSamples(1, 1, 1, 1, 0, FLOATS, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + + try { + sm.getPixels(1, 1, 1, 1, FLOATS, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + + try { + sm.setPixels(1, 1, 1, 1, FLOATS, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + } + + private static void doTestNull(SampleModel sm, double[] DOUBLES) { + try { + sm.getSamples(1, 1, 1, 1, 0, DOUBLES, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + + try { + sm.getSamples(1, 1, 1, 1, 0, DOUBLES, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + + try { + sm.getPixels(1, 1, 1, 1, DOUBLES, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + + try { + sm.setPixels(1, 1, 1, 1, DOUBLES, null); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + } + + private static void doTest(SampleModel sm, int x, int y, int w, int h, int b) { + doTest(sm, x, y, w, h, b, INTS); + doTest(sm, x, y, w, h, b, FLOATS); + doTest(sm, x, y, w, h, b, DOUBLES); + } + + private static void doTest(SampleModel sm, int x, int y, int w, int h, int b, int[] INTS) { + + // Now test each API with a non-null buffer and the specified values. + DataBuffer db = sm.createDataBuffer(); + + try { + sm.getSamples(x, y, w, h, b, INTS, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + + try { + sm.setSamples(x, y, w, h, b, INTS, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + + if (b < 0 || b >= NUMBANDS) { + return; // Values were to test illegal bands, skip the rest. + } + + try { + sm.getPixels(x, y, w, h, INTS, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + + try { + sm.setPixels(x, y, w, h, INTS, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + } + + private static void doTest(SampleModel sm, int x, int y, int w, int h, int b, float[] FLOATS) { + + // Now test each API with a non-null buffer and the specified values. + DataBuffer db = sm.createDataBuffer(); + + try { + sm.getSamples(x, y, w, h, b, FLOATS, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + + try { + sm.setSamples(x, y, w, h, b, FLOATS, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + + if (b < 0 || b >= NUMBANDS) { + return; // Values were to test illegal bands, skip the rest. + } + + try { + sm.getPixels(x, y, w, h, FLOATS, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + + try { + sm.setPixels(x, y, w, h, FLOATS, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + } + + private static void doTest(SampleModel sm, int x, int y, int w, int h, int b, double[] DOUBLES) { + + // Now test each API with a non-null buffer and the specified values. + DataBuffer db = sm.createDataBuffer(); + + try { + sm.getSamples(x, y, w, h, b, DOUBLES, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + + try { + sm.setSamples(x, y, w, h, b, DOUBLES, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + + if (b < 0 || b >= NUMBANDS) { + return; // Values were to test illegal bands, skip the rest. + } + + try { + sm.getPixels(x, y, w, h, DOUBLES, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + + try { + sm.setPixels(x, y, w, h, DOUBLES, db); + noException(sm); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + } + + try { + sm.setDataElements(0, 0, null, db); + noException(sm); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + } + + private static SampleModel createSampleModel(Class cls) { + SampleModel res = null; + + if (cls == ComponentSampleModel.class) { + res = new ComponentSampleModel(DATATYPE, WIDTH, HEIGHT, 4, WIDTH * 4, new int[] { 0, 1, 2, 3 } ); + } else if (cls == MultiPixelPackedSampleModel.class) { + res = new MultiPixelPackedSampleModel(DATATYPE, WIDTH, HEIGHT, 4); + } else if (cls == SinglePixelPackedSampleModel.class) { + res = new SinglePixelPackedSampleModel(DATATYPE, WIDTH, HEIGHT, + new int[]{ 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff }); + } else if (cls == BandedSampleModel.class) { + res = new BandedSampleModel(DATATYPE, WIDTH, HEIGHT, NUMBANDS); + } else if (cls == PixelInterleavedSampleModel.class) { + res = new PixelInterleavedSampleModel(DATATYPE, WIDTH, HEIGHT, 4, WIDTH * 4, new int[] { 0, 1, 2, 3 }); + } else { + throw new RuntimeException("Unknown class " + cls); + } + return res; + } +} diff --git a/test/jdk/java/awt/image/XBMDecoder/XBMDecoderTest.java b/test/jdk/java/awt/image/XBMDecoder/XBMDecoderTest.java index 19bc6d95c39..9694043d1bb 100644 --- a/test/jdk/java/awt/image/XBMDecoder/XBMDecoderTest.java +++ b/test/jdk/java/awt/image/XBMDecoder/XBMDecoderTest.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 @@ -29,10 +29,14 @@ * @run main XBMDecoderTest */ +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.PrintStream; +import java.util.Arrays; import javax.swing.ImageIcon; public class XBMDecoderTest { @@ -57,21 +61,39 @@ public class XBMDecoderTest { ImageIcon icon = new ImageIcon(fis.readAllBytes()); boolean isErrEmpty = errContent.toString().isEmpty(); + if (!isErrEmpty) { System.out.println("Expected ImageFormatException occurred."); System.out.print(errContent); } - if (validCase && !isErrEmpty) { throw new RuntimeException("Test failed: Error stream not empty"); - } else if (!validCase && isErrEmpty) { + } else if (!validCase && isErrEmpty && hasPixelData(icon.getImage())) { throw new RuntimeException("Test failed: ImageFormatException" + " expected but not thrown"); } + if (validCase && !hasPixelData(icon.getImage())) { + throw new RuntimeException("Test failed: the parsed image " + + "does not contain any pixel data"); + } System.out.println("PASSED\n"); } finally { System.setErr(originalErr); } } } + + private static boolean hasPixelData(Image img) { + int w = img.getWidth(null); + int h = img.getHeight(null); + BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = bi.createGraphics(); + g.drawImage(img, 0, 0, null); + g.dispose(); + int[] pixels = bi.getRGB(0, 0, w, h, null, 0, w); + if (Arrays.stream(pixels).allMatch(i -> i == 0)) { + return false; + } + return true; + } } diff --git a/test/jdk/java/awt/image/XBMDecoder/invalid_empty.xbm b/test/jdk/java/awt/image/XBMDecoder/invalid_empty.xbm new file mode 100644 index 00000000000..5cfb8e21cf8 --- /dev/null +++ b/test/jdk/java/awt/image/XBMDecoder/invalid_empty.xbm @@ -0,0 +1,6 @@ +#define test_width 16 +#define test_height 3 +#define ht_x 1 +#define ht_y 2 +static unsigned char test_bits[] = { +}; diff --git a/test/jdk/java/awt/image/XBMDecoder/invalid_hex.xbm b/test/jdk/java/awt/image/XBMDecoder/invalid_hex.xbm index c6f819582d0..1286eee1d9b 100644 --- a/test/jdk/java/awt/image/XBMDecoder/invalid_hex.xbm +++ b/test/jdk/java/awt/image/XBMDecoder/invalid_hex.xbm @@ -1,3 +1,3 @@ -#define k_wt 16 -#define k_ht 1 +#define k_width 16 +#define k_height 1 k[] = { 0x10, 1234567890}; diff --git a/test/jdk/java/awt/image/XBMDecoder/invalid_plus.xbm b/test/jdk/java/awt/image/XBMDecoder/invalid_plus.xbm new file mode 100644 index 00000000000..714907084f2 --- /dev/null +++ b/test/jdk/java/awt/image/XBMDecoder/invalid_plus.xbm @@ -0,0 +1,3 @@ +#define test_width 16 +#define test_height 2 +static unsigned char test_bits[] = { 0x13, 0x11, 0xAB+, 0xff }; \ No newline at end of file diff --git a/test/jdk/java/awt/image/XBMDecoder/valid_multiline.xbm b/test/jdk/java/awt/image/XBMDecoder/valid_multiline.xbm new file mode 100644 index 00000000000..e24bc10e9b0 --- /dev/null +++ b/test/jdk/java/awt/image/XBMDecoder/valid_multiline.xbm @@ -0,0 +1,8 @@ +#define test_width 16 +#define test_height 3 +#define ht_x 1 +#define ht_y 2 +static unsigned char test_bits[] = { +0x20, 0x10, +0x25, 0x01, +0xAC, 0xab }; diff --git a/test/jdk/java/awt/print/Dialog/DialogOrient.java b/test/jdk/java/awt/print/Dialog/DialogOrient.java index b89f3950e99..99bc9b84d94 100644 --- a/test/jdk/java/awt/print/Dialog/DialogOrient.java +++ b/test/jdk/java/awt/print/Dialog/DialogOrient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/awt/print/PrinterJob/PageDialogTest.java b/test/jdk/java/awt/print/PrinterJob/PageDialogTest.java index ed02c64b48e..9c71df3afe3 100644 --- a/test/jdk/java/awt/print/PrinterJob/PageDialogTest.java +++ b/test/jdk/java/awt/print/PrinterJob/PageDialogTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/awt/print/PrinterJob/PrintDialog.java b/test/jdk/java/awt/print/PrinterJob/PrintDialog.java index 395312aaa45..c9bed3aab4d 100644 --- a/test/jdk/java/awt/print/PrinterJob/PrintDialog.java +++ b/test/jdk/java/awt/print/PrinterJob/PrintDialog.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/awt/print/PrinterJob/PrintDialogCancel.java b/test/jdk/java/awt/print/PrinterJob/PrintDialogCancel.java index 9a1884a5f54..96a13787468 100644 --- a/test/jdk/java/awt/print/PrinterJob/PrintDialogCancel.java +++ b/test/jdk/java/awt/print/PrinterJob/PrintDialogCancel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/awt/print/PrinterJob/PrintTextTest.java b/test/jdk/java/awt/print/PrinterJob/PrintTextTest.java index 06e71c4067f..defca807fc0 100644 --- a/test/jdk/java/awt/print/PrinterJob/PrintTextTest.java +++ b/test/jdk/java/awt/print/PrinterJob/PrintTextTest.java @@ -23,7 +23,7 @@ /* * @test - * @bug 6425068 7156751 7157659 8029204 8132890 8148334 8344637 + * @bug 6425068 7156751 7157659 8029204 8132890 8148334 8344637 8368702 * @key printer * @summary Confirm that text prints where we expect to the length we expect. * @library /java/awt/regtesthelpers diff --git a/test/jdk/java/awt/print/PrinterJob/ThinLines.java b/test/jdk/java/awt/print/PrinterJob/ThinLines.java index 95cbfed8796..9ad47f08bc4 100644 --- a/test/jdk/java/awt/print/PrinterJob/ThinLines.java +++ b/test/jdk/java/awt/print/PrinterJob/ThinLines.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/awt/print/RemotePrinterStatusRefresh/RemotePrinterStatusRefresh.java b/test/jdk/java/awt/print/RemotePrinterStatusRefresh/RemotePrinterStatusRefresh.java index 33fe9fc86d3..7aaedb6e5a1 100644 --- a/test/jdk/java/awt/print/RemotePrinterStatusRefresh/RemotePrinterStatusRefresh.java +++ b/test/jdk/java/awt/print/RemotePrinterStatusRefresh/RemotePrinterStatusRefresh.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 diff --git a/test/jdk/java/awt/regtesthelpers/AbstractTest.java b/test/jdk/java/awt/regtesthelpers/AbstractTest.java index fbf66e45e3b..8c66f1ccf3c 100644 --- a/test/jdk/java/awt/regtesthelpers/AbstractTest.java +++ b/test/jdk/java/awt/regtesthelpers/AbstractTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/awt/regtesthelpers/Util.java b/test/jdk/java/awt/regtesthelpers/Util.java index 45d9c89ee46..fd0e708a3ac 100644 --- a/test/jdk/java/awt/regtesthelpers/Util.java +++ b/test/jdk/java/awt/regtesthelpers/Util.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 diff --git a/test/jdk/java/awt/regtesthelpers/process/ProcessCommunicator.java b/test/jdk/java/awt/regtesthelpers/process/ProcessCommunicator.java index 3b173009d23..bca89f019d4 100644 --- a/test/jdk/java/awt/regtesthelpers/process/ProcessCommunicator.java +++ b/test/jdk/java/awt/regtesthelpers/process/ProcessCommunicator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 diff --git a/test/jdk/java/beans/Introspector/4520754/Test4520754.java b/test/jdk/java/beans/Introspector/4520754/Test4520754.java index 3ad890c57db..fd2417767c4 100644 --- a/test/jdk/java/beans/Introspector/4520754/Test4520754.java +++ b/test/jdk/java/beans/Introspector/4520754/Test4520754.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 diff --git a/test/jdk/java/beans/Performance/TestIntrospector.java b/test/jdk/java/beans/Performance/TestIntrospector.java index 749a6de5b4c..6e10af45c0b 100644 --- a/test/jdk/java/beans/Performance/TestIntrospector.java +++ b/test/jdk/java/beans/Performance/TestIntrospector.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 diff --git a/test/jdk/java/beans/PropertyChangeSupport/Test4682386.java b/test/jdk/java/beans/PropertyChangeSupport/Test4682386.java index 72a7c0b5084..19666cebf61 100644 --- a/test/jdk/java/beans/PropertyChangeSupport/Test4682386.java +++ b/test/jdk/java/beans/PropertyChangeSupport/Test4682386.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 diff --git a/test/jdk/java/foreign/TestMemoryAlignment.java b/test/jdk/java/foreign/TestMemoryAlignment.java index a73635c8f08..10916b731d5 100644 --- a/test/jdk/java/foreign/TestMemoryAlignment.java +++ b/test/jdk/java/foreign/TestMemoryAlignment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 diff --git a/test/jdk/java/foreign/TestSegments.java b/test/jdk/java/foreign/TestSegments.java index 2942b388d50..e9f3e8a87cc 100644 --- a/test/jdk/java/foreign/TestSegments.java +++ b/test/jdk/java/foreign/TestSegments.java @@ -212,14 +212,32 @@ public class TestSegments { } @Test - public void testSegmentOOBMessage() { + public void testSegmentAccessOOBMessage() { try { var segment = Arena.global().allocate(10, 1); segment.getAtIndex(ValueLayout.JAVA_INT, 2); + fail("Expected IndexOutOfBoundsException was not thrown"); } catch (IndexOutOfBoundsException ex) { - assertTrue(ex.getMessage().contains("Out of bound access")); - assertTrue(ex.getMessage().contains("offset = 8")); - assertTrue(ex.getMessage().contains("length = 4")); + assertTrue(ex.getMessage().startsWith("Out of bound access")); + assertTrue(ex.getMessage().endsWith("attempting to access an element of length 4 at offset 8 " + + "which is outside the valid range 0 <= offset+length < byteSize (=10)")); + } catch (Exception ex) { + fail("Unexpected exception type thrown: " + ex); + } + } + + @Test + public void testSegmentSliceOOBMessage() { + try { + var segment = Arena.global().allocate(10, 1); + var slice = segment.asSlice(8, 4); + fail("Expected IndexOutOfBoundsException was not thrown"); + } catch (IndexOutOfBoundsException ex) { + assertTrue(ex.getMessage().startsWith("Out of bound access")); + assertTrue(ex.getMessage().endsWith("attempting to get slice of length 4 at offset 8 " + + "which is outside the valid range 0 <= offset+length < byteSize (=10)")); + } catch (Exception ex) { + fail("Unexpected exception type thrown: " + ex); } } diff --git a/test/jdk/java/foreign/TestStringEncoding.java b/test/jdk/java/foreign/TestStringEncoding.java index 94732943b9d..e9e47420a68 100644 --- a/test/jdk/java/foreign/TestStringEncoding.java +++ b/test/jdk/java/foreign/TestStringEncoding.java @@ -37,6 +37,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; +import java.util.Set; import java.util.function.UnaryOperator; import jdk.internal.foreign.AbstractMemorySegmentImpl; @@ -102,6 +103,140 @@ public class TestStringEncoding { } } + @Test(dataProvider = "strings") + public void testStringsLength(String testString) { + if (!testString.isEmpty()) { + for (Charset charset : Charset.availableCharsets().values()) { + if (charset.canEncode()) { + for (Arena arena : arenas()) { + try (arena) { + MemorySegment text = arena.allocateFrom(testString, charset, 0, testString.length()); + long length = text.byteSize(); + assertEquals(length, testString.getBytes(charset).length); + String roundTrip = text.getString(0, charset, length); + if (charset.newEncoder().canEncode(testString)) { + assertEquals(roundTrip, testString); + } + } + } + } + } + } + } + + @Test(dataProvider = "strings") + public void testStringsCopy(String testString) { + if (!testString.isEmpty()) { + for (Charset charset : Charset.availableCharsets().values()) { + if (charset.canEncode()) { + for (Arena arena : arenas()) { + try (arena) { + byte[] bytes = testString.getBytes(charset); + MemorySegment text = arena.allocate(JAVA_BYTE, bytes.length); + MemorySegment.copy(testString, charset, 0, text, 0, testString.length()); + String roundTrip = text.getString(0, charset, bytes.length); + if (charset.newEncoder().canEncode(testString)) { + assertEquals(roundTrip, testString); + } + } + } + } + } + } + } + + @Test + public void testStringsLengthNegative() { + try (Arena arena = Arena.ofConfined()) { + var segment = arena.allocateFrom("abc"); + assertThrows(IllegalArgumentException.class, () -> segment.getString(1, StandardCharsets.UTF_8, -1)); + } + } + + @Test + public void testCopyThrows() { + try (Arena arena = Arena.ofConfined()) { + String testString = "abc"; + String testString_notBytesCompatible = "snowman \u26C4"; + MemorySegment text = arena.allocate(JAVA_BYTE, 3); + MemorySegment text_notBytesCompatible = arena.allocate(JAVA_BYTE, + testString_notBytesCompatible.getBytes(StandardCharsets.UTF_8).length); + MemorySegment.copy(testString, StandardCharsets.UTF_8, 0, text, 0, testString.length()); + MemorySegment.copy(testString_notBytesCompatible, StandardCharsets.UTF_8, 0, + text_notBytesCompatible, 0, + testString_notBytesCompatible.length()); + // srcIndex < 0 + assertThrows(IndexOutOfBoundsException.class, () -> + MemorySegment.copy(testString, StandardCharsets.UTF_8, -1, text, 0, testString.length())); + // dstOffset < 0 + assertThrows(IndexOutOfBoundsException.class, () -> + MemorySegment.copy(testString, StandardCharsets.UTF_8, 0, text, -1, testString.length())); + // numChars < 0 + assertThrows(IndexOutOfBoundsException.class, () -> + MemorySegment.copy(testString, StandardCharsets.UTF_8, 0, text, 0, -1)); + // srcIndex + numChars > length + assertThrows(IndexOutOfBoundsException.class, () -> + MemorySegment.copy(testString, StandardCharsets.UTF_8, 1, text, 0, testString.length())); + assertThrows(IndexOutOfBoundsException.class, () -> + MemorySegment.copy(testString, StandardCharsets.UTF_8, 0, text, 0, testString.length() + 1)); + // dstOffset > byteSize() - B + assertThrows(IndexOutOfBoundsException.class, () -> + MemorySegment.copy(testString, StandardCharsets.UTF_8, 0, text, 1, testString.length())); + // srcIndex + numChars overflows + assertThrows(IndexOutOfBoundsException.class, () -> + MemorySegment.copy(testString, StandardCharsets.UTF_8, Integer.MAX_VALUE, text, 0, Integer.MAX_VALUE + 3)); + assertThrows(IndexOutOfBoundsException.class, () -> + MemorySegment.copy(testString_notBytesCompatible, StandardCharsets.UTF_8, Integer.MAX_VALUE, text, 0, Integer.MAX_VALUE + 3)); + } + } + + @Test + public void testAllocateFromThrows() { + try (Arena arena = Arena.ofConfined()) { + String testString = "abc"; + String testString_notBytesCompatible = "snowman \u26C4"; + arena.allocateFrom(testString, StandardCharsets.UTF_8, 0, testString.length()); + arena.allocateFrom(testString, StandardCharsets.UTF_8, 2, 1); + // srcIndex < 0 + assertThrows(IndexOutOfBoundsException.class, () -> + arena.allocateFrom(testString, StandardCharsets.UTF_8, -1, testString.length())); + // numChars < 0 + assertThrows(IndexOutOfBoundsException.class, () -> + arena.allocateFrom(testString, StandardCharsets.UTF_8, 0, -1)); + // srcIndex + numChars > length + assertThrows(IndexOutOfBoundsException.class, () -> + arena.allocateFrom(testString, StandardCharsets.UTF_8, 0, testString.length() + 1)); + assertThrows(IndexOutOfBoundsException.class, () -> + arena.allocateFrom(testString, StandardCharsets.UTF_8, 1, testString.length())); + // srcIndex + numChars overflows + assertThrows(IndexOutOfBoundsException.class, () -> + arena.allocateFrom(testString, StandardCharsets.UTF_8, 3, Integer.MAX_VALUE)); + assertThrows(IndexOutOfBoundsException.class, () -> arena.allocateFrom( + testString_notBytesCompatible, StandardCharsets.UTF_8, 3, Integer.MAX_VALUE)); + } + } + + @Test + public void testGetStringThrows() { + try (Arena arena = Arena.ofConfined()) { + String testString = "abc"; + MemorySegment text = arena.allocateFrom(testString, StandardCharsets.UTF_8, 0, testString.length()); + text.getString(0, StandardCharsets.UTF_8, 3); + // unsupported string size + assertThrows(IllegalArgumentException.class, () -> + text.getString(0, StandardCharsets.UTF_8, Integer.MAX_VALUE + 1L)); + // offset < 0 + assertThrows(IndexOutOfBoundsException.class, () -> + text.getString(-1, StandardCharsets.UTF_8, 3)); + // offset > byteSize() - length + assertThrows(IndexOutOfBoundsException.class, () -> + text.getString(1, StandardCharsets.UTF_8, 3)); + // length < 0 + assertThrows(IllegalArgumentException.class, () -> + text.getString(0, StandardCharsets.UTF_8, -1)); + } + } + @Test(dataProvider = "strings") public void testStringsHeap(String testString) { for (Charset charset : singleByteCharsets()) { @@ -221,6 +356,74 @@ public class TestStringEncoding { } } + @Test(dataProvider = "strings") + public void testSubstringGetString(String testString) { + if (testString.length() < 3 || !containsOnlyRegularCharacters(testString)) { + return; + } + for (var charset : singleByteCharsets()) { + for (var arena: arenas()) { + try (arena) { + MemorySegment text = arena.allocateFrom(testString, charset, 0, testString.length()); + for (int srcIndex = 0; srcIndex <= testString.length(); srcIndex++) { + for (int numChars = 0; numChars <= testString.length() - srcIndex; numChars++) { + // this test assumes single-byte charsets + String roundTrip = text.getString(srcIndex, charset, numChars); + String substring = testString.substring(srcIndex, srcIndex + numChars); + assertEquals(roundTrip, substring); + } + } + } + } + } + } + + @Test(dataProvider = "strings") + public void testSubstringAllocate(String testString) { + if (testString.length() < 3 || !containsOnlyRegularCharacters(testString)) { + return; + } + for (var charset : singleByteCharsets()) { + for (var arena: arenas()) { + try (arena) { + for (int srcIndex = 0; srcIndex <= testString.length(); srcIndex++) { + for (int numChars = 0; numChars <= testString.length() - srcIndex; numChars++) { + MemorySegment text = arena.allocateFrom(testString, charset, srcIndex, numChars); + String substring = testString.substring(srcIndex, srcIndex + numChars); + assertEquals(text.byteSize(), substring.getBytes(charset).length); + String roundTrip = text.getString(0, charset, text.byteSize()); + assertEquals(roundTrip, substring); + } + } + } + } + } + } + + @Test(dataProvider = "strings") + public void testSubstringCopy(String testString) { + if (testString.length() < 3 || !containsOnlyRegularCharacters(testString)) { + return; + } + for (var charset : singleByteCharsets()) { + for (var arena: arenas()) { + try (arena) { + for (int srcIndex = 0; srcIndex <= testString.length(); srcIndex++) { + for (int numChars = 0; numChars <= testString.length() - srcIndex; numChars++) { + String substring = testString.substring(srcIndex, srcIndex + numChars); + long length = substring.getBytes(charset).length; + MemorySegment text = arena.allocate(JAVA_BYTE, length); + long copied = MemorySegment.copy(testString, charset, srcIndex, text, 0, numChars); + String roundTrip = text.getString(0, charset, length); + assertEquals(roundTrip, substring); + assertEquals(copied, length); + } + } + } + } + } + } + private static final MemoryLayout CHAR_POINTER = ADDRESS .withTargetLayout(MemoryLayout.sequenceLayout(Long.MAX_VALUE, JAVA_BYTE)); private static final Linker LINKER = Linker.nativeLinker(); @@ -402,7 +605,7 @@ public class TestStringEncoding { {""}, {"X"}, {"12345"}, - {"yen \u00A5"}, + {"section \u00A7"}, {"snowman \u26C4"}, {"rainbow \uD83C\uDF08"}, {"0"}, diff --git a/test/jdk/java/foreign/TestUpcallStructScope.java b/test/jdk/java/foreign/TestUpcallStructScope.java index d9729cb8f3b..b71156d9e52 100644 --- a/test/jdk/java/foreign/TestUpcallStructScope.java +++ b/test/jdk/java/foreign/TestUpcallStructScope.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 diff --git a/test/jdk/java/foreign/libTest4BAlignedDouble.c b/test/jdk/java/foreign/libTest4BAlignedDouble.c index c79280ed421..89d6216564d 100644 --- a/test/jdk/java/foreign/libTest4BAlignedDouble.c +++ b/test/jdk/java/foreign/libTest4BAlignedDouble.c @@ -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. * Copyright (c) 2024 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/test/jdk/java/foreign/libTestUpcallStructScope.c b/test/jdk/java/foreign/libTestUpcallStructScope.c index e18543d5b1a..4dba9664ae3 100644 --- a/test/jdk/java/foreign/libTestUpcallStructScope.c +++ b/test/jdk/java/foreign/libTestUpcallStructScope.c @@ -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 diff --git a/test/jdk/java/foreign/sharedclosejvmti/TestSharedCloseJvmti.java b/test/jdk/java/foreign/sharedclosejvmti/TestSharedCloseJvmti.java index b2bfdd18b50..9fba092744e 100644 --- a/test/jdk/java/foreign/sharedclosejvmti/TestSharedCloseJvmti.java +++ b/test/jdk/java/foreign/sharedclosejvmti/TestSharedCloseJvmti.java @@ -81,7 +81,9 @@ public class TestSharedCloseJvmti { // run in separate thread so that waiting on // latch doesn't block main thread Thread.ofPlatform().name("Trigger").start(() -> { - SINK = segment.get(ValueLayout.JAVA_INT, 0); + SINK = segment.get(ValueLayout.JAVA_INT, 0); // should throw + System.err.println("No exception thrown during outer memory access"); + System.exit(1); }); // wait until trigger thread is in JVMTI event callback MAIN_LATCH.await(); @@ -107,7 +109,9 @@ public class TestSharedCloseJvmti { } else { reentrant = true; try (Arena arena = Arena.ofConfined()) { - SINK = arena.allocate(4).get(ValueLayout.JAVA_INT, 0); + SINK = arena.allocate(4).get(ValueLayout.JAVA_INT, 0); // should throw + System.err.println("No exception thrown during reentrant memory access"); + System.exit(1); } reentrant = false; } diff --git a/test/jdk/java/foreign/sharedclosejvmti/libSharedCloseAgent.cpp b/test/jdk/java/foreign/sharedclosejvmti/libSharedCloseAgent.cpp index a82818e0280..c5626ee78fa 100644 --- a/test/jdk/java/foreign/sharedclosejvmti/libSharedCloseAgent.cpp +++ b/test/jdk/java/foreign/sharedclosejvmti/libSharedCloseAgent.cpp @@ -23,10 +23,12 @@ #include -#include +#include +#include static jclass MAIN_CLS; static jmethodID TARGET_ID; +static jclass EXCEPTION_CLS; static const char* TARGET_CLASS_NAME = "TestSharedCloseJvmti$EventDuringScopedAccessRunner"; static const char* TARGET_METHOD_NAME = "target"; @@ -35,6 +37,8 @@ static const char* TARGET_METHOD_SIG = "()V"; static const char* INTERCEPT_CLASS_NAME = "Ljdk/internal/foreign/MemorySessionImpl;"; static const char* INTERCEPT_METHOD_NAME = "checkValidStateRaw"; +static const char* EXCEPTION_CLASS_NAME = "Ljdk/internal/misc/ScopedMemoryAccess$ScopedAccessError;"; + void start(jvmtiEnv*, JNIEnv* jni_env, jthread) { jclass cls = jni_env->FindClass(TARGET_CLASS_NAME); @@ -50,6 +54,14 @@ void start(jvmtiEnv*, JNIEnv* jni_env, jthread) { jni_env->ExceptionDescribe(); return; } + + jclass ex_cls = jni_env->FindClass(EXCEPTION_CLASS_NAME); + if (ex_cls == nullptr) { + jni_env->ExceptionDescribe(); + return; + } + + EXCEPTION_CLS = (jclass) jni_env->NewGlobalRef(ex_cls); } void method_exit(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread, jmethodID method, @@ -60,38 +72,44 @@ void method_exit(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread, jmethodID return; } - if (strcmp(method_name, INTERCEPT_METHOD_NAME) != 0) { - jvmti_env->Deallocate((unsigned char*) method_name); + bool is_intercept_method = strcmp(method_name, INTERCEPT_METHOD_NAME) == 0; + jvmti_env->Deallocate((unsigned char*) method_name); + if (!is_intercept_method) { return; } jclass cls; err = jvmti_env->GetMethodDeclaringClass(method, &cls); if (err != JVMTI_ERROR_NONE) { - jvmti_env->Deallocate((unsigned char*) method_name); return; } char* class_sig = nullptr; err = jvmti_env->GetClassSignature(cls, &class_sig, nullptr); if (err != JVMTI_ERROR_NONE) { - jvmti_env->Deallocate((unsigned char*) method_name); return; } - if (strcmp(class_sig, INTERCEPT_CLASS_NAME) != 0) { - jvmti_env->Deallocate((unsigned char*) method_name); - jvmti_env->Deallocate((unsigned char*) class_sig); + bool is_intercept_class = strcmp(class_sig, INTERCEPT_CLASS_NAME) == 0; + jvmti_env->Deallocate((unsigned char*) class_sig); + if (!is_intercept_class) { return; } jni_env->CallStaticVoidMethod(MAIN_CLS, TARGET_ID); - if (jni_env->ExceptionOccurred()) { + jthrowable ex = jni_env->ExceptionOccurred(); + if (ex != nullptr) { + // we can not return with a pending exception from this JMVTI callback, + // and there is no way to propagate it to the caller so that the memory + // access will be interrupted. + // We log the exception for testing purposes end then terminate the process. jni_env->ExceptionDescribe(); + if (jni_env->IsInstanceOf(ex, EXCEPTION_CLS)) { + exit(0); // success + } + // else, another exception was thrown. Let the java logic handle the lack of + // ScopedAccessError } - - jvmti_env->Deallocate((unsigned char*) method_name); - jvmti_env->Deallocate((unsigned char*) class_sig); } JNIEXPORT jint JNICALL @@ -102,7 +120,8 @@ Agent_OnLoad(JavaVM *vm, char *options, void *reserved) { return jni_err; } - jvmtiCapabilities capabilities{}; + jvmtiCapabilities capabilities; + memset(&capabilities, 0, sizeof(jvmtiCapabilities)); capabilities.can_generate_method_exit_events = 1; jvmtiError err = env->AddCapabilities(&capabilities); diff --git a/test/jdk/java/io/File/GetXSpace.java b/test/jdk/java/io/File/GetXSpace.java index e61880edb2c..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,18 +102,13 @@ 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"); - } + if (Platform.isWindows() && isCDDrive(name)) { + getCDDriveSpace(name, sizes); } else { - if (getSpace0(name, sizes)) + if (getSpace(name, sizes)) System.err.println("WARNING: total space is estimated"); } this.size = sizes[0]; @@ -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(); @@ -184,7 +178,7 @@ public class GetXSpace { out.format("%s (%d):%n", s.name(), s.size()); String fmt = " %-4s total = %12d free = %12d usable = %12d%n"; - String method = Platform.isWindows() & isCDDrive(s.name()) ? "getCDDriveSpace" : "getSpace0"; + String method = Platform.isWindows() && isCDDrive(s.name()) ? "getCDDriveSpace" : "getSpace"; out.format(fmt, method, s.total(), s.free(), s.available()); out.format(fmt, "getXSpace", ts, fs, us); @@ -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 getSpace0 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,10 +414,23 @@ 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) + throws IOException { + try { + return getSpace0(root, space); + } catch (IOException e) { + File f = new File(root); + System.err.printf("getSpace0 failed for %s (%s, %s)%n", + root, f.exists(), f.canRead()); + throw e; + } + } + private static void getCDDriveSpace(String root, long[] sizes) throws IOException { String[] cmd = new String[] {"df", "-k", "-P", root}; diff --git a/test/jdk/java/io/File/libGetXSpace.c b/test/jdk/java/io/File/libGetXSpace.c index c45aea14691..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, 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 @@ -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/io/Serializable/records/AbsentStreamValuesTest.java b/test/jdk/java/io/Serializable/records/AbsentStreamValuesTest.java index 0f72b9f8f67..02cb35601a9 100644 --- a/test/jdk/java/io/Serializable/records/AbsentStreamValuesTest.java +++ b/test/jdk/java/io/Serializable/records/AbsentStreamValuesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -25,7 +25,7 @@ * @test * @bug 8246774 * @summary Checks that the appropriate default value is given to the canonical ctr - * @run testng AbsentStreamValuesTest + * @run junit AbsentStreamValuesTest */ import java.io.ByteArrayInputStream; @@ -34,16 +34,20 @@ import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.io.ObjectStreamConstants.*; import static java.lang.System.out; -import static org.testng.Assert.*; + +import static 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; /** * Basic test to check that default primitive / reference values are presented * to the record's canonical constructor, for fields not in the stream. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class AbsentStreamValuesTest { record R01(boolean x) implements Serializable { } @@ -61,7 +65,6 @@ public class AbsentStreamValuesTest { record R13(R12 x) implements Serializable { } record R14(R13[] x) implements Serializable { } - @DataProvider(name = "recordTypeAndExpectedValue") public Object[][] recordTypeAndExpectedValue() { return new Object[][] { new Object[] { R01.class, false }, @@ -81,7 +84,8 @@ public class AbsentStreamValuesTest { }; } - @Test(dataProvider = "recordTypeAndExpectedValue") + @ParameterizedTest + @MethodSource("recordTypeAndExpectedValue") public void testWithDifferentTypes(Class clazz, Object expectedXValue) throws Exception { @@ -92,7 +96,7 @@ public class AbsentStreamValuesTest { Object obj = deserialize(bytes); out.println("deserialized: " + obj); Object actualXValue = clazz.getDeclaredMethod("x").invoke(obj); - assertEquals(actualXValue, expectedXValue); + assertEquals(expectedXValue, actualXValue); } // --- all together @@ -107,18 +111,18 @@ public class AbsentStreamValuesTest { R15 obj = (R15)deserialize(bytes); out.println("deserialized: " + obj); - assertEquals(obj.a, false); - assertEquals(obj.b, 0); - assertEquals(obj.c, 0); - assertEquals(obj.d, '\u0000'); - assertEquals(obj.e, 0); - assertEquals(obj.f, 0l); - assertEquals(obj.g, 0f); - assertEquals(obj.h, 0d); - assertEquals(obj.i, null); - assertEquals(obj.j, null); - assertEquals(obj.k, null); - assertEquals(obj.l, null); + assertEquals(false, obj.a); + assertEquals(0, obj.b); + assertEquals(0, obj.c); + assertEquals('\u0000', obj.d); + assertEquals(0, obj.e); + assertEquals(0l, obj.f); + assertEquals(0f, obj.g); + assertEquals(0d, obj.h); + assertEquals(null, obj.i); + assertEquals(null, obj.j); + assertEquals(null, obj.k); + assertEquals(null, obj.l); } // --- generic type @@ -132,8 +136,8 @@ public class AbsentStreamValuesTest { R16 obj = (R16)deserialize(bytes); out.println("deserialized: " + obj); - assertEquals(obj.t, null); - assertEquals(obj.u, null); + assertEquals(null, obj.t); + assertEquals(null, obj.u); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/BadCanonicalCtrTest.java b/test/jdk/java/io/Serializable/records/BadCanonicalCtrTest.java index 44959eaea87..528a006fc87 100644 --- a/test/jdk/java/io/Serializable/records/BadCanonicalCtrTest.java +++ b/test/jdk/java/io/Serializable/records/BadCanonicalCtrTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -27,7 +27,7 @@ * @summary InvalidClassException is thrown when the canonical constructor * cannot be found during deserialization. * @library /test/lib - * @run testng BadCanonicalCtrTest + * @run junit BadCanonicalCtrTest */ import java.io.ByteArrayInputStream; @@ -44,22 +44,25 @@ import java.lang.constant.MethodTypeDesc; import jdk.test.lib.compiler.InMemoryJavaCompiler; import jdk.test.lib.ByteCodeLoader; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; import static java.lang.classfile.ClassFile.ACC_PUBLIC; import static java.lang.constant.ConstantDescs.CD_Object; import static java.lang.constant.ConstantDescs.CD_void; import static java.lang.constant.ConstantDescs.INIT_NAME; import static java.lang.constant.ConstantDescs.MTD_void; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; + +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertTrue; +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; /** * Checks that an InvalidClassException is thrown when the canonical * constructor cannot be found during deserialization. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class BadCanonicalCtrTest { // ClassLoader for creating instances of the records to test with. @@ -76,7 +79,7 @@ public class BadCanonicalCtrTest { * the initial bytecode for the record classes using javac, then removes or * modifies the generated canonical constructor. */ - @BeforeTest + @BeforeAll public void setup() { { byte[] byteCode = InMemoryJavaCompiler.compile("R1", @@ -133,7 +136,6 @@ public class BadCanonicalCtrTest { return c.getConstructor(long.class).newInstance(l); } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() throws Exception { return new Object[][] { new Object[] { newR1() }, @@ -148,13 +150,14 @@ public class BadCanonicalCtrTest { * Tests that InvalidClassException is thrown when no constructor is * present. */ - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void missingConstructorTest(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); byte[] bytes = serialize(objToSerialize); out.println("deserializing"); - InvalidClassException ice = expectThrows(ICE, () -> deserialize(bytes, missingCtrClassLoader)); + InvalidClassException ice = Assertions.assertThrows(ICE, () -> deserialize(bytes, missingCtrClassLoader)); out.println("caught expected ICE: " + ice); assertTrue(ice.getMessage().contains("record canonical constructor not found")); } @@ -164,13 +167,14 @@ public class BadCanonicalCtrTest { * constructor is not present. ( a non-canonical constructor is * present ). */ - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void nonCanonicalConstructorTest(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); byte[] bytes = serialize(objToSerialize); out.println("deserializing"); - InvalidClassException ice = expectThrows(ICE, () -> deserialize(bytes, nonCanonicalCtrClassLoader)); + InvalidClassException ice = Assertions.assertThrows(ICE, () -> deserialize(bytes, nonCanonicalCtrClassLoader)); out.println("caught expected ICE: " + ice); assertTrue(ice.getMessage().contains("record canonical constructor not found")); } diff --git a/test/jdk/java/io/Serializable/records/BadValues.java b/test/jdk/java/io/Serializable/records/BadValues.java index 4e3dbaa200f..9d5e0c7be82 100644 --- a/test/jdk/java/io/Serializable/records/BadValues.java +++ b/test/jdk/java/io/Serializable/records/BadValues.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 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 @@ -24,7 +24,7 @@ /* * @test * @summary Basic test for ClassNotFoundException - * @run testng BadValues + * @run junit BadValues */ import java.io.ByteArrayInputStream; @@ -32,10 +32,11 @@ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; -import org.testng.annotations.Test; import static java.io.ObjectStreamConstants.*; import static java.lang.System.out; -import static org.testng.Assert.*; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; /** * Not directly related to records but provokes surrounding code, and ensures @@ -73,7 +74,7 @@ public class BadValues { public void testNotFoundSer() throws Exception { out.println("\n---"); byte[] bytes = byteStreamFor("XxYyZz", 0L, (byte)SC_SERIALIZABLE); - Throwable t = expectThrows(CNFE, () -> deserialize(bytes)); + Throwable t = assertThrows(CNFE, () -> deserialize(bytes)); out.println("caught expected CNFE: " + t); } @@ -81,7 +82,7 @@ public class BadValues { public void testNotFoundSerWr() throws Exception { out.println("\n---"); byte[] bytes = byteStreamFor("XxYyZz", 0L, (byte)(SC_SERIALIZABLE | SC_WRITE_METHOD)); - Throwable t = expectThrows(CNFE, () -> deserialize(bytes)); + Throwable t = assertThrows(CNFE, () -> deserialize(bytes)); out.println("caught expected CNFE: " + t); } @@ -89,7 +90,7 @@ public class BadValues { public void testNotFoundExt() throws Exception { out.println("\n---"); byte[] bytes = byteStreamFor("AaBbCc", 0L, (byte)SC_EXTERNALIZABLE); - Throwable t = expectThrows(CNFE, () -> deserialize(bytes)); + Throwable t = assertThrows(CNFE, () -> deserialize(bytes)); out.println("caught expected CNFE: " + t); } @@ -97,7 +98,7 @@ public class BadValues { public void testNotFoundExtWr() throws Exception { out.println("\n---"); byte[] bytes = byteStreamFor("AaBbCc", 0L, (byte)(SC_SERIALIZABLE | SC_WRITE_METHOD)); - Throwable t = expectThrows(CNFE, () -> deserialize(bytes)); + Throwable t = assertThrows(CNFE, () -> deserialize(bytes)); out.println("caught expected CNFE: " + t); } diff --git a/test/jdk/java/io/Serializable/records/BasicRecordSer.java b/test/jdk/java/io/Serializable/records/BasicRecordSer.java index 94a79e85b38..b05d6bd9550 100644 --- a/test/jdk/java/io/Serializable/records/BasicRecordSer.java +++ b/test/jdk/java/io/Serializable/records/BasicRecordSer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -25,7 +25,7 @@ * @test * @bug 8246774 * @summary Basic test that serializes and deserializes a number of records - * @run testng BasicRecordSer + * @run junit BasicRecordSer */ import java.io.ByteArrayInputStream; @@ -39,19 +39,24 @@ import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable; import java.math.BigInteger; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.String.format; import static java.lang.System.out; import static java.net.InetAddress.getLoopbackAddress; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; -import static org.testng.Assert.fail; + +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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; /** * Basic test that serializes and deserializes a number of simple records. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class BasicRecordSer { // a mix of a few record and non-record classes @@ -101,7 +106,6 @@ public class BasicRecordSer { record Wubble (Wobble wobble, Wibble wibble, String s) implements ThrowingExternalizable { } - @DataProvider(name = "serializable") public Object[][] serializable() { Foo foo = new Foo(23); return new Object[][] { @@ -121,14 +125,20 @@ public class BasicRecordSer { } /** Tests serializing and deserializing a number of records. */ - @Test(dataProvider = "serializable") + @ParameterizedTest + @MethodSource("serializable") public void testSerializable(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); var objDeserialized = serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize, objDeserialized); - assertEquals(objDeserialized, objToSerialize); + if (objToSerialize.getClass().isArray()) { + assertArrayEquals((Object[]) objDeserialized, (Object[]) objToSerialize); + assertArrayEquals((Object[]) objToSerialize, (Object[]) objDeserialized); + } else { + assertEquals(objDeserialized, objToSerialize); + assertEquals(objToSerialize, objDeserialized); + } } /** Tests serializing and deserializing of local records. */ @@ -154,8 +164,8 @@ public class BasicRecordSer { out.println("serializing : " + objToSerialize); Foo[] objDeserialized = (Foo[])serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize, objDeserialized); - assertEquals(objDeserialized, objToSerialize); + Assertions.assertArrayEquals(objDeserialized, objToSerialize); + Assertions.assertArrayEquals(objToSerialize, objDeserialized); for (Foo f : objDeserialized) assertTrue(objDeserialized[0] == f); @@ -171,8 +181,8 @@ public class BasicRecordSer { out.println("serializing : " + objToSerialize); Wobble[] objDeserialized = (Wobble[])serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize, objDeserialized); - assertEquals(objDeserialized, objToSerialize); + Assertions.assertArrayEquals(objDeserialized, objToSerialize); + Assertions.assertArrayEquals(objToSerialize, objDeserialized); for (Wobble w : objDeserialized) { assertTrue(objDeserialized[0] == w); @@ -192,7 +202,6 @@ public class BasicRecordSer { final NotSer notSer = new NotSer(7); } - @DataProvider(name = "notSerializable") public Object[][] notSerializable() { return new Object[][] { new Object[] { new NotSerEmpty() }, @@ -209,11 +218,12 @@ public class BasicRecordSer { static final Class NSE = NotSerializableException.class; /** Tests that non-Serializable record objects throw NotSerializableException. */ - @Test(dataProvider = "notSerializable") + @ParameterizedTest + @MethodSource("notSerializable") public void testNotSerializable(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); - NotSerializableException expected = expectThrows(NSE, () -> serialize(objToSerialize)); + NotSerializableException expected = Assertions.assertThrows(NSE, () -> serialize(objToSerialize)); out.println("caught expected NSE:" + expected); } @@ -235,9 +245,9 @@ public class BasicRecordSer { out.println("serializing : " + objToSerialize); var objDeserialized = serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize, objDeserialized); assertEquals(objDeserialized, objToSerialize); - assertEquals(e_ctrInvocationCount, 1); + assertEquals(objToSerialize, objDeserialized); + assertEquals(1, e_ctrInvocationCount); } // --- @@ -258,9 +268,9 @@ public class BasicRecordSer { var objToSerialize = new G(); g_ctrInvocationCount = 0; // reset out.println("serializing : " + objToSerialize); - NotSerializableException expected = expectThrows(NSE, () -> serialize(objToSerialize)); + NotSerializableException expected = Assertions.assertThrows(NSE, () -> serialize(objToSerialize)); out.println("caught expected NSE:" + expected); - assertEquals(g_ctrInvocationCount, 0); + assertEquals(0, g_ctrInvocationCount); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/ConstructorAccessTest.java b/test/jdk/java/io/Serializable/records/ConstructorAccessTest.java index 5057fcc7cbb..c84c7c9519e 100644 --- a/test/jdk/java/io/Serializable/records/ConstructorAccessTest.java +++ b/test/jdk/java/io/Serializable/records/ConstructorAccessTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -26,7 +26,7 @@ * @bug 8246774 * @summary Ensures that the serialization implementation can *always* access * the record constructor - * @run testng ConstructorAccessTest + * @run junit ConstructorAccessTest */ import java.io.ByteArrayInputStream; @@ -38,16 +38,19 @@ import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Externalizable; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -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.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /*implicit*/ record Aux1 (int x) implements Serializable { } /*implicit*/ record Aux2 (int x) implements Serializable { } +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ConstructorAccessTest { public record A (int x) implements Serializable { } @@ -75,7 +78,6 @@ public class ConstructorAccessTest { private record H (double d) implements ThrowingExternalizable { } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { new A(34) }, @@ -91,7 +93,8 @@ public class ConstructorAccessTest { }; } - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void roundTrip(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); diff --git a/test/jdk/java/io/Serializable/records/CycleTest.java b/test/jdk/java/io/Serializable/records/CycleTest.java index 53d1247e808..7b323a78af8 100644 --- a/test/jdk/java/io/Serializable/records/CycleTest.java +++ b/test/jdk/java/io/Serializable/records/CycleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -25,7 +25,7 @@ * @test * @bug 8246774 * @summary Ensures basic behavior of cycles from record components - * @run testng CycleTest + * @run junit CycleTest */ import java.io.ByteArrayInputStream; @@ -34,10 +34,11 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.testng.annotations.Test; import static java.lang.System.out; -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; public class CycleTest { @@ -61,10 +62,10 @@ public class CycleTest { out.println("serializing : " + r); R deserializedObj = serializeDeserialize(r); out.println("deserialized: " + deserializedObj); - assertEquals(deserializedObj.x(), 1); // sanity - assertEquals(deserializedObj.y(), 2); // sanity + assertEquals(1, deserializedObj.x()); // sanity + assertEquals(2, deserializedObj.y()); // sanity assertTrue(deserializedObj.c() instanceof C); // sanity - assertEquals(deserializedObj.c().obj, null); // cycle, expect null + assertEquals(null, deserializedObj.c().obj); // cycle, expect null } /** @@ -84,8 +85,8 @@ public class CycleTest { out.println("deserialized: " + deserializedObj); assertTrue(deserializedObj instanceof C); // sanity assertTrue(deserializedObj.obj != null); // expect non-null, r - assertEquals(((R)deserializedObj.obj).x(), 3); // sanity - assertEquals(((R)deserializedObj.obj).y(), 4); // sanity + assertEquals(3, ((R)deserializedObj.obj).x()); // sanity + assertEquals(4, ((R)deserializedObj.obj).y()); // sanity } record R2 (int x, int y, C c1, C c2) implements Serializable { } @@ -105,8 +106,8 @@ public class CycleTest { out.println("serializing : " + r); R2 deserializedObj = serializeDeserialize(r); out.println("deserialized: " + deserializedObj); - assertEquals(deserializedObj.x(), 5); // sanity - assertEquals(deserializedObj.y(), 6); // sanity + assertEquals(5, deserializedObj.x()); // sanity + assertEquals(6, deserializedObj.y()); // sanity c1 = deserializedObj.c1(); c2 = deserializedObj.c2(); @@ -132,11 +133,11 @@ public class CycleTest { R3 deserializedObj = serializeDeserialize(r3); out.println("deserialized: " + deserializedObj); assertTrue(deserializedObj.r() != null); - assertEquals(deserializedObj.l(), 9); // sanity - assertEquals(deserializedObj.r().x(), 7); // sanity - assertEquals(deserializedObj.r().y(), 8); // sanity + assertEquals(9, deserializedObj.l()); // sanity + assertEquals(7, deserializedObj.r().x()); // sanity + assertEquals(8, deserializedObj.r().y()); // sanity assertTrue(deserializedObj.r().c() instanceof C); // sanity - assertEquals(deserializedObj.r().c().obj, null); // cycle, expect null + assertEquals(null, deserializedObj.r().c().obj); // cycle, expect null } // --- infra diff --git a/test/jdk/java/io/Serializable/records/DifferentStreamFieldsTest.java b/test/jdk/java/io/Serializable/records/DifferentStreamFieldsTest.java index 02175c53bb8..2960cc4f723 100644 --- a/test/jdk/java/io/Serializable/records/DifferentStreamFieldsTest.java +++ b/test/jdk/java/io/Serializable/records/DifferentStreamFieldsTest.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 @@ -26,7 +26,7 @@ * @bug 8246774 * @summary Checks that the appropriate value is given to the canonical ctr * @library /test/lib - * @run testng DifferentStreamFieldsTest + * @run junit DifferentStreamFieldsTest */ import java.io.ByteArrayInputStream; @@ -38,14 +38,19 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import jdk.test.lib.serial.SerialObjectBuilder; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; + +import org.junit.jupiter.api.Assertions; +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; /** * Checks that the appropriate value is given to the canonical ctr. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class DifferentStreamFieldsTest { record R01(boolean x) implements Serializable {} @@ -76,7 +81,6 @@ public class DifferentStreamFieldsTest { record R14(R13[]x) implements Serializable {} - @DataProvider(name = "recordTypeAndExpectedValue") public Object[][] recordTypeAndExpectedValue() { return new Object[][]{ new Object[]{R01.class, false}, @@ -96,7 +100,8 @@ public class DifferentStreamFieldsTest { }; } - @Test(dataProvider = "recordTypeAndExpectedValue") + @ParameterizedTest + @MethodSource("recordTypeAndExpectedValue") public void testWithDifferentTypes(Class clazz, Object expectedXValue) throws Exception { out.println("\n---"); @@ -108,7 +113,7 @@ public class DifferentStreamFieldsTest { Object obj = deserialize(bytes); out.println("deserialized: " + obj); Object actualXValue = clazz.getDeclaredMethod("x").invoke(obj); - assertEquals(actualXValue, expectedXValue); + assertEquals(expectedXValue, actualXValue); bytes = SerialObjectBuilder .newBuilder(clazz.getName()) @@ -118,7 +123,7 @@ public class DifferentStreamFieldsTest { obj = deserialize(bytes); out.println("deserialized: " + obj); actualXValue = clazz.getDeclaredMethod("x").invoke(obj); - assertEquals(actualXValue, expectedXValue); + assertEquals(expectedXValue, actualXValue); } // --- all together @@ -137,18 +142,18 @@ public class DifferentStreamFieldsTest { R15 obj = deserialize(bytes); out.println("deserialized: " + obj); - assertEquals(obj.a, false); - assertEquals(obj.b, 0); - assertEquals(obj.c, 0); - assertEquals(obj.d, '\u0000'); - assertEquals(obj.e, 0); - assertEquals(obj.f, 0l); - assertEquals(obj.g, 0f); - assertEquals(obj.h, 0d); - assertEquals(obj.i, null); - assertEquals(obj.j, null); - assertEquals(obj.k, null); - assertEquals(obj.l, null); + assertEquals(false, obj.a); + assertEquals(0, obj.b); + assertEquals(0, obj.c); + assertEquals('\u0000', obj.d); + assertEquals(0, obj.e); + assertEquals(0l, obj.f); + assertEquals(0f, obj.g); + assertEquals(0d, obj.h); + assertEquals(null, obj.i); + assertEquals(null, obj.j); + assertEquals(null, obj.k); + assertEquals(null, obj.l); } @Test @@ -166,9 +171,9 @@ public class DifferentStreamFieldsTest { .build(); var deser1 = deserialize(OOSBytes); - assertEquals(deser1, r); + assertEquals(r, deser1); var deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); } { record R(int x, int y) implements Serializable {} @@ -176,7 +181,7 @@ public class DifferentStreamFieldsTest { var r = new R(7, 8); byte[] OOSBytes = serialize(r); var deser1 = deserialize(OOSBytes); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(R.class.getName()) @@ -185,7 +190,7 @@ public class DifferentStreamFieldsTest { .build(); var deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); builderBytes = SerialObjectBuilder .newBuilder(R.class.getName()) @@ -193,7 +198,7 @@ public class DifferentStreamFieldsTest { .addPrimitiveField("x", int.class, 7) .build(); deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); builderBytes = SerialObjectBuilder .newBuilder(R.class.getName()) @@ -203,12 +208,12 @@ public class DifferentStreamFieldsTest { .addPrimitiveField("z", int.class, 9) // additional fields .build(); deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); r = new R(0, 0); OOSBytes = serialize(r); deser1 = deserialize(OOSBytes); - assertEquals(deser1, r); + assertEquals(r, deser1); builderBytes = SerialObjectBuilder .newBuilder(R.class.getName()) @@ -216,13 +221,13 @@ public class DifferentStreamFieldsTest { .addPrimitiveField("x", int.class, 0) .build(); deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); builderBytes = SerialObjectBuilder .newBuilder(R.class.getName()) // no field values .build(); deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); } } @@ -234,7 +239,7 @@ public class DifferentStreamFieldsTest { var r = new Str("Hello", "World!"); var deser1 = deserialize(serialize(r)); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(Str.class.getName()) @@ -243,7 +248,7 @@ public class DifferentStreamFieldsTest { .build(); var deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); builderBytes = SerialObjectBuilder .newBuilder(Str.class.getName()) @@ -254,7 +259,7 @@ public class DifferentStreamFieldsTest { .build(); var deser3 = deserialize(builderBytes); - assertEquals(deser3, deser1); + assertEquals(deser1, deser3); } @Test @@ -264,8 +269,8 @@ public class DifferentStreamFieldsTest { record IntArray(int[]ints, long[]longs) implements Serializable {} IntArray r = new IntArray(new int[]{5, 4, 3, 2, 1}, new long[]{9L}); IntArray deser1 = deserialize(serialize(r)); - assertEquals(deser1.ints(), r.ints()); - assertEquals(deser1.longs(), r.longs()); + Assertions.assertArrayEquals(r.ints(), deser1.ints()); + Assertions.assertArrayEquals(r.longs(), deser1.longs()); byte[] builderBytes = SerialObjectBuilder .newBuilder(IntArray.class.getName()) @@ -274,14 +279,14 @@ public class DifferentStreamFieldsTest { .build(); IntArray deser2 = deserialize(builderBytes); - assertEquals(deser2.ints(), deser1.ints()); - assertEquals(deser2.longs(), deser1.longs()); + Assertions.assertArrayEquals(deser1.ints(), deser2.ints()); + Assertions.assertArrayEquals(deser1.longs(), deser2.longs()); } { record StrArray(String[]stringArray) implements Serializable {} StrArray r = new StrArray(new String[]{"foo", "bar"}); StrArray deser1 = deserialize(serialize(r)); - assertEquals(deser1.stringArray(), r.stringArray()); + Assertions.assertArrayEquals(r.stringArray(), deser1.stringArray()); byte[] builderBytes = SerialObjectBuilder .newBuilder(StrArray.class.getName()) @@ -289,7 +294,7 @@ public class DifferentStreamFieldsTest { .build(); StrArray deser2 = deserialize(builderBytes); - assertEquals(deser2.stringArray(), deser1.stringArray()); + Assertions.assertArrayEquals(deser1.stringArray(), deser2.stringArray()); } } @@ -302,7 +307,7 @@ public class DifferentStreamFieldsTest { var r = new NumberHolder(123); var deser1 = deserialize(serialize(r)); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(NumberHolder.class.getName()) @@ -310,7 +315,7 @@ public class DifferentStreamFieldsTest { .build(); var deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); } { @@ -318,7 +323,7 @@ public class DifferentStreamFieldsTest { var r = new IntegerHolder(123); var deser1 = deserialize(serialize(r)); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(IntegerHolder.class.getName()) @@ -326,7 +331,7 @@ public class DifferentStreamFieldsTest { .build(); var deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); } } @@ -338,7 +343,7 @@ public class DifferentStreamFieldsTest { var r = new StringHolder("123"); var deser1 = deserialize(serialize(r)); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(StringHolder.class.getName()) @@ -362,7 +367,7 @@ public class DifferentStreamFieldsTest { var r = new IntHolder(123); var deser1 = deserialize(serialize(r)); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(IntHolder.class.getName()) diff --git a/test/jdk/java/io/Serializable/records/ProhibitedMethods.java b/test/jdk/java/io/Serializable/records/ProhibitedMethods.java index d744e9ddbad..815fbacc0f7 100644 --- a/test/jdk/java/io/Serializable/records/ProhibitedMethods.java +++ b/test/jdk/java/io/Serializable/records/ProhibitedMethods.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -26,7 +26,7 @@ * @bug 8246774 * @summary Basic tests for prohibited magic serialization methods * @library /test/lib - * @run testng ProhibitedMethods + * @run junit ProhibitedMethods */ import java.io.ByteArrayInputStream; @@ -49,24 +49,28 @@ import java.math.BigDecimal; import jdk.test.lib.compiler.InMemoryJavaCompiler; import jdk.test.lib.ByteCodeLoader; -import org.testng.Assert; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; import static java.lang.classfile.ClassFile.ACC_PRIVATE; +import static java.lang.constant.ConstantDescs.CD_Object; import static java.lang.constant.ConstantDescs.CD_String; import static java.lang.constant.ConstantDescs.CD_void; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; -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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeAll; +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; /** * Checks that the various prohibited Serialization magic methods, and * Externalizable methods, are not invoked ( effectively ignored ) for * record objects. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ProhibitedMethods { public interface ThrowingExternalizable extends Externalizable { @@ -100,7 +104,7 @@ public class ProhibitedMethods { * fail("readObjectNoData should not be invoked"); } * } */ - @BeforeTest + @BeforeAll public void setup() { { byte[] byteCode = InMemoryJavaCompiler.compile("Foo", @@ -165,7 +169,6 @@ public class ProhibitedMethods { } } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { newFoo() }, @@ -177,7 +180,8 @@ public class ProhibitedMethods { }; } - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void roundTrip(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); @@ -245,8 +249,8 @@ public class ProhibitedMethods { return cf.transformClass(cf.parse(classBytes), ClassTransform.endHandler(clb -> { clb.withMethodBody(name, desc, ACC_PRIVATE, cob -> { cob.loadConstant(name + " should not be invoked"); - cob.invokestatic(Assert.class.describeConstable().orElseThrow(), "fail", - MethodTypeDesc.of(CD_void, CD_String)); + cob.invokestatic(Assertions.class.describeConstable().orElseThrow(), "fail", + MethodTypeDesc.of(CD_Object, CD_String)); cob.return_(); }); })); @@ -266,37 +270,37 @@ public class ProhibitedMethods { Method m = obj.getClass().getDeclaredMethod("writeObject", ObjectOutputStream.class); assertTrue((m.getModifiers() & Modifier.PRIVATE) != 0); m.setAccessible(true); - ReflectiveOperationException t = expectThrows(ROE, () -> + ReflectiveOperationException t = Assertions.assertThrows(ROE, () -> m.invoke(obj, new ObjectOutputStream(OutputStream.nullOutputStream()))); Throwable assertionError = t.getCause(); out.println("caught expected AssertionError: " + assertionError); assertTrue(assertionError instanceof AssertionError, "Expected AssertionError, got:" + assertionError); - assertEquals(assertionError.getMessage(), "writeObject should not be invoked"); + assertEquals("writeObject should not be invoked", assertionError.getMessage()); } { // readObject Method m = obj.getClass().getDeclaredMethod("readObject", ObjectInputStream.class); assertTrue((m.getModifiers() & Modifier.PRIVATE) != 0); m.setAccessible(true); - ReflectiveOperationException t = expectThrows(ROE, () -> + ReflectiveOperationException t = Assertions.assertThrows(ROE, () -> m.invoke(obj, new ObjectInputStream() { })); Throwable assertionError = t.getCause(); out.println("caught expected AssertionError: " + assertionError); assertTrue(assertionError instanceof AssertionError, "Expected AssertionError, got:" + assertionError); - assertEquals(assertionError.getMessage(), "readObject should not be invoked"); + assertEquals("readObject should not be invoked", assertionError.getMessage()); } { // readObjectNoData Method m = obj.getClass().getDeclaredMethod("readObjectNoData"); assertTrue((m.getModifiers() & Modifier.PRIVATE) != 0); m.setAccessible(true); - ReflectiveOperationException t = expectThrows(ROE, () -> m.invoke(obj)); + ReflectiveOperationException t = Assertions.assertThrows(ROE, () -> m.invoke(obj)); Throwable assertionError = t.getCause(); out.println("caught expected AssertionError: " + assertionError); assertTrue(assertionError instanceof AssertionError, "Expected AssertionError, got:" + assertionError); - assertEquals(assertionError.getMessage(), "readObjectNoData should not be invoked"); + assertEquals("readObjectNoData should not be invoked", assertionError.getMessage()); } } } diff --git a/test/jdk/java/io/Serializable/records/ReadResolveTest.java b/test/jdk/java/io/Serializable/records/ReadResolveTest.java index 04de34781f9..2eb77bbf663 100644 --- a/test/jdk/java/io/Serializable/records/ReadResolveTest.java +++ b/test/jdk/java/io/Serializable/records/ReadResolveTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -25,7 +25,7 @@ * @test * @bug 8246774 * @summary Basic tests for readResolve - * @run testng ReadResolveTest + * @run junit ReadResolveTest */ import java.io.ByteArrayInputStream; @@ -35,15 +35,19 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serial; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.String.format; import static java.lang.System.out; -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; /** * Tests records being used as a serial proxy. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ReadResolveTest { static class C1 implements Serializable { @@ -94,7 +98,6 @@ public class ReadResolveTest { } } - @DataProvider(name = "objectsToSerialize") public Object[][] objectsToSerialize() { return new Object[][] { new Object[] { new C1(3,4) }, @@ -103,13 +106,14 @@ public class ReadResolveTest { }; } - @Test(dataProvider = "objectsToSerialize") + @ParameterizedTest + @MethodSource("objectsToSerialize") public void testSerialize(Object objectToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objectToSerialize); Object deserializedObj = serializeDeserialize(objectToSerialize); out.println("deserialized: " + deserializedObj); - assertEquals(deserializedObj, objectToSerialize); + assertEquals(objectToSerialize, deserializedObj); } // -- null replacement @@ -128,7 +132,7 @@ public class ReadResolveTest { out.println("serializing : " + objectToSerialize); Object deserializedObj = serializeDeserialize(objectToSerialize); out.println("deserialized: " + deserializedObj); - assertEquals(deserializedObj, null); + assertEquals(null, deserializedObj); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/RecordClassTest.java b/test/jdk/java/io/Serializable/records/RecordClassTest.java index 401512056e6..ba920ce92e5 100644 --- a/test/jdk/java/io/Serializable/records/RecordClassTest.java +++ b/test/jdk/java/io/Serializable/records/RecordClassTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -25,7 +25,7 @@ * @test * @bug 8246774 * @summary Basic tests for serializing and deserializing record classes - * @run testng RecordClassTest + * @run junit RecordClassTest */ import java.io.ByteArrayInputStream; @@ -38,15 +38,18 @@ import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -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.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Serializes and deserializes record classes. Ensures that the SUID is 0. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class RecordClassTest { record Foo () implements Serializable { } @@ -74,7 +77,6 @@ public class RecordClassTest { record Wubble (Wobble wobble, Wibble wibble, String s) implements ThrowingExternalizable { } - @DataProvider(name = "recordClasses") public Object[][] recordClasses() { return new Object[][] { new Object[] { Foo.class , 0L }, @@ -87,7 +89,8 @@ public class RecordClassTest { } /** Tests that the serialized and deserialized instances are equal. */ - @Test(dataProvider = "recordClasses") + @ParameterizedTest + @MethodSource("recordClasses") public void testClassSerialization(Class recordClass, long unused) throws Exception { @@ -95,21 +98,22 @@ public class RecordClassTest { out.println("serializing : " + recordClass); var deserializedClass = serializeDeserialize(recordClass); out.println("deserialized: " + deserializedClass); - assertEquals(recordClass, deserializedClass); assertEquals(deserializedClass, recordClass); + assertEquals(recordClass, deserializedClass); } /** Tests that the SUID is always 0 unless explicitly declared. */ - @Test(dataProvider = "recordClasses") + @ParameterizedTest + @MethodSource("recordClasses") public void testSerialVersionUID(Class recordClass, long expectedUID) { out.println("\n---"); ObjectStreamClass osc = ObjectStreamClass.lookup(recordClass); out.println("ObjectStreamClass::lookup : " + osc); - assertEquals(osc.getSerialVersionUID(), expectedUID); + assertEquals(expectedUID, osc.getSerialVersionUID()); osc = ObjectStreamClass.lookupAny(recordClass); out.println("ObjectStreamClass::lookupAny: " + osc); - assertEquals(osc.getSerialVersionUID(), expectedUID); + assertEquals(expectedUID, osc.getSerialVersionUID()); } // --- not Serializable @@ -120,7 +124,6 @@ public class RecordClassTest { record NotSerializable3(T t) { } - @DataProvider(name = "notSerRecordClasses") public Object[][] notSerRecordClasses() { return new Object[][] { new Object[] { NotSerializable1.class }, @@ -130,16 +133,17 @@ public class RecordClassTest { } /** Tests that the generated SUID is always 0 for all non-Serializable record classes. */ - @Test(dataProvider = "notSerRecordClasses") + @ParameterizedTest + @MethodSource("notSerRecordClasses") public void testSerialVersionUIDNonSer(Class recordClass) { out.println("\n---"); ObjectStreamClass osc = ObjectStreamClass.lookup(recordClass); out.println("ObjectStreamClass::lookup : " + osc); - assertEquals(osc, null); + assertEquals(null, osc); osc = ObjectStreamClass.lookupAny(recordClass); out.println("ObjectStreamClass::lookupAny: " + osc); - assertEquals(osc.getSerialVersionUID(), 0L); + assertEquals(0L, osc.getSerialVersionUID()); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/SerialPersistentFieldsTest.java b/test/jdk/java/io/Serializable/records/SerialPersistentFieldsTest.java index 16266806850..471e94b6ed7 100644 --- a/test/jdk/java/io/Serializable/records/SerialPersistentFieldsTest.java +++ b/test/jdk/java/io/Serializable/records/SerialPersistentFieldsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -26,7 +26,7 @@ * @bug 8246774 * @summary Basic tests for prohibited magic serialPersistentFields * @library /test/lib - * @run testng SerialPersistentFieldsTest + * @run junit SerialPersistentFieldsTest */ import java.io.ByteArrayInputStream; @@ -52,9 +52,6 @@ import java.math.BigDecimal; import jdk.test.lib.ByteCodeLoader; import jdk.test.lib.compiler.InMemoryJavaCompiler; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; import static java.lang.classfile.ClassFile.ACC_FINAL; import static java.lang.classfile.ClassFile.ACC_PRIVATE; @@ -65,12 +62,18 @@ import static java.lang.constant.ConstantDescs.CD_void; import static java.lang.constant.ConstantDescs.CLASS_INIT_NAME; import static java.lang.constant.ConstantDescs.INIT_NAME; import static java.lang.constant.ConstantDescs.MTD_void; -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.BeforeAll; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Checks that the serialPersistentFields declaration is effectively ignored. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SerialPersistentFieldsTest { ClassLoader serializableRecordLoader; @@ -88,7 +91,7 @@ public class SerialPersistentFieldsTest { * }; * } */ - @BeforeTest + @BeforeAll public void setup() { { // R1 byte[] byteCode = InMemoryJavaCompiler.compile("R1", @@ -174,7 +177,6 @@ public class SerialPersistentFieldsTest { return newRecord("R5", new Class[]{int.class}, new Object[]{x}); } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { newR1() }, @@ -185,14 +187,15 @@ public class SerialPersistentFieldsTest { }; } - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void roundTrip(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); var objDeserialized = serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize, objDeserialized); assertEquals(objDeserialized, objToSerialize); + assertEquals(objToSerialize, objDeserialized); } byte[] serialize(T obj) throws IOException { @@ -290,7 +293,8 @@ public class SerialPersistentFieldsTest { // -- infra sanity -- /** Checks to ensure correct operation of the test's generation logic. */ - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void wellFormedGeneratedClasses(Object obj) throws Exception { out.println("\n---"); out.println(obj); diff --git a/test/jdk/java/io/Serializable/records/SerialVersionUIDTest.java b/test/jdk/java/io/Serializable/records/SerialVersionUIDTest.java index abc0c63b0f2..2c133392dcb 100644 --- a/test/jdk/java/io/Serializable/records/SerialVersionUIDTest.java +++ b/test/jdk/java/io/Serializable/records/SerialVersionUIDTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -25,7 +25,7 @@ * @test * @bug 8246774 * @summary Basic tests for SUID in the serial stream - * @run testng SerialVersionUIDTest + * @run junit SerialVersionUIDTest */ import java.io.ByteArrayInputStream; @@ -39,13 +39,16 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.stream.LongStream; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.io.ObjectStreamConstants.*; import static java.lang.System.out; -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.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SerialVersionUIDTest { record R1 () implements Serializable { @@ -64,7 +67,6 @@ public class SerialVersionUIDTest { private static final long serialVersionUID = 5678L; } - @DataProvider(name = "recordObjects") public Object[][] recordObjects() { return new Object[][] { new Object[] { new R1(), 1L }, @@ -78,7 +80,8 @@ public class SerialVersionUIDTest { /** * Tests that a declared SUID for a record class is inserted into the stream. */ - @Test(dataProvider = "recordObjects") + @ParameterizedTest + @MethodSource("recordObjects") public void testSerialize(Object objectToSerialize, long expectedUID) throws Exception { @@ -90,17 +93,16 @@ public class SerialVersionUIDTest { DataInputStream dis = new DataInputStream(bais); // sanity - assertEquals(dis.readShort(), STREAM_MAGIC); - assertEquals(dis.readShort(), STREAM_VERSION); - assertEquals(dis.readByte(), TC_OBJECT); - assertEquals(dis.readByte(), TC_CLASSDESC); - assertEquals(dis.readUTF(), objectToSerialize.getClass().getName()); + assertEquals(STREAM_MAGIC, dis.readShort()); + assertEquals(STREAM_VERSION, dis.readShort()); + assertEquals(TC_OBJECT, dis.readByte()); + assertEquals(TC_CLASSDESC, dis.readByte()); + assertEquals(objectToSerialize.getClass().getName(), dis.readUTF()); // verify that the UID is as expected - assertEquals(dis.readLong(), expectedUID); + assertEquals(expectedUID, dis.readLong()); } - @DataProvider(name = "recordClasses") public Object[][] recordClasses() { List list = new ArrayList<>(); List> recordClasses = List.of(R1.class, R2.class, R3.class, R4.class, R5.class); @@ -115,14 +117,15 @@ public class SerialVersionUIDTest { * Tests that matching of the serialVersionUID values ( stream value * and runtime class value ) is waived for record classes. */ - @Test(dataProvider = "recordClasses") + @ParameterizedTest + @MethodSource("recordClasses") public void testSerializeFromClass(Class cl, long suid) throws Exception { out.println("\n---"); byte[] bytes = byteStreamFor(cl.getName(), suid); Object obj = deserialize(bytes); - assertEquals(obj.getClass(), cl); + assertEquals(cl, obj.getClass()); assertTrue(obj.getClass().isRecord()); } diff --git a/test/jdk/java/io/Serializable/records/StreamRefTest.java b/test/jdk/java/io/Serializable/records/StreamRefTest.java index b0c72ec8a96..d0d3e353bdb 100644 --- a/test/jdk/java/io/Serializable/records/StreamRefTest.java +++ b/test/jdk/java/io/Serializable/records/StreamRefTest.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 @@ -25,7 +25,7 @@ * @test * @bug 8246774 * @summary Tests for stream references - * @run testng StreamRefTest + * @run junit StreamRefTest */ import java.io.ByteArrayInputStream; @@ -36,11 +36,12 @@ import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; + +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; /** * Tests for stream references. @@ -123,14 +124,14 @@ public class StreamRefTest { updateIntValue(3, -3, bytes, 40); var byteStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); - InvalidObjectException ioe = expectThrows(IOE, () -> deserializeOne(byteStream)); + InvalidObjectException ioe = Assertions.assertThrows(IOE, () -> deserializeOne(byteStream)); out.println("caught expected IOE: " + ioe); Throwable t = ioe.getCause(); assertTrue(t instanceof IllegalArgumentException, "Expected IAE, got:" + t); out.println("expected cause IAE: " + t); B b1 = (B)deserializeOne(byteStream); - assertEquals(b1.a, null); + assertEquals(null, b1.a); } @Test @@ -144,14 +145,14 @@ public class StreamRefTest { updateIntValue(3, -3, bytes, 96); var byteStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); - InvalidObjectException ioe = expectThrows(IOE, () -> deserializeOne(byteStream)); + InvalidObjectException ioe = Assertions.assertThrows(IOE, () -> deserializeOne(byteStream)); out.println("caught expected IOE: " + ioe); Throwable t = ioe.getCause(); assertTrue(t instanceof IllegalArgumentException, "Expected IAE, got:" + t); out.println("expected cause IAE: " + t); A a1 = (A)deserializeOne(byteStream); - assertEquals(a1, null); + assertEquals(null, a1); } // --- @@ -211,7 +212,7 @@ public class StreamRefTest { throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(bytes, offset, 4); DataInputStream dis = new DataInputStream(bais); - assertEquals(dis.readInt(), expectedValue); + assertEquals(expectedValue, dis.readInt()); } static void updateIntValue(int expectedValue, int newValue, byte[] bytes, int offset) diff --git a/test/jdk/java/io/Serializable/records/ThrowingConstructorTest.java b/test/jdk/java/io/Serializable/records/ThrowingConstructorTest.java index 8e43a11a832..ee05930f29e 100644 --- a/test/jdk/java/io/Serializable/records/ThrowingConstructorTest.java +++ b/test/jdk/java/io/Serializable/records/ThrowingConstructorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -25,7 +25,7 @@ * @test * @bug 8246774 * @summary Tests constructor invocation exceptions are handled appropriately - * @run testng ThrowingConstructorTest + * @run junit ThrowingConstructorTest */ import java.io.ByteArrayInputStream; @@ -35,17 +35,20 @@ import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; + +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.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * If the constructor invocation throws an exception, an * `InvalidObjectException` is thrown with that exception as its cause. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ThrowingConstructorTest { /** "big switch" that can be used to allow/disallow record construction @@ -84,7 +87,6 @@ public class ThrowingConstructorTest { static final Class IOE = InvalidObjectException.class; - @DataProvider(name = "exceptionInstances") public Object[][] exceptionInstances() { Object[][] objs = new Object[][] { new Object[] { new R1(), NullPointerException.class, "thrown from R1" }, @@ -98,7 +100,8 @@ public class ThrowingConstructorTest { return objs; } - @Test(dataProvider = "exceptionInstances") + @ParameterizedTest + @MethodSource("exceptionInstances") public void testExceptions(Object objectToSerialize, Class expectedExType, String expectedExMessage) @@ -107,13 +110,13 @@ public class ThrowingConstructorTest { out.println("\n---"); out.println("serializing: " + objectToSerialize); byte[] bytes = serialize(objectToSerialize); - InvalidObjectException ioe = expectThrows(IOE, () -> deserialize(bytes)); + InvalidObjectException ioe = Assertions.assertThrows(IOE, () -> deserialize(bytes)); out.println("caught expected IOE: " + ioe); Throwable t = ioe.getCause(); assertTrue(t.getClass().equals(expectedExType), "Expected:" + expectedExType + ", got:" + t); out.println("expected cause " + expectedExType +" : " + t); - assertEquals(t.getMessage(), expectedExMessage); + assertEquals(expectedExMessage, t.getMessage()); } // -- errors ( pass through unwrapped ) @@ -143,7 +146,6 @@ public class ThrowingConstructorTest { } } - @DataProvider(name = "errorInstances") public Object[][] errorInstances() { Object[][] objs = new Object[][] { new Object[] { new R4(), OutOfMemoryError.class, "thrown from R4" }, @@ -157,7 +159,8 @@ public class ThrowingConstructorTest { return objs; } - @Test(dataProvider = "errorInstances") + @ParameterizedTest + @MethodSource("errorInstances") public void testErrors(Object objectToSerialize, Class expectedExType, String expectedExMessage) @@ -166,11 +169,11 @@ public class ThrowingConstructorTest { out.println("\n---"); out.println("serializing: " + objectToSerialize); byte[] bytes = serialize(objectToSerialize); - Throwable t = expectThrows(expectedExType, () -> deserialize(bytes)); + Throwable t = Assertions.assertThrows(expectedExType, () -> deserialize(bytes)); assertTrue(t.getClass().equals(expectedExType), "Expected:" + expectedExType + ", got:" + t); out.println("caught expected " + expectedExType +" : " + t); - assertEquals(t.getMessage(), expectedExMessage); + assertEquals(expectedExMessage, t.getMessage()); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/UnsharedTest.java b/test/jdk/java/io/Serializable/records/UnsharedTest.java index c96010c83ab..114e2dc6e10 100644 --- a/test/jdk/java/io/Serializable/records/UnsharedTest.java +++ b/test/jdk/java/io/Serializable/records/UnsharedTest.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 @@ -25,7 +25,7 @@ * @test * @bug 8238763 8246774 * @summary ObjectInputStream readUnshared method handling of Records - * @run testng UnsharedTest + * @run junit UnsharedTest */ import java.io.ByteArrayInputStream; @@ -35,10 +35,11 @@ import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; +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; /** * Tests OOS::writeUnshared and OIS::readUnshared to verify that records @@ -56,16 +57,16 @@ public class UnsharedTest { { // shared - sanity to ensure the second foo is a ref var byteStream = serialize(foo, foo); var foo1 = (Foo) deserializeOne(byteStream); - assertEquals(foo1.x, foo.x); + assertEquals(foo.x, foo1.x); var foo2 = (Foo) deserializeOne(byteStream); - assertEquals(foo2.x, foo.x); + assertEquals(foo.x, foo2.x); assertTrue(foo2 == foo1); } { // unshared var byteStream = serialize(foo, foo); var foo1 = (Foo) deserializeOneUnshared(byteStream); - assertEquals(foo1.x, foo.x); - var expected = expectThrows(IOE, () -> deserializeOne(byteStream)); + assertEquals(foo.x, foo1.x); + var expected = Assertions.assertThrows(IOE, () -> deserializeOne(byteStream)); assertTrue(expected.getMessage().contains("cannot read back reference to unshared object")); } } @@ -76,17 +77,17 @@ public class UnsharedTest { { // shared - sanity to ensure the second foo is NOT a ref var byteStream = serializeUnshared(foo, foo); var foo1 = (Foo) deserializeOne(byteStream); - assertEquals(foo1.x, foo.x); + assertEquals(foo.x, foo1.x); var foo2 = (Foo) deserializeOne(byteStream); - assertEquals(foo2.x, foo.x); + assertEquals(foo.x, foo2.x); assertTrue(foo2 != foo1); } { // unshared var byteStream = serializeUnshared(foo, foo); var foo1 = (Foo) deserializeOneUnshared(byteStream); - assertEquals(foo1.x, foo.x); + assertEquals(foo.x, foo1.x); var foo2 = (Foo) deserializeOneUnshared(byteStream); - assertEquals(foo2.x, foo.x); + assertEquals(foo.x, foo2.x); assertTrue(foo2 != foo1); } } diff --git a/test/jdk/java/io/Serializable/records/WriteReplaceTest.java b/test/jdk/java/io/Serializable/records/WriteReplaceTest.java index c64d6355dd2..2e253c166a0 100644 --- a/test/jdk/java/io/Serializable/records/WriteReplaceTest.java +++ b/test/jdk/java/io/Serializable/records/WriteReplaceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -25,7 +25,7 @@ * @test * @bug 8246774 * @summary Basic tests for writeReplace - * @run testng WriteReplaceTest + * @run junit WriteReplaceTest */ import java.io.ByteArrayInputStream; @@ -34,11 +34,15 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -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; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class WriteReplaceTest { record R1 () implements Serializable { @@ -71,7 +75,6 @@ public class WriteReplaceTest { } } - @DataProvider(name = "recordObjects") public Object[][] recordObjects() { return new Object[][] { new Object[] { new R1(), R1.class }, @@ -81,7 +84,8 @@ public class WriteReplaceTest { }; } - @Test(dataProvider = "recordObjects") + @ParameterizedTest + @MethodSource("recordObjects") public void testSerialize(Object objectToSerialize, Class expectedType) throws Exception { @@ -90,9 +94,9 @@ public class WriteReplaceTest { Object deserializedObj = serializeDeserialize(objectToSerialize); out.println("deserialized: " + deserializedObj); if (objectToSerialize.getClass().equals(expectedType)) - assertEquals(deserializedObj, objectToSerialize); + assertEquals(objectToSerialize, deserializedObj); else - assertEquals(deserializedObj.getClass(), expectedType); + assertEquals(expectedType, deserializedObj.getClass()); } // -- null replacement @@ -108,7 +112,7 @@ public class WriteReplaceTest { out.println("serializing : " + objectToSerialize); Object deserializedObj = serializeDeserialize(objectToSerialize); out.println("deserialized: " + deserializedObj); - assertEquals(deserializedObj, null); + assertEquals(null, deserializedObj); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/migration/AbstractTest.java b/test/jdk/java/io/Serializable/records/migration/AbstractTest.java index e0bbc574500..488f4a33acd 100644 --- a/test/jdk/java/io/Serializable/records/migration/AbstractTest.java +++ b/test/jdk/java/io/Serializable/records/migration/AbstractTest.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 @@ -34,8 +34,9 @@ import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Path; import jdk.test.lib.compiler.CompilerUtils; -import org.testng.annotations.BeforeTest; -import static org.testng.Assert.*; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeAll; /** * An abstract superclass for tests that require to serialize and deserialize @@ -54,7 +55,7 @@ public class AbstractTest { static final Path RECORD_SRC_DIR = Path.of(TEST_SRC, "record"); static final Path RECORD_DEST_DIR = Path.of("record"); - @BeforeTest + @BeforeAll public void setup() throws IOException { assertTrue(CompilerUtils.compile(PLAIN_SRC_DIR, PLAIN_DEST_DIR, "--class-path", TEST_CLASSES_DIR.toString())); diff --git a/test/jdk/java/io/Serializable/records/migration/AssignableFromTest.java b/test/jdk/java/io/Serializable/records/migration/AssignableFromTest.java index 6097e2477df..117a8474c67 100644 --- a/test/jdk/java/io/Serializable/records/migration/AssignableFromTest.java +++ b/test/jdk/java/io/Serializable/records/migration/AssignableFromTest.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 @@ -29,24 +29,26 @@ * @modules jdk.compiler * @compile AssignableFrom.java Point.java * DefaultValues.java SuperStreamFields.java - * @run testng AssignableFromTest + * @run junit AssignableFromTest */ import java.math.BigDecimal; import java.math.BigInteger; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -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; /** * Basic test to check that stream field values that are not the exact * declared param/field type, but assignable to a declared supertype, * are bound/assigned correctly. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class AssignableFromTest extends AbstractTest { - @DataProvider(name = "plainInstances") public Object[][] plainInstances() { return new Object[][] { new Object[] { newPlainAssignableFrom(Byte.valueOf((byte)11)) }, @@ -59,7 +61,8 @@ public class AssignableFromTest extends AbstractTest { } /** Serialize non-record (plain) instances, deserialize as a record. */ - @Test(dataProvider = "plainInstances") + @ParameterizedTest + @MethodSource("plainInstances") public void testPlainToRecord(AssignableFrom objToSerialize) throws Exception { assert !objToSerialize.getClass().isRecord(); out.println("serialize : " + objToSerialize); @@ -68,13 +71,12 @@ public class AssignableFromTest extends AbstractTest { assert objDeserialized.getClass().isRecord(); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize.number(), objDeserialized.number()); assertEquals(objDeserialized.number(), objToSerialize.number()); + assertEquals(objToSerialize.number(), objDeserialized.number()); assertEquals(objDeserialized.number().getClass(), objDeserialized.number().getClass()); } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { newRecordAssignableFrom(Byte.valueOf((byte)21)) }, @@ -87,7 +89,8 @@ public class AssignableFromTest extends AbstractTest { } /** Serialize record instances, deserialize as non-record (plain). */ - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void testRecordToPlain(AssignableFrom objToSerialize) throws Exception { assert objToSerialize.getClass().isRecord(); out.println("serialize : " + objToSerialize); @@ -96,8 +99,8 @@ public class AssignableFromTest extends AbstractTest { assert !objDeserialized.getClass().isRecord(); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize.number(), objDeserialized.number()); assertEquals(objDeserialized.number(), objToSerialize.number()); + assertEquals(objToSerialize.number(), objDeserialized.number()); assertEquals(objDeserialized.number().getClass(), objDeserialized.number().getClass()); } diff --git a/test/jdk/java/io/Serializable/records/migration/DefaultValuesTest.java b/test/jdk/java/io/Serializable/records/migration/DefaultValuesTest.java index 4af684156c6..357c9400777 100644 --- a/test/jdk/java/io/Serializable/records/migration/DefaultValuesTest.java +++ b/test/jdk/java/io/Serializable/records/migration/DefaultValuesTest.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 @@ -28,21 +28,24 @@ * @library /test/lib * @modules jdk.compiler * @compile AssignableFrom.java Point.java DefaultValues.java SuperStreamFields.java - * @run testng DefaultValuesTest + * @run junit DefaultValuesTest */ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; -import org.testng.annotations.Test; import static java.io.ObjectStreamConstants.*; import static java.lang.System.out; -import static org.testng.Assert.*; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; /** * Basic test to check that default primitive / reference values are * presented to the record's canonical constructor, for fields not in * the stream. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class DefaultValuesTest extends AbstractTest { /** @@ -77,13 +80,13 @@ public class DefaultValuesTest extends AbstractTest { Point point = deserializeAsPlain(bytes); out.println("deserialized: " + point); - assertEquals(point.x(), 0); - assertEquals(point.y(), 0); + assertEquals(0, point.x()); + assertEquals(0, point.y()); point = deserializeAsRecord(bytes); out.println("deserialized: " + point); - assertEquals(point.x(), 0); - assertEquals(point.y(), 0); + assertEquals(0, point.x()); + assertEquals(0, point.y()); } // --- @@ -115,8 +118,8 @@ public class DefaultValuesTest extends AbstractTest { DefaultValues o1 = deserializeAsRecord(bytes); out.println("deserialized: " + o1); - assertEquals(o1.point().x(), point.x()); // sanity - assertEquals(o1.point().y(), point.y()); // sanity + assertEquals(point.x(), o1.point().x()); // sanity + assertEquals(point.y(), o1.point().y()); // sanity assertTrue(o1.bool() == Defaults.bool); assertTrue(o1.by() == Defaults.by); assertTrue(o1.ch() == Defaults.ch); diff --git a/test/jdk/java/io/Serializable/records/migration/SuperStreamFieldsTest.java b/test/jdk/java/io/Serializable/records/migration/SuperStreamFieldsTest.java index 6090d71003e..35e75341dbf 100644 --- a/test/jdk/java/io/Serializable/records/migration/SuperStreamFieldsTest.java +++ b/test/jdk/java/io/Serializable/records/migration/SuperStreamFieldsTest.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 @@ -28,20 +28,23 @@ * @library /test/lib * @modules jdk.compiler * @compile AssignableFrom.java Point.java DefaultValues.java SuperStreamFields.java - * @run testng SuperStreamFieldsTest + * @run junit SuperStreamFieldsTest */ -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; + +import org.junit.jupiter.api.Assertions; +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; /** * Tests that superclass fields in the stream are discarded. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SuperStreamFieldsTest extends AbstractTest { - @DataProvider(name = "plainInstances") public Object[][] plainInstances() { return new Object[][] { new Object[] { newPlainSuperStreamFields("cat", new int[] { 1 }, 1) }, @@ -51,7 +54,8 @@ public class SuperStreamFieldsTest extends AbstractTest { } /** Serializes non-record (plain) instance, deserializes as a record. */ - @Test(dataProvider = "plainInstances") + @ParameterizedTest + @MethodSource("plainInstances") public void testPlainToRecord(SuperStreamFields objToSerialize) throws Exception { assert !objToSerialize.getClass().isRecord(); out.println("serialize : " + objToSerialize); @@ -60,12 +64,11 @@ public class SuperStreamFieldsTest extends AbstractTest { assert objDeserialized.getClass().isRecord(); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize.str(), objDeserialized.str()); - assertEquals(objToSerialize.x(), objDeserialized.x()); - assertEquals(objToSerialize.y(), objDeserialized.y()); + assertEquals(objDeserialized.str(), objToSerialize.str()); + Assertions.assertArrayEquals(objDeserialized.x(), objToSerialize.x()); + assertEquals(objDeserialized.y(), objToSerialize.y()); } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { newRecordSuperStreamFields("goat", new int[] { 56 }, 66) }, @@ -75,7 +78,8 @@ public class SuperStreamFieldsTest extends AbstractTest { } /** Serializes record instance, deserializes as non-record (plain). */ - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void testRecordToPlain(SuperStreamFields objToSerialize) throws Exception { assert objToSerialize.getClass().isRecord(); out.println("serialize : " + objToSerialize); @@ -84,9 +88,9 @@ public class SuperStreamFieldsTest extends AbstractTest { assert !objDeserialized.getClass().isRecord(); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize.str(), objDeserialized.str()); - assertEquals(objToSerialize.x(), objDeserialized.x()); - assertEquals(objToSerialize.y(), objDeserialized.y()); + assertEquals(objDeserialized.str(), objToSerialize.str()); + Assertions.assertArrayEquals(objDeserialized.x(), objToSerialize.x()); + assertEquals(objDeserialized.y(), objToSerialize.y()); } diff --git a/test/jdk/java/io/pathNames/win32/DriveOnly.java b/test/jdk/java/io/pathNames/win32/DriveOnly.java index 96aba22a408..8c5d2dc0fe8 100644 --- a/test/jdk/java/io/pathNames/win32/DriveOnly.java +++ b/test/jdk/java/io/pathNames/win32/DriveOnly.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 diff --git a/test/jdk/java/lang/Class/getEnclosingClass/EnclosingClass.java b/test/jdk/java/lang/Class/getEnclosingClass/EnclosingClass.java index f458a0a6b00..c6900d18a19 100644 --- a/test/jdk/java/lang/Class/getEnclosingClass/EnclosingClass.java +++ b/test/jdk/java/lang/Class/getEnclosingClass/EnclosingClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 diff --git a/test/jdk/java/lang/Class/getEnclosingClass/EnclosingClassTest.java b/test/jdk/java/lang/Class/getEnclosingClass/EnclosingClassTest.java index 156d42dd6f8..c99d68d21b5 100644 --- a/test/jdk/java/lang/Class/getEnclosingClass/EnclosingClassTest.java +++ b/test/jdk/java/lang/Class/getEnclosingClass/EnclosingClassTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 diff --git a/test/jdk/java/lang/Class/getEnclosingClass/common/TestMe.java b/test/jdk/java/lang/Class/getEnclosingClass/common/TestMe.java index 220542239a0..79d13cd5ad4 100644 --- a/test/jdk/java/lang/Class/getEnclosingClass/common/TestMe.java +++ b/test/jdk/java/lang/Class/getEnclosingClass/common/TestMe.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 diff --git a/test/jdk/java/lang/IO/IO.java b/test/jdk/java/lang/IO/IO.java index 2b13657b58e..cff64146cd6 100644 --- a/test/jdk/java/lang/IO/IO.java +++ b/test/jdk/java/lang/IO/IO.java @@ -149,7 +149,7 @@ public class IO { } """); } - var pb = ProcessTools.createTestJavaProcessBuilder(file.toString()); + var pb = ProcessTools.createTestJavaProcessBuilder("-Xlog:aot=off", "-Xlog:cds=off", file.toString()); OutputAnalyzer output = ProcessTools.executeProcess(pb); assertEquals(0, output.getExitValue()); assertTrue(output.getStderr().isEmpty()); diff --git a/test/jdk/java/lang/ProcessBuilder/Basic.java b/test/jdk/java/lang/ProcessBuilder/Basic.java index 4377752650d..7034174f85c 100644 --- a/test/jdk/java/lang/ProcessBuilder/Basic.java +++ b/test/jdk/java/lang/ProcessBuilder/Basic.java @@ -85,8 +85,8 @@ public class Basic { static final String libpath = System.getenv("LIBPATH"); /* Used for regex String matching for long error messages */ - static final String PERMISSION_DENIED_ERROR_MSG = "(Permission denied|error=13)"; - static final String NO_SUCH_FILE_ERROR_MSG = "(No such file|error=2)"; + static final String PERMISSION_DENIED_ERROR_MSG = "(Permission denied|error:13)"; + static final String NO_SUCH_FILE_ERROR_MSG = "(No such file|error:2)"; static final String SPAWNHELPER_FAILURE_MSG = "(Possible reasons:)"; /** diff --git a/test/jdk/java/lang/ProcessBuilder/FDLeakTest/exeFDLeakTester.c b/test/jdk/java/lang/ProcessBuilder/FDLeakTest/exeFDLeakTester.c index b47228ee5de..3a86c8677d6 100644 --- a/test/jdk/java/lang/ProcessBuilder/FDLeakTest/exeFDLeakTester.c +++ b/test/jdk/java/lang/ProcessBuilder/FDLeakTest/exeFDLeakTester.c @@ -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 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/ScopedValue/ManyBindings.java b/test/jdk/java/lang/ScopedValue/ManyBindings.java index 5f9b5e6e176..be10d599ebd 100644 --- a/test/jdk/java/lang/ScopedValue/ManyBindings.java +++ b/test/jdk/java/lang/ScopedValue/ManyBindings.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 diff --git a/test/jdk/java/lang/ScopedValue/ScopedValueAPI.java b/test/jdk/java/lang/ScopedValue/ScopedValueAPI.java index 5652de7e10e..b15137c02a8 100644 --- a/test/jdk/java/lang/ScopedValue/ScopedValueAPI.java +++ b/test/jdk/java/lang/ScopedValue/ScopedValueAPI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, 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 diff --git a/test/jdk/java/lang/String/UnicodeCaseFoldingTest.java b/test/jdk/java/lang/String/UnicodeCaseFoldingTest.java new file mode 100644 index 00000000000..86b3fba0a27 --- /dev/null +++ b/test/jdk/java/lang/String/UnicodeCaseFoldingTest.java @@ -0,0 +1,329 @@ +/* + * 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 + * @summary tests unicode case-folding based String comparison and equality + * @bug 4397357 + * @library /lib/testlibrary/java/lang + * @modules java.base/jdk.internal.lang:+open + * @run junit/othervm + * UnicodeCaseFoldingTest + */ + +import java.nio.file.Files; +import java.util.stream.Stream; +import java.util.stream.Collectors; +import java.util.ArrayList; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import jdk.internal.lang.CaseFolding; + +public class UnicodeCaseFoldingTest { + + @Test + void testAllCommnFullCodePointsListedInCaseFoldinigTxt() throws Throwable { + var filter = "^.*; [CF]; .*$"; // C=common, F=full, for full case folding + var results = Files.lines(UCDFiles.CASEFOLDING) + .filter(line -> !line.startsWith("#") && line.matches(filter)) + .map(line -> { + var fields = line.split("; "); + var cp = Integer.parseInt(fields[0], 16); + fields = fields[2].trim().split(" "); + var folding = new int[fields.length]; + for (int i = 0; i < folding.length; i++) { + folding[i] = Integer.parseInt(fields[i], 16); + } + var source = new String(Character.toChars(cp)); + var expected = new String(folding, 0, folding.length); + // (1) Verify the folding result matches expected + assertEquals(expected, foldCase(source), "CaseFolding.fold(): "); + + // (2) Verify compareToFoldCase() result + assertEquals(0, source.compareToFoldCase(expected), "source.compareToFoldCase(expected)"); + assertEquals(0, expected.compareToFoldCase(source), "expected.compareToFoldCase(source)"); + + // (3) Verify equalsFoldCase() result + assertEquals(true, source.equalsFoldCase(expected), "source.equalsFoldCase(expected)"); + assertEquals(true, expected.equalsFoldCase(source), "expected.equalsFoldCase(source)"); + return null; + }) + .filter(error -> error != null) + .toArray(); + assertEquals(0, results.length); + } + + @Test + void testAllSimpleCodePointsListedInCaseFoldinigTxt() throws Throwable { + // S=simple, for simple case folding. The simple case folding should still matches + var filter = "^.*; [S]; .*$"; + var results = Files.lines(UCDFiles.CASEFOLDING) + .filter(line -> !line.startsWith("#") && line.matches(filter)) + .map(line -> { + var fields = line.split("; "); + var cp = Integer.parseInt(fields[0], 16); + fields = fields[2].trim().split(" "); + var folding = new int[fields.length]; + for (int i = 0; i < folding.length; i++) { + folding[i] = Integer.parseInt(fields[i], 16); + } + var source = new String(Character.toChars(cp)); + var expected = new String(folding, 0, folding.length); + + // (1) Verify compareToFoldCase() result + assertEquals(0, source.compareToFoldCase(expected), "source.compareToFoldCase(expected)"); + assertEquals(0, expected.compareToFoldCase(source), "expected.compareToFoldCase(source)"); + + // (2) Verify equalsFoldCase() result + assertEquals(true, source.equalsFoldCase(expected), "source.equalsFoldCase(expected)"); + assertEquals(true, expected.equalsFoldCase(source), "expected.equalsFoldCase(source)"); + return null; + }) + .filter(error -> error != null) + .toArray(); + assertEquals(0, results.length); + } + + @Test + public void testAllCodePointsFoldToThemselvesIfNotListed() throws Exception { + // Collect all code points that appear in CaseFolding.txt + var listed = Files.lines(UCDFiles.CASEFOLDING) + .filter(line -> !line.startsWith("#") && line.matches("^.*; [CF]; .*$")) + .map(line -> Integer.parseInt(line.split("; ")[0], 16)) + .collect(Collectors.toSet()); + + var failures = new ArrayList(); + + // Scan BMP + Supplementary Plane 1 (U+0000..U+1FFFF) + for (int cp = Character.MIN_CODE_POINT; cp <= 0x1FFFF; cp++) { + if (!Character.isDefined(cp)) { + continue; // skip undefined + } + if (Character.isSurrogate((char) cp)) { + continue; // skip surrogate code units + } + if (listed.contains(cp)) { + continue; // already tested separately + } + String s = new String(Character.toChars(cp)); + String folded = foldCase(s); + if (!s.equals(folded)) { + failures.add(String.format("Unexpected folding: U+%04X '%s' → '%s'", cp, s, folded)); + } + } + + assertEquals(0, failures.size(), + () -> "Some unlisted code points folded unexpectedly:\n" + + String.join("\n", failures)); + } + + @ParameterizedTest(name = "CaseFold \"{0}\" → \"{1}\"") + @MethodSource("caseFoldTestCases") + void testIndividualCaseFolding(String input, String expected) { + assertEquals(expected, foldCase(input)); + } + + static Stream caseFoldTestCases() { + return Stream.of( + // ASCII simple cases + Arguments.of("ABC", "abc"), + Arguments.of("already", "already"), + Arguments.of("MiXeD123", "mixed123"), + // --- Latin-1 to non-Latin-1 fold --- + Arguments.of("aBc\u00B5Efg", "abc\u03BCefg"), // "µ" → "μ" + Arguments.of("test\u00B5\ud801\udc00X", "test\u03bc\ud801\udc28x"), + // German Eszett + Arguments.of("Stra\u00DFe", "strasse"), // "Straße" + Arguments.of("\u1E9E", "ss"), // "ẞ" capital sharp S + // Turkish dotted I / dotless i + Arguments.of("I", "i"), + Arguments.of("\u0130", "i\u0307"), // capital dotted I → "i + dot above" + Arguments.of("\u0069\u0307", "i\u0307"), // small i + dot above remains + Arguments.of("\u0131", "\u0131"), // "ı" (dotless i stays dotless) + + // Greek special cases --- + Arguments.of("\u039F\u03A3", "\u03BF\u03C3"), // "ΟΣ" → "οσ" final sigma always folds to normal sigma + Arguments.of("\u1F88", "\u1F00\u03B9"), // "ᾈ" → "ἀι" Alpha with psili + ypogegrammeni + Arguments.of("\u039C\u03AC\u03CA\u03BF\u03C2", "\u03BC\u03AC\u03CA\u03BF\u03C3"), // "Μάϊος" → "μάϊοσ" + Arguments.of("\u1F08", "\u1F00"), // Ἀ (Capital Alpha with psili) → ἀ + + // Supplementary Plane characters + Arguments.of("\uD801\uDC00", "\uD801\uDC28"), // Deseret Capital Letter Long I → Small + Arguments.of("\uD801\uDC01", "\uD801\uDC29"), // Deseret Capital Letter Long E → Small + + // Supplementary inside ASCII + Arguments.of("abc\uD801\uDC00def", "abc\uD801\uDC28def"), + // Ligatures and compatibility folds + Arguments.of("\uFB00", "ff"), // ff → ff + Arguments.of("\uFB03", "ffi"), // ffi → ffi + Arguments.of("\u212A", "k"), // Kelvin sign → k + + Arguments.of("abc\uFB00def", "abcffdef"), // ff → ff + Arguments.of("abc\uFB03def", "abcffidef"), // ffi → ffi + Arguments.of("abc\u212Adef", "abckdef"), // Kelvin sign → k + + // --- Fullwidth --- + Arguments.of("\uFF21\uFF22\uFF23", "\uFF41\uFF42\uFF43"), // "ABC" → "abc" + + // --- Armenian --- + Arguments.of("\u0531", "\u0561"), // "Ա" → "ա" + + // --- Cherokee --- + Arguments.of("\u13A0", "\u13A0"), // Capital Cherokee A folds to itself + Arguments.of("\uAB70", "\u13A0") // Small Cherokee A folds Capital Cherokee A + ); + } + + static Stream caseFoldEqualProvider() { + return Stream.of( + Arguments.of("abc", "ABC"), + Arguments.of("aBcDe", "AbCdE"), + Arguments.of("\u00C0\u00E7", "\u00E0\u00C7"), // Àç vs àÇ + Arguments.of("straße", "STRASSE"), // ß → ss + Arguments.of("\uD83C\uDDE6", "\uD83C\uDDE6"), // 🇦 vs 🇦 + Arguments.of("\u1E9E", "ss"), // ẞ (capital sharp S) + Arguments.of("\u03A3", "\u03C3"), // Σ vs σ (Greek Sigma) + Arguments.of("\u03C3", "\u03C2"), // σ vs ς (Greek sigma/final sigma) + Arguments.of("\u212B", "\u00E5"), // Å (Angstrom sign) vs å + Arguments.of("\uFB00", "ff"), // ff (ligature) + Arguments.of("\u01C5", "\u01C5"), // Dž (Latin capital D with small z with caron) + Arguments.of("Caf\u00E9", "CAF\u00C9"), // Café vs CAFÉ + Arguments.of("\u03BA\u03B1\u03BB\u03B7\u03BC\u03AD\u03C1\u03B1", "\u039A\u0391\u039B\u0397\u039C\u0388\u03A1\u0391"), // καλημέρα vs ΚΑΛΗΜΕΡΑ + Arguments.of("\u4E2D\u56FD", "\u4E2D\u56FD"), // 中国 + Arguments.of("\u03B1", "\u0391"), // α vs Α (Greek alpha) + Arguments.of("\u212B", "\u00C5"), // Å vs Å + // from StringCompareToIgnoreCase + Arguments.of("\u0100\u0102\u0104\u0106\u0108", "\u0100\u0102\u0104\u0106\u0109"), // ĀĂĄĆĈ vs ĀĂĄĆĉ + Arguments.of("\u0101\u0103\u0105\u0107\u0109", "\u0100\u0102\u0104\u0106\u0109"), // āăąćĉ vs ĀĂĄĆĉ + Arguments.of("\ud801\udc00\ud801\udc01\ud801\udc02\ud801\udc03\ud801\udc04", + "\ud801\udc00\ud801\udc01\ud801\udc02\ud801\udc03\ud801\udc2c"), // 𐐀𐐁𐐂𐐃𐐄 vs 𐐀𐐁𐐂𐐃𐐬 + Arguments.of("\ud801\udc28\ud801\udc29\ud801\udc2a\ud801\udc2b\ud801\udc2c", + "\ud801\udc00\ud801\udc01\ud801\udc02\ud801\udc03\ud801\udc2c") // 𐐨𐐩𐐪𐐫𐐬 vs 𐐀𐐁𐐂𐐃𐐬 + ); + } + + @ParameterizedTest + @MethodSource("caseFoldEqualProvider") + void testcompareToFoldCaseEquals(String s1, String s2) { + assertEquals(0, s1.compareToFoldCase(s2)); + assertEquals(0, s2.compareToFoldCase(s1)); + assertEquals(true, s1.equalsFoldCase(s2)); + assertEquals(true, s2.equalsFoldCase(s1)); + assertEquals(foldCase(s1), foldCase(s2)); + } + + static Stream caseFoldOrderingProvider() { + return Stream.of( + Arguments.of("asa", "aß", -1), // ß → ss → "asa" < "ass" + Arguments.of("aß", "asa", +1), + Arguments.of("a\u00DF", "ass", 0), // aß vs ass + Arguments.of("\uFB03", "ffi", 0), // ffi (ligature) + Arguments.of("\u00C5", "Z", 1), // Å vs Z + Arguments.of("A", "\u00C0", -1), // A vs À + Arguments.of("\u03A9", "\u03C9", 0), // Ω vs ω + Arguments.of("\u03C2", "\u03C3", 0), // ς vs σ + Arguments.of("\uD835\uDD23", "R", 1), // 𝔯 (fraktur r) vs R + Arguments.of("\uFF26", "E", 1), // F (full-width F) vs E + Arguments.of("\u00C9clair", "Eclair", 1), // Éclair vs Eclair + Arguments.of("\u03bc\u00df", "\u00b5s", 1), + Arguments.of("\u00b5s", "\u03bc\u00df", -1) + ); + } + + @ParameterizedTest + @MethodSource("caseFoldOrderingProvider") + void testcompareToFoldCaseOrdering(String s1, String s2, int expectedSign) { + int cmp = s1.compareToFoldCase(s2); + assertEquals(expectedSign, Integer.signum(cmp)); + } + + static Stream roundTripProvider() { + return Stream.of( + Arguments.of("abc"), + Arguments.of("ABC"), + Arguments.of("straße"), + Arguments.of("Àç"), + Arguments.of("aß"), + Arguments.of("\uFB02uff"), // fluff (ligature in "fluff") + Arguments.of("\u00C9COLE") // ÉCOLE + ); + } + + @ParameterizedTest + @MethodSource("roundTripProvider") + void testCaseFoldRoundTrip(String s) { + String folded = foldCase(s); + assertEquals(0, s.compareToFoldCase(folded)); + assertEquals(0, folded.compareToFoldCase(s)); + assertEquals(true, s.equalsFoldCase(folded)); + assertEquals(true, folded.equalsFoldCase(s)); + } + + // helper to test the integrity of folding mapping + private static int[] longToFolding(long value) { + int len = (int) (value >>> 48); + if (len == 0) { + return new int[]{(int) (value & 0xFFFFF)}; + } else { + var folding = new int[len]; + for (int i = 0; i < len; i++) { + folding[i] = (int) (value & 0xFFFF); + value >>= 16; + } + return folding; + } + } + + private static String foldCase(String s) { + int first; + int len = s.length(); + int cpCnt = 1; + for (first = 0; first < len; first += cpCnt) { + int cp = s.codePointAt(first); + if (CaseFolding.isDefined(cp)) { + break; + } + cpCnt = Character.charCount(cp); + } + if (first == len) { + return s; + } + StringBuilder sb = new StringBuilder(len); + sb.append(s, 0, first); + for (int i = first; i < len; i += cpCnt) { + int cp = s.codePointAt(i); + int[] folded = longToFolding(CaseFolding.fold(cp)); + for (int f : folded) { + sb.appendCodePoint(f); + } + cpCnt = Character.charCount(cp); + } + return sb.toString(); + } +} diff --git a/test/jdk/java/lang/StringBuffer/ECoreIndexOf.java b/test/jdk/java/lang/StringBuffer/ECoreIndexOf.java index ccaee0f77ea..85930539059 100644 --- a/test/jdk/java/lang/StringBuffer/ECoreIndexOf.java +++ b/test/jdk/java/lang/StringBuffer/ECoreIndexOf.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 diff --git a/test/jdk/java/lang/System/PropertyTest.java b/test/jdk/java/lang/System/PropertyTest.java index 09b0835fb6e..dc263778959 100644 --- a/test/jdk/java/lang/System/PropertyTest.java +++ b/test/jdk/java/lang/System/PropertyTest.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 diff --git a/test/jdk/java/lang/System/i18nEnvArg.java b/test/jdk/java/lang/System/i18nEnvArg.java index b6c62c15e1f..fdeb1a18762 100644 --- a/test/jdk/java/lang/System/i18nEnvArg.java +++ b/test/jdk/java/lang/System/i18nEnvArg.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 diff --git a/test/jdk/java/lang/Thread/virtual/YieldQueuing.java b/test/jdk/java/lang/Thread/virtual/YieldQueuing.java index 7bd2320e2ab..bbecd711737 100644 --- a/test/jdk/java/lang/Thread/virtual/YieldQueuing.java +++ b/test/jdk/java/lang/Thread/virtual/YieldQueuing.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 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/lang/invoke/TestVHInvokerCaching.java b/test/jdk/java/lang/invoke/TestVHInvokerCaching.java index ccd97f82e9b..0a1ae5914ca 100644 --- a/test/jdk/java/lang/invoke/TestVHInvokerCaching.java +++ b/test/jdk/java/lang/invoke/TestVHInvokerCaching.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 @@ -37,7 +37,7 @@ import java.util.ArrayList; import java.util.List; import static java.lang.invoke.MethodHandles.lookup; -import static org.testng.Assert.assertSame; +import static org.testng.Assert.*; public class TestVHInvokerCaching { @@ -74,7 +74,7 @@ public class TestVHInvokerCaching { MethodHandles.Lookup lookup = lookup(); - for (Field field : Holder.class.getFields()) { + for (Field field : Holder.class.getDeclaredFields()) { String fieldName = field.getName(); Class fieldType = field.getType(); @@ -82,6 +82,8 @@ public class TestVHInvokerCaching { testHandles.add(lookup.findVarHandle(Holder.class, fieldName, fieldType)); } + assertFalse(testHandles.isEmpty()); + return testHandles.stream().map(vh -> new Object[]{ vh }).toArray(Object[][]::new); } } diff --git a/test/jdk/java/lang/management/MemoryMXBean/MemoryManagement.java b/test/jdk/java/lang/management/MemoryMXBean/MemoryManagement.java index b136b724b71..f6c7446d1f3 100644 --- a/test/jdk/java/lang/management/MemoryMXBean/MemoryManagement.java +++ b/test/jdk/java/lang/management/MemoryMXBean/MemoryManagement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -49,7 +49,7 @@ * * @modules jdk.management * - * @run main/timeout=600 MemoryManagement + * @run main/othervm/timeout=600 -Xmn8m MemoryManagement */ import java.lang.management.*; @@ -58,6 +58,10 @@ import javax.management.*; import javax.management.openmbean.CompositeData; public class MemoryManagement { + + private static final int YOUNG_GEN_SIZE = 8 * 1024 * 1024; // Must match -Xmn set on the @run line + private static final int NUM_CHUNKS = 2; + private static final MemoryMXBean mm = ManagementFactory.getMemoryMXBean(); private static final List pools = Collections.synchronizedList(ManagementFactory.getMemoryPoolMXBeans()); @@ -66,9 +70,6 @@ public class MemoryManagement { private static volatile MemoryPoolMXBean mpool = null; private static volatile boolean trace = false; private static volatile boolean testFailed = false; - private static final int NUM_CHUNKS = 2; - // Must match -Xmn set on the @run line - private static final int YOUNG_GEN_SIZE = 8 * 1024 * 1024; private static volatile long chunkSize; private static volatile int listenerInvoked = 0; diff --git a/test/jdk/java/lang/module/ClassFileVersionsTest.java b/test/jdk/java/lang/module/ClassFileVersionsTest.java index 308df36b81d..26a0b7e2fe3 100644 --- a/test/jdk/java/lang/module/ClassFileVersionsTest.java +++ b/test/jdk/java/lang/module/ClassFileVersionsTest.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 diff --git a/test/jdk/java/lang/module/ModuleDescriptorTest.java b/test/jdk/java/lang/module/ModuleDescriptorTest.java index fd7d32cc978..872dd9aa58a 100644 --- a/test/jdk/java/lang/module/ModuleDescriptorTest.java +++ b/test/jdk/java/lang/module/ModuleDescriptorTest.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 diff --git a/test/jdk/java/lang/module/ModuleReader/patched/PatchedModuleReaderTest.java b/test/jdk/java/lang/module/ModuleReader/patched/PatchedModuleReaderTest.java new file mode 100644 index 00000000000..80f4e324627 --- /dev/null +++ b/test/jdk/java/lang/module/ModuleReader/patched/PatchedModuleReaderTest.java @@ -0,0 +1,132 @@ +/* + * 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. + */ + +import java.io.IOException; +import java.lang.module.ModuleFinder; +import java.lang.module.ModuleReader; +import java.lang.module.ModuleReference; +import java.net.URI; +import java.util.Optional; +import java.util.stream.Stream; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/* + * @test + * @bug 8372787 + * @summary Test the behaviour of ModuleReader when using --patch-module + * @comment patch the java.base module with a test specific resource + * @compile/module=java.base java/lang/PatchedFoo.java + * @run junit/othervm ${test.main.class} + */ +class PatchedModuleReaderTest { + + private static ModuleReference patchedModuleRef; + + @BeforeAll + static void beforeAll() { + patchedModuleRef = ModuleFinder.ofSystem() + .find("java.base") + .orElseThrow(); + } + + /* + * Verifies that the resource that was patched into a module + * is found by the ModuleReader. + */ + @Test + void testResourceFound() throws Exception { + try (ModuleReader reader = patchedModuleRef.open()) { + String resourceName = "java/lang/PatchedFoo.class"; + Optional res = reader.find(resourceName); + assertTrue(res.isPresent(), resourceName + " is missing in " + + patchedModuleRef.descriptor().name() + " module"); + URI uri = res.get(); + assertEquals("file", uri.getScheme(), + "unexpected scheme in resource URI " + uri); + assertTrue(uri.getPath().endsWith(resourceName), + "unexpected path component " + uri.getPath() + + " in resource URI " + uri); + + } + } + + /* + * Verifies the ModuleReader against a resource which isn't + * expected to be part of the patched module. + */ + @Test + void testResourceNotFound() throws Exception { + try (ModuleReader reader = patchedModuleRef.open()) { + String nonExistentResource = "foo/bar/NonExistent.class"; + Optional res = reader.find(nonExistentResource); + assertTrue(res.isEmpty(), "unexpected resource " + nonExistentResource + + " in " + patchedModuleRef.descriptor().name() + " module"); + } + } + + /* + * This test opens a ModuleReader for a patched module, accumulates + * the Stream of resources from that ModuleReader and then closes that + * ModuleReader. It then verifies that the closed ModuleReader + * throws the specified IOException whenever it is used for subsequent + * operations on the Stream of resources. + */ + @Test + void testIOExceptionAfterClose() throws Exception { + ModuleReader reader; + Stream resources; + try (var _ = reader = patchedModuleRef.open()) { + // hold on to the available resources, to test them after the + // ModuleReader is closed + resources = reader.list(); + } // close the ModuleReader + + // verify IOException is thrown by the closed ModuleReader + + assertThrows(IOException.class, () -> reader.list(), + "ModuleReader.list()"); + + resources.forEach(rn -> { + assertThrows(IOException.class, () -> reader.read(rn), + "ModuleReader.read(String)"); + assertThrows(IOException.class, () -> reader.open(rn), + "ModuleReader.open(String)"); + assertThrows(IOException.class, () -> reader.find(rn), + "ModuleReader.find(String)"); + }); + + // repeat the test for a non-existent resource + String nonExistentResource = "foo/bar/NonExistent.class"; + assertThrows(IOException.class, () -> reader.read(nonExistentResource), + "ModuleReader.read(String)"); + assertThrows(IOException.class, () -> reader.open(nonExistentResource), + "ModuleReader.open(String)"); + assertThrows(IOException.class, () -> reader.find(nonExistentResource), + "ModuleReader.find(String)"); + } +} diff --git a/test/jdk/java/lang/module/ModuleReader/patched/java.base/java/lang/PatchedFoo.java b/test/jdk/java/lang/module/ModuleReader/patched/java.base/java/lang/PatchedFoo.java new file mode 100644 index 00000000000..814757134d6 --- /dev/null +++ b/test/jdk/java/lang/module/ModuleReader/patched/java.base/java/lang/PatchedFoo.java @@ -0,0 +1,26 @@ +/* + * 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 java.lang; + +public class PatchedFoo { +} diff --git a/test/jdk/java/lang/reflect/Generics/ProtectInnerStateOfTypeVariableImplTest.java b/test/jdk/java/lang/reflect/Generics/ProtectInnerStateOfTypeVariableImplTest.java new file mode 100644 index 00000000000..05a2a8e84de --- /dev/null +++ b/test/jdk/java/lang/reflect/Generics/ProtectInnerStateOfTypeVariableImplTest.java @@ -0,0 +1,70 @@ +/* + * 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 8372258 + * @summary Test if a copy of the internal state is provided + * @run junit ProtectInnerStateOfTypeVariableImplTest + */ + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.TypeVariable; + +import static org.junit.jupiter.api.Assertions.*; + +final class ProtectInnerStateOfTypeVariableImplTest { + + static final class Foo { + public Foo() { + } + + X x() { + return null; + } + } + + @Test + void testMethod() throws NoSuchMethodException { + Method method = Foo.class.getDeclaredMethod("x"); + TypeVariable tv = method.getTypeParameters()[0]; + + Method gd = tv.getGenericDeclaration(); + Method gd2 = tv.getGenericDeclaration(); + assertNotSame(gd, gd2); + } + + @Test + void testConstructor() throws NoSuchMethodException { + Constructor ctor = Foo.class.getConstructor(); + TypeVariable> tv = ctor.getTypeParameters()[0]; + + Constructor gd = tv.getGenericDeclaration(); + Constructor gd2 = tv.getGenericDeclaration(); + assertNotSame(gd, gd2); + } + +} diff --git a/test/jdk/java/lang/reflect/Modifier/toStringTest.java b/test/jdk/java/lang/reflect/Modifier/toStringTest.java index 85bceb48339..f36d83f1ad8 100644 --- a/test/jdk/java/lang/reflect/Modifier/toStringTest.java +++ b/test/jdk/java/lang/reflect/Modifier/toStringTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, 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 @@ -23,36 +23,71 @@ /** * @test - * @bug 4394937 8051382 + * @bug 4394937 8051382 8373125 * @summary tests the toString method of reflect.Modifier */ import java.lang.reflect.Modifier; +import static java.lang.reflect.Modifier.*; public class toStringTest { static void testString(int test, String expected) { - if(!Modifier.toString(test).equals(expected)) - throw new RuntimeException(test + - " yields incorrect toString result"); + String result = Modifier.toString(test); + if(!expected.equals(result)) { + System.err.println("For input 0x" + Integer.toHexString(test)); + System.err.println("expected:\t" + expected + "\ngot\t\t" + result); + + throw new RuntimeException(); + } } - public static void main(String [] argv) { - int allMods = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | - Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | - Modifier.TRANSIENT | Modifier.VOLATILE | Modifier.SYNCHRONIZED | - Modifier.NATIVE | Modifier.STRICT | Modifier.INTERFACE; + public static void main(String... argv) { + int allMods = PUBLIC | PROTECTED | PRIVATE | + ABSTRACT | STATIC | FINAL | + TRANSIENT | VOLATILE | SYNCHRONIZED | + NATIVE | STRICT | INTERFACE; String allModsString = "public protected private abstract static " + "final transient volatile synchronized native strictfp interface"; - /* zero should have an empty string */ + final int ALL_ONES = ~0; + + // zero should have an empty string testString(0, ""); - /* test to make sure all modifiers print out in the proper order */ + // test to make sure all modifiers print out in the proper order testString(allMods, allModsString); - /* verify no extraneous modifiers are printed */ - testString(~0, allModsString); + // verify no extraneous modifiers are printed + testString(ALL_ONES, allModsString); + + ModifierKindCase[] kindModifiers = { + new ModifierKindCase(classModifiers(), + "public protected private abstract " + + "static final strictfp"), + + new ModifierKindCase(constructorModifiers(),"public protected private"), + + new ModifierKindCase(fieldModifiers(), + "public protected private " + + "static final transient volatile"), + + new ModifierKindCase(interfaceModifiers(), + "public protected private " + + "abstract static strictfp"), + + new ModifierKindCase(methodModifiers(), + "public protected private abstract " + + "static final synchronized native strictfp"), + + new ModifierKindCase(parameterModifiers(), "final"), + }; + + for (var modKindCase : kindModifiers) { + testString(ALL_ONES & modKindCase.mask(), modKindCase.expected()); + } } + + private record ModifierKindCase(int mask, String expected){} } diff --git a/test/jdk/java/lang/reflect/exeCallerAccessTest/CallerAccessTest.java b/test/jdk/java/lang/reflect/exeCallerAccessTest/CallerAccessTest.java index bcd77af9ead..bf949fd2d15 100644 --- a/test/jdk/java/lang/reflect/exeCallerAccessTest/CallerAccessTest.java +++ b/test/jdk/java/lang/reflect/exeCallerAccessTest/CallerAccessTest.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 diff --git a/test/jdk/java/math/BigDecimal/Constructor.java b/test/jdk/java/math/BigDecimal/Constructor.java index b7371074225..975d96772a6 100644 --- a/test/jdk/java/math/BigDecimal/Constructor.java +++ b/test/jdk/java/math/BigDecimal/Constructor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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,45 +26,57 @@ * @bug 4259453 8200698 * @summary Test constructors of BigDecimal * @library .. - * @run testng Constructor + * @run junit Constructor */ +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import java.math.BigDecimal; -import org.testng.annotations.Test; public class Constructor { - @Test(expectedExceptions=NumberFormatException.class) + @Test public void stringConstructor() { - BigDecimal bd = new BigDecimal("1.2e"); + Assertions.assertThrows(NumberFormatException.class, () -> { + BigDecimal bd = new BigDecimal("1.2e"); + }); } - @Test(expectedExceptions=NumberFormatException.class) + @Test public void charArrayConstructorNegativeOffset() { - BigDecimal bd = new BigDecimal(new char[5], -1, 4, null); + Assertions.assertThrows(NumberFormatException.class, () -> { + BigDecimal bd = new BigDecimal(new char[5], -1, 4, null); + }); } - @Test(expectedExceptions=NumberFormatException.class) + @Test public void charArrayConstructorNegativeLength() { - BigDecimal bd = new BigDecimal(new char[5], 0, -1, null); + Assertions.assertThrows(NumberFormatException.class, () -> { + BigDecimal bd = new BigDecimal(new char[5], 0, -1, null); + }); } - @Test(expectedExceptions=NumberFormatException.class) + @Test public void charArrayConstructorIntegerOverflow() { - try { - BigDecimal bd = new BigDecimal(new char[5], Integer.MAX_VALUE - 5, - 6, null); - } catch (NumberFormatException nfe) { - if (nfe.getCause() instanceof IndexOutOfBoundsException) { - throw new RuntimeException - ("NumberFormatException should not have a cause"); - } else { - throw nfe; + Assertions.assertThrows(NumberFormatException.class, () -> { + try { + BigDecimal bd = new BigDecimal(new char[5], Integer.MAX_VALUE - 5, + 6, null); + } catch (NumberFormatException nfe) { + if (nfe.getCause() instanceof IndexOutOfBoundsException) { + throw new RuntimeException + ("NumberFormatException should not have a cause"); + } else { + throw nfe; + } } - } + }); } - @Test(expectedExceptions=NumberFormatException.class) + @Test public void charArrayConstructorIndexOutOfBounds() { - BigDecimal bd = new BigDecimal(new char[5], 1, 5, null); + Assertions.assertThrows(NumberFormatException.class, () -> { + BigDecimal bd = new BigDecimal(new char[5], 1, 5, null); + }); } } diff --git a/test/jdk/java/math/BigInteger/LargeValueExceptions.java b/test/jdk/java/math/BigInteger/LargeValueExceptions.java index 4c85281a5c0..9670691e51c 100644 --- a/test/jdk/java/math/BigInteger/LargeValueExceptions.java +++ b/test/jdk/java/math/BigInteger/LargeValueExceptions.java @@ -26,13 +26,16 @@ * @bug 8200698 * @summary Tests that exceptions are thrown for ops which would overflow * @requires (sun.arch.data.model == "64" & os.maxMemory >= 4g) - * @run testng/othervm/timeout=480 -Xmx4g LargeValueExceptions + * @run junit/othervm/timeout=480 -Xmx4g LargeValueExceptions */ + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import java.math.BigInteger; + import static java.math.BigInteger.ONE; -import org.testng.ITestResult; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.Test; // // The intent of this test is to probe the boundaries between overflow and @@ -64,47 +67,48 @@ public class LargeValueExceptions { // Half BigInteger.MAX_MAG_LENGTH private static final int MAX_INTS_HALF = MAX_INTS / 2; - // Print the run time of each sub-test in milliseconds - @AfterMethod - public void getRunTime(ITestResult tr) { - long time = tr.getEndMillis() - tr.getStartMillis(); - System.out.printf("Run time: %d ms%n", time); - } - // --- squaring --- // Largest no overflow determined by examining data lengths alone. - @Test(enabled=false) + @Test + @Disabled public void squareNoOverflow() { BigInteger x = ONE.shiftLeft(16*MAX_INTS - 1).subtract(ONE); BigInteger y = x.multiply(x); } // Smallest no overflow determined by extra calculations. - @Test(enabled=false) + @Test + @Disabled public void squareIndefiniteOverflowSuccess() { BigInteger x = ONE.shiftLeft(16*MAX_INTS - 1); BigInteger y = x.multiply(x); } // Largest overflow detected by extra calculations. - @Test(expectedExceptions=ArithmeticException.class,enabled=false) + @Test + @Disabled public void squareIndefiniteOverflowFailure() { - BigInteger x = ONE.shiftLeft(16*MAX_INTS).subtract(ONE); - BigInteger y = x.multiply(x); + Assertions.assertThrows(ArithmeticException.class, () -> { + BigInteger x = ONE.shiftLeft(16*MAX_INTS).subtract(ONE); + BigInteger y = x.multiply(x); + }); } // Smallest overflow detected by examining data lengths alone. - @Test(expectedExceptions=ArithmeticException.class) + @Test public void squareDefiniteOverflow() { - BigInteger x = ONE.shiftLeft(16*MAX_INTS); - BigInteger y = x.multiply(x); + Assertions.assertThrows(ArithmeticException.class, () -> { + BigInteger x = ONE.shiftLeft(16*MAX_INTS); + BigInteger y = x.multiply(x); + }); } // --- multiplication --- // Largest no overflow determined by examining data lengths alone. - @Test(enabled=false) + @Test + @Disabled public void multiplyNoOverflow() { final int halfMaxBits = MAX_INTS_HALF << 5; @@ -114,7 +118,8 @@ public class LargeValueExceptions { } // Smallest no overflow determined by extra calculations. - @Test(enabled=false) + @Test + @Disabled public void multiplyIndefiniteOverflowSuccess() { BigInteger x = ONE.shiftLeft((int)(MAX_BITS/2) - 1); long m = MAX_BITS - x.bitLength(); @@ -130,68 +135,83 @@ public class LargeValueExceptions { } // Largest overflow detected by extra calculations. - @Test(expectedExceptions=ArithmeticException.class,enabled=false) + @Test + @Disabled public void multiplyIndefiniteOverflowFailure() { - BigInteger x = ONE.shiftLeft((int)(MAX_BITS/2)).subtract(ONE); - long m = MAX_BITS - x.bitLength(); + Assertions.assertThrows(ArithmeticException.class, () -> { + BigInteger x = ONE.shiftLeft((int)(MAX_BITS/2)).subtract(ONE); + long m = MAX_BITS - x.bitLength(); - BigInteger y = ONE.shiftLeft((int)(MAX_BITS/2)).subtract(ONE); - long n = MAX_BITS - y.bitLength(); + BigInteger y = ONE.shiftLeft((int)(MAX_BITS/2)).subtract(ONE); + long n = MAX_BITS - y.bitLength(); - if (m + n != MAX_BITS) { - throw new RuntimeException("Unexpected leading zero sum"); - } + if (m + n != MAX_BITS) { + throw new RuntimeException("Unexpected leading zero sum"); + } - BigInteger z = x.multiply(y); + BigInteger z = x.multiply(y); + }); } // Smallest overflow detected by examining data lengths alone. - @Test(expectedExceptions=ArithmeticException.class) + @Test public void multiplyDefiniteOverflow() { - // multiply by 4 as MAX_INTS_HALF refers to ints - byte[] xmag = new byte[4*MAX_INTS_HALF]; - xmag[0] = (byte)0xff; - BigInteger x = new BigInteger(1, xmag); + Assertions.assertThrows(ArithmeticException.class, () -> { + // multiply by 4 as MAX_INTS_HALF refers to ints + byte[] xmag = new byte[4*MAX_INTS_HALF]; + xmag[0] = (byte)0xff; + BigInteger x = new BigInteger(1, xmag); - byte[] ymag = new byte[4*MAX_INTS_HALF + 1]; - ymag[0] = (byte)0xff; - BigInteger y = new BigInteger(1, ymag); + byte[] ymag = new byte[4*MAX_INTS_HALF + 1]; + ymag[0] = (byte)0xff; + BigInteger y = new BigInteger(1, ymag); - BigInteger z = x.multiply(y); + BigInteger z = x.multiply(y); + }); } // --- exponentiation --- - @Test(expectedExceptions=ArithmeticException.class) + @Test public void powOverflow() { - BigInteger.TEN.pow(Integer.MAX_VALUE); + Assertions.assertThrows(ArithmeticException.class, () -> { + BigInteger.TEN.pow(Integer.MAX_VALUE); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void powOverflow1() { - int shift = 20; - int exponent = 1 << shift; - BigInteger x = ONE.shiftLeft((int)(MAX_BITS / exponent)); - BigInteger y = x.pow(exponent); + Assertions.assertThrows(ArithmeticException.class, () -> { + int shift = 20; + int exponent = 1 << shift; + BigInteger x = ONE.shiftLeft((int)(MAX_BITS / exponent)); + BigInteger y = x.pow(exponent); + }); } - @Test(expectedExceptions=ArithmeticException.class) + @Test public void powOverflow2() { - int shift = 20; - int exponent = 1 << shift; - BigInteger x = ONE.shiftLeft((int)(MAX_BITS / exponent)).add(ONE); - BigInteger y = x.pow(exponent); + Assertions.assertThrows(ArithmeticException.class, () -> { + int shift = 20; + int exponent = 1 << shift; + BigInteger x = ONE.shiftLeft((int)(MAX_BITS / exponent)).add(ONE); + BigInteger y = x.pow(exponent); + }); } - @Test(expectedExceptions=ArithmeticException.class,enabled=false) + @Test + @Disabled public void powOverflow3() { - int shift = 20; - int exponent = 1 << shift; - BigInteger x = ONE.shiftLeft((int)(MAX_BITS / exponent)).subtract(ONE); - BigInteger y = x.pow(exponent); + Assertions.assertThrows(ArithmeticException.class, () -> { + int shift = 20; + int exponent = 1 << shift; + BigInteger x = ONE.shiftLeft((int)(MAX_BITS / exponent)).subtract(ONE); + BigInteger y = x.pow(exponent); + }); } - @Test(enabled=false) + @Test + @Disabled public void powOverflow4() { int shift = 20; int exponent = 1 << shift; diff --git a/test/jdk/java/net/HttpURLConnection/HttpURLConnectionExpectContinueTest.java b/test/jdk/java/net/HttpURLConnection/HttpURLConnectionExpectContinueTest.java index e701e234d83..a2d4bad995e 100644 --- a/test/jdk/java/net/HttpURLConnection/HttpURLConnectionExpectContinueTest.java +++ b/test/jdk/java/net/HttpURLConnection/HttpURLConnectionExpectContinueTest.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 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/Socket/AsyncShutdown.java b/test/jdk/java/net/Socket/AsyncShutdown.java index cdc930b360c..159c08075ad 100644 --- a/test/jdk/java/net/Socket/AsyncShutdown.java +++ b/test/jdk/java/net/Socket/AsyncShutdown.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 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 @@ -24,11 +24,13 @@ /* * @test * @requires (os.family == "linux" | os.family == "mac") - * @run testng AsyncShutdown * @summary Test shutdownInput/shutdownOutput with threads blocked in read/write + * @run junit AsyncShutdown */ import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; @@ -38,54 +40,56 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import static org.junit.jupiter.api.Assertions.*; -@Test -public class AsyncShutdown { +class AsyncShutdown { - public void testShutdownInput1() throws IOException { + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void testShutdownInput(boolean timed) throws IOException { withConnection((s1, s2) -> { + InputStream in = s1.getInputStream(); scheduleShutdownInput(s1, 2000); - int n = s1.getInputStream().read(); - assertTrue(n == -1); + if (timed) { + s1.setSoTimeout(30*1000); + } + assertEquals(-1, in.read()); + assertEquals(0, in.available()); }); } - public void testShutdownInput2() throws IOException { - withConnection((s1, s2) -> { - scheduleShutdownInput(s1, 2000); - s1.setSoTimeout(30*1000); - int n = s1.getInputStream().read(); - assertTrue(n == -1); - }); - } - - public void testShutdownOutput1() throws IOException { + @Test + void testShutdownOutput1() throws IOException { withConnection((s1, s2) -> { + OutputStream out = s1.getOutputStream(); scheduleShutdownOutput(s1, 2000); byte[] data = new byte[128*1024]; try { while (true) { - s1.getOutputStream().write(data); + out.write(data); } } catch (IOException expected) { } }); } - public void testShutdownOutput2() throws IOException { + @Test + void testShutdownOutput2() throws IOException { withConnection((s1, s2) -> { s1.setSoTimeout(100); try { s1.getInputStream().read(); - assertTrue(false); + fail(); } catch (SocketTimeoutException e) { } + OutputStream out = s1.getOutputStream(); scheduleShutdownOutput(s1, 2000); byte[] data = new byte[128*1024]; try { while (true) { - s1.getOutputStream().write(data); + out.write(data); } } catch (IOException expected) { } }); diff --git a/test/jdk/java/net/URL/OpenStream.java b/test/jdk/java/net/URL/OpenStream.java index 82fd5106056..10737d544d0 100644 --- a/test/jdk/java/net/URL/OpenStream.java +++ b/test/jdk/java/net/URL/OpenStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 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 9a9c2b44cd7..992b215ade0 100644 --- a/test/jdk/java/net/httpclient/AbstractThrowingPublishers.java +++ b/test/jdk/java/net/httpclient/AbstractThrowingPublishers.java @@ -23,14 +23,6 @@ import jdk.httpclient.test.lib.http3.Http3TestServer; import jdk.test.lib.net.SimpleSSLContext; -import org.testng.ITestContext; -import org.testng.ITestResult; -import org.testng.SkipException; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; import javax.net.ssl.SSLContext; import java.io.IOException; @@ -48,7 +40,6 @@ import java.net.http.HttpResponse.BodyHandler; import java.net.http.HttpResponse.BodyHandlers; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Set; @@ -61,6 +52,7 @@ import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.Flow; import java.util.concurrent.SubmissionPublisher; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiPredicate; @@ -78,28 +70,35 @@ import static java.net.http.HttpClient.Version.HTTP_2; import static java.net.http.HttpClient.Version.HTTP_3; 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.assertTrue; +import org.junit.jupiter.api.AfterAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.extension.TestWatcher; public abstract class AbstractThrowingPublishers implements HttpServerAdapters { - SSLContext sslContext; - HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] - HttpTestServer httpsTestServer; // HTTPS/1.1 - HttpTestServer http2TestServer; // HTTP/2 ( h2c ) - HttpTestServer https2TestServer; // HTTP/2 ( h2 ) - HttpTestServer http3TestServer; // HTTP/3 ( h3 ) - String httpURI_fixed; - String httpURI_chunk; - String httpsURI_fixed; - String httpsURI_chunk; - String http2URI_fixed; - String http2URI_chunk; - String https2URI_fixed; - String https2URI_chunk; - String http3URI_fixed; - String http3URI_chunk; - String http3URI_head; + 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 ) + static HttpTestServer https2TestServer; // HTTP/2 ( h2 ) + static HttpTestServer http3TestServer; // HTTP/3 ( h3 ) + static String httpURI_fixed; + static String httpURI_chunk; + static String httpsURI_fixed; + static String httpsURI_chunk; + static String http2URI_fixed; + static String http2URI_chunk; + static String https2URI_fixed; + static String https2URI_chunk; + static String http3URI_fixed; + static String http3URI_chunk; + static String http3URI_head; static final int ITERATION_COUNT = 1; // a shared executor helps reduce the amount of threads created by the test @@ -117,8 +116,34 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan); } - final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; - private volatile HttpClient sharedClient; + final static class TestStopper implements TestWatcher, BeforeEachCallback { + final AtomicReference failed = new AtomicReference<>(); + TestStopper() { } + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + if (stopAfterFirstFailure()) { + String msg = "Aborting due to: " + cause; + failed.compareAndSet(null, msg); + FAILURES.putIfAbsent(context.getDisplayName(), cause); + System.out.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + System.err.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + } + } + + @Override + public void beforeEach(ExtensionContext context) { + String msg = failed.get(); + Assumptions.assumeTrue(msg == null, msg); + } + } + + @RegisterExtension + static final TestStopper stopper = new TestStopper(); + + static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; + private static volatile HttpClient sharedClient; static class TestExecutor implements Executor { final AtomicLong tasks = new AtomicLong(); @@ -144,21 +169,10 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { } } - protected boolean stopAfterFirstFailure() { + protected static boolean stopAfterFirstFailure() { return Boolean.getBoolean("jdk.internal.httpclient.debug"); } - final AtomicReference skiptests = new AtomicReference<>(); - void checkSkip() { - var skip = skiptests.get(); - if (skip != null) throw skip; - } - static String name(ITestResult result) { - var params = result.getParameters(); - return result.getName() - + (params == null ? "()" : Arrays.toString(result.getParameters())); - } - static Version version(String uri) { if (uri.contains("/http1/") || uri.contains("/https1/")) return HTTP_1_1; @@ -169,7 +183,7 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { return null; } - HttpRequest.Builder newRequestBuilder(String uri) { + static HttpRequest.Builder newRequestBuilder(String uri) { var builder = HttpRequest.newBuilder(URI.create(uri)); if (version(uri) == HTTP_3) { builder.version(HTTP_3); @@ -178,7 +192,7 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { return builder; } - HttpResponse headRequest(HttpClient client) + static HttpResponse headRequest(HttpClient client) throws IOException, InterruptedException { System.out.println("\n" + now() + "--- Sending HEAD request ----\n"); @@ -187,26 +201,16 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { var request = newRequestBuilder(http3URI_head) .HEAD().version(HTTP_2).build(); var response = client.send(request, BodyHandlers.ofString()); - assertEquals(response.statusCode(), 200); - assertEquals(response.version(), HTTP_2); + assertEquals(200, response.statusCode()); + assertEquals(HTTP_2, response.version()); System.out.println("\n" + now() + "--- HEAD request succeeded ----\n"); System.err.println("\n" + now() + "--- HEAD request succeeded ----\n"); return response; } - @BeforeMethod - void beforeMethod(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - if (skiptests.get() == null) { - SkipException skip = new SkipException("some tests failed"); - skip.setStackTrace(new StackTraceElement[0]); - skiptests.compareAndSet(null, skip); - } - } - } - @AfterClass - static final void printFailedTests(ITestContext context) { + @AfterAll + static final void printFailedTests() { out.println("\n========================="); try { // Exceptions should already have been added to FAILURES @@ -230,7 +234,7 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { } } - private String[] uris() { + private static String[] uris() { return new String[] { http3URI_fixed, http3URI_chunk, @@ -245,8 +249,7 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { }; } - @DataProvider(name = "sanity") - public Object[][] sanity() { + public static Object[][] sanity() { String[] uris = uris(); Object[][] result = new Object[uris.length * 2][]; //Object[][] result = new Object[uris.length][]; @@ -277,7 +280,7 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { } } - private Object[][] variants(List throwers, Set whereValues) { + private static Object[][] variants(List throwers, Set whereValues) { String[] uris = uris(); Object[][] result = new Object[uris.length * 2 * throwers.size()][]; //Object[][] result = new Object[(uris.length/2) * 2 * 2][]; @@ -296,93 +299,65 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { return result; } - @DataProvider(name = "subscribeProvider") - public Object[][] subscribeProvider(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] subscribeProvider() { return variants(List.of( new UncheckedCustomExceptionThrower(), new UncheckedIOExceptionThrower()), EnumSet.of(Where.BEFORE_SUBSCRIBE, Where.AFTER_SUBSCRIBE)); } - @DataProvider(name = "requestProvider") - public Object[][] requestProvider(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] requestProvider() { return variants(List.of( new UncheckedCustomExceptionThrower(), new UncheckedIOExceptionThrower()), EnumSet.of(Where.BEFORE_REQUEST, Where.AFTER_REQUEST)); } - @DataProvider(name = "nextRequestProvider") - public Object[][] nextRequestProvider(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] nextRequestProvider() { return variants(List.of( new UncheckedCustomExceptionThrower(), new UncheckedIOExceptionThrower()), EnumSet.of(Where.BEFORE_NEXT_REQUEST, Where.AFTER_NEXT_REQUEST)); } - @DataProvider(name = "beforeCancelProviderIO") - public Object[][] beforeCancelProviderIO(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] beforeCancelProviderIO() { return variants(List.of( new UncheckedIOExceptionThrower()), EnumSet.of(Where.BEFORE_CANCEL)); } - @DataProvider(name = "afterCancelProviderIO") - public Object[][] afterCancelProviderIO(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] afterCancelProviderIO() { return variants(List.of( new UncheckedIOExceptionThrower()), EnumSet.of(Where.AFTER_CANCEL)); } - @DataProvider(name = "beforeCancelProviderCustom") - public Object[][] beforeCancelProviderCustom(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] beforeCancelProviderCustom() { return variants(List.of( new UncheckedCustomExceptionThrower()), EnumSet.of(Where.BEFORE_CANCEL)); } - @DataProvider(name = "afterCancelProviderCustom") - public Object[][] afterCancelProvider(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] afterCancelProviderCustom() { return variants(List.of( new UncheckedCustomExceptionThrower()), EnumSet.of(Where.AFTER_CANCEL)); } - private HttpClient makeNewClient() { + private static HttpClient makeNewClient() { clientCount.incrementAndGet(); - return TRACKER.track(newClientBuilderForH3() + return TRACKER.track(HttpServerAdapters.createClientBuilderForH3() .proxy(HttpClient.Builder.NO_PROXY) .executor(executor) .sslContext(sslContext) .build()); } - HttpClient newHttpClient(boolean share) { + static HttpClient newHttpClient(boolean share) { if (!share) return makeNewClient(); HttpClient shared = sharedClient; if (shared != null) return shared; - synchronized (this) { + synchronized (AbstractThrowingPublishers.class) { shared = sharedClient; if (shared == null) { shared = sharedClient = makeNewClient(); @@ -430,7 +405,7 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { CompletableFuture> response = client.sendAsync(req, handler); String body = response.join().body(); - assertEquals(body, Stream.of(BODY.split("\\|")).collect(Collectors.joining())); + assertEquals(Stream.of(BODY.split("\\|")).collect(Collectors.joining()), body); if (!sameClient) { // Wait for the client to be garbage collected. // we use the ReferenceTracker API rather than HttpClient::close here, @@ -474,7 +449,6 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { boolean async, Set whereValues) throws Exception { - checkSkip(); out.printf("%n%s%s%n", now(), name); try { testThrowing(uri, sameClient, publishers, finisher, thrower, async, whereValues); @@ -778,15 +752,11 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { } - @BeforeTest - public void setup() throws Exception { + @BeforeAll + public static void setup() throws Exception { 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(); @@ -861,8 +831,8 @@ public abstract class AbstractThrowingPublishers implements HttpServerAdapters { System.err.println(now() + "setup done"); } - @AfterTest - public void teardown() throws Exception { + @AfterAll + public static void teardown() throws Exception { System.out.println(now() + "teardown"); System.err.println(now() + "teardown"); diff --git a/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java b/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java index a7aea89c379..ddd9c52fc58 100644 --- a/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java +++ b/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java @@ -35,18 +35,10 @@ * ReferenceTracker AbstractThrowingPushPromises * jdk.httpclient.test.lib.common.HttpServerAdapters * - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true */ import jdk.test.lib.net.SimpleSSLContext; -import org.testng.ITestContext; -import org.testng.ITestResult; -import org.testng.SkipException; -import org.testng.annotations.AfterTest; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; import javax.net.ssl.SSLContext; import java.io.BufferedReader; @@ -100,21 +92,31 @@ import static java.net.http.HttpClient.Version.HTTP_3; 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.assertTrue; +import org.junit.jupiter.api.AfterAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +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.TestInstance; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.extension.TestWatcher; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public abstract class AbstractThrowingPushPromises implements HttpServerAdapters { - SSLContext sslContext; - HttpTestServer http2TestServer; // HTTP/2 ( h2c ) - HttpTestServer https2TestServer; // HTTP/2 ( h2 ) - HttpTestServer http3TestServer; // HTTP/3 ( h3 ) - String http2URI_fixed; - String http2URI_chunk; - String https2URI_fixed; - String https2URI_chunk; - String http3URI_fixed; - String http3URI_chunk; + 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 ) + static String http2URI_fixed; + static String http2URI_chunk; + static String https2URI_fixed; + static String https2URI_chunk; + static String http3URI_fixed; + static String http3URI_chunk; static final int ITERATION_COUNT = 1; // a shared executor helps reduce the amount of threads created by the test @@ -132,8 +134,34 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan); } - final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; - private volatile HttpClient sharedClient; + static final class TestStopper implements TestWatcher, BeforeEachCallback { + final AtomicReference failed = new AtomicReference<>(); + TestStopper() { } + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + if (stopAfterFirstFailure()) { + String msg = "Aborting due to: " + cause; + failed.compareAndSet(null, msg); + FAILURES.putIfAbsent(context.getDisplayName(), cause); + System.out.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + System.err.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + } + } + + @Override + public void beforeEach(ExtensionContext context) { + String msg = failed.get(); + Assumptions.assumeTrue(msg == null, msg); + } + } + + @RegisterExtension + static final TestStopper stopper = new TestStopper(); + + static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; + private static volatile HttpClient sharedClient; static class TestExecutor implements Executor { final AtomicLong tasks = new AtomicLong(); @@ -159,34 +187,13 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters } } - protected boolean stopAfterFirstFailure() { + protected static boolean stopAfterFirstFailure() { return Boolean.getBoolean("jdk.internal.httpclient.debug"); } - final AtomicReference skiptests = new AtomicReference<>(); - void checkSkip() { - var skip = skiptests.get(); - if (skip != null) throw skip; - } - static String name(ITestResult result) { - var params = result.getParameters(); - return result.getName() - + (params == null ? "()" : Arrays.toString(result.getParameters())); - } - @BeforeMethod - void beforeMethod(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - if (skiptests.get() == null) { - SkipException skip = new SkipException("some tests failed"); - skip.setStackTrace(new StackTraceElement[0]); - skiptests.compareAndSet(null, skip); - } - } - } - - @AfterClass - static final void printFailedTests(ITestContext context) { + @AfterAll + static final void printFailedTests() { out.println("\n========================="); try { // Exceptions should already have been added to FAILURES @@ -211,7 +218,7 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters } } - private String[] uris() { + private static String[] uris() { return new String[] { http3URI_fixed, http3URI_chunk, @@ -222,8 +229,7 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters }; } - @DataProvider(name = "sanity") - public Object[][] sanity() { + public static Object[][] sanity() { String[] uris = uris(); Object[][] result = new Object[uris.length * 2][]; @@ -252,7 +258,7 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters } } - private Object[][] variants(List throwers) { + private static Object[][] variants(List throwers) { String[] uris = uris(); // reduce traces by always using the same client if // stopAfterFirstFailure is requested. @@ -272,27 +278,19 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters return result; } - @DataProvider(name = "ioVariants") - public Object[][] ioVariants(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] ioVariants() { return variants(List.of( new UncheckedIOExceptionThrower())); } - @DataProvider(name = "customVariants") - public Object[][] customVariants(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] customVariants() { return variants(List.of( new UncheckedCustomExceptionThrower())); } - private HttpClient makeNewClient() { + private static HttpClient makeNewClient() { clientCount.incrementAndGet(); - return TRACKER.track(newClientBuilderForH3() + return TRACKER.track(HttpServerAdapters.createClientBuilderForH3() .version(HTTP_3) .proxy(HttpClient.Builder.NO_PROXY) .executor(executor) @@ -300,11 +298,11 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters .build()); } - HttpClient newHttpClient(boolean share) { + static HttpClient newHttpClient(boolean share) { if (!share) return makeNewClient(); HttpClient shared = sharedClient; if (shared != null) return shared; - synchronized (this) { + synchronized (AbstractThrowingPushPromises.class) { shared = sharedClient; if (shared == null) { shared = sharedClient = makeNewClient(); @@ -313,15 +311,15 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters } } - Http3DiscoveryMode config(String uri) { + static Http3DiscoveryMode config(String uri) { return uri.contains("/http3/") ? HTTP_3_URI_ONLY : null; } - Version version(String uri) { + static Version version(String uri) { return uri.contains("/http3/") ? HTTP_3 : HTTP_2; } - HttpRequest request(String uri) { + static HttpRequest request(String uri) { var builder = HttpRequest.newBuilder(URI.create(uri)) .version(version(uri)); var config = config(uri); @@ -358,15 +356,15 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters HttpResponse> response = client.sendAsync(req, BodyHandlers.ofLines(), pushHandler).get(); String body = response.body().collect(Collectors.joining("|")); - assertEquals(URI.create(body).getPath(), URI.create(uri).getPath()); + assertEquals(URI.create(uri).getPath(), URI.create(body).getPath()); for (HttpRequest promised : pushPromises.keySet()) { out.printf("%s Received promise: %s%n\tresponse: %s%n", now(), promised, pushPromises.get(promised).get()); String promisedBody = pushPromises.get(promised).get().body() .collect(Collectors.joining("|")); - assertEquals(promisedBody, promised.uri().toASCIIString()); + assertEquals(promised.uri().toASCIIString(), promisedBody); } - assertEquals(pushPromises.size(), 3); + assertEquals(3, pushPromises.size()); if (!sameClient) { // Wait for the client to be garbage collected. // we use the ReferenceTracker API rather than HttpClient::close here, @@ -429,7 +427,6 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters Finisher finisher, Thrower thrower) throws Exception { - checkSkip(); out.printf("%n%s%s%n", now(), name); try { testThrowing(uri, sameClient, handlers, finisher, thrower); @@ -603,9 +600,9 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters default: expectedCount = 3; } - assertEquals(promises.size(), expectedCount, + assertEquals(expectedCount, promises.size(), "bad promise count for " + reqURI + " with " + w); - assertEquals(result, List.of(reqURI.toASCIIString())); + assertEquals(List.of(reqURI.toASCIIString()), result); return result; } @@ -758,12 +755,8 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters } - @BeforeTest - public void setup() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); - + @BeforeAll + public static void setup() throws Exception { // HTTP/2 HttpTestHandler fixedLengthHandler = new HTTP_FixedLengthHandler(); HttpTestHandler chunkedHandler = new HTTP_ChunkedHandler(); @@ -792,8 +785,8 @@ public abstract class AbstractThrowingPushPromises implements HttpServerAdapters http3TestServer.start(); } - @AfterTest - public void teardown() throws Exception { + @AfterAll + public static void teardown() throws Exception { String sharedClientName = sharedClient == null ? null : sharedClient.toString(); sharedClient = null; diff --git a/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java b/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java index 0dc808b8bb2..33063775243 100644 --- a/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java +++ b/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java @@ -23,14 +23,6 @@ import jdk.httpclient.test.lib.http3.Http3TestServer; import jdk.test.lib.net.SimpleSSLContext; -import org.testng.ITestContext; -import org.testng.ITestResult; -import org.testng.SkipException; -import org.testng.annotations.AfterTest; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; import javax.net.ssl.SSLContext; import java.io.BufferedReader; @@ -49,7 +41,6 @@ import java.net.http.HttpResponse.BodyHandlers; import java.net.http.HttpResponse.BodySubscriber; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -76,28 +67,37 @@ import static java.net.http.HttpClient.Version.HTTP_2; import static java.net.http.HttpClient.Version.HTTP_3; 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.assertTrue; +import org.junit.jupiter.api.AfterAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +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.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.extension.TestWatcher; public abstract class AbstractThrowingSubscribers implements HttpServerAdapters { - SSLContext sslContext; - HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] - HttpTestServer httpsTestServer; // HTTPS/1.1 - HttpTestServer http2TestServer; // HTTP/2 ( h2c ) - HttpTestServer https2TestServer; // HTTP/2 ( h2 ) - HttpTestServer http3TestServer; // HTTP/3 ( h3 ) - String httpURI_fixed; - String httpURI_chunk; - String httpsURI_fixed; - String httpsURI_chunk; - String http2URI_fixed; - String http2URI_chunk; - String https2URI_fixed; - String https2URI_chunk; - String http3URI_fixed; - String http3URI_chunk; - String http3URI_head; + 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 ) + static HttpTestServer https2TestServer; // HTTP/2 ( h2 ) + static HttpTestServer http3TestServer; // HTTP/3 ( h3 ) + static String httpURI_fixed; + static String httpURI_chunk; + static String httpsURI_fixed; + static String httpsURI_chunk; + static String http2URI_fixed; + static String http2URI_chunk; + static String https2URI_fixed; + static String https2URI_chunk; + static String http3URI_fixed; + static String http3URI_chunk; + static String http3URI_head; static final int ITERATION_COUNT = 1; static final int REPEAT_RESPONSE = 3; @@ -116,8 +116,34 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan); } - final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; - private volatile HttpClient sharedClient; + static final class TestStopper implements TestWatcher, BeforeEachCallback { + final AtomicReference failed = new AtomicReference<>(); + TestStopper() { } + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + if (stopAfterFirstFailure()) { + String msg = "Aborting due to: " + cause; + failed.compareAndSet(null, msg); + FAILURES.putIfAbsent(context.getDisplayName(), cause); + System.out.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + System.err.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + } + } + + @Override + public void beforeEach(ExtensionContext context) { + String msg = failed.get(); + Assumptions.assumeTrue(msg == null, msg); + } + } + + @RegisterExtension + static final TestStopper stopper = new TestStopper(); + + static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; + private static volatile HttpClient sharedClient; static class TestExecutor implements Executor { final AtomicLong tasks = new AtomicLong(); @@ -143,21 +169,10 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters } } - protected boolean stopAfterFirstFailure() { + protected static boolean stopAfterFirstFailure() { return Boolean.getBoolean("jdk.internal.httpclient.debug"); } - final AtomicReference skiptests = new AtomicReference<>(); - void checkSkip() { - var skip = skiptests.get(); - if (skip != null) throw skip; - } - static String name(ITestResult result) { - var params = result.getParameters(); - return result.getName() - + (params == null ? "()" : Arrays.toString(result.getParameters())); - } - static Version version(String uri) { if (uri.contains("/http1/") || uri.contains("/https1/")) return HTTP_1_1; @@ -168,7 +183,7 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters return null; } - HttpRequest.Builder newRequestBuilder(String uri) { + static HttpRequest.Builder newRequestBuilder(String uri) { var builder = HttpRequest.newBuilder(URI.create(uri)); if (version(uri) == HTTP_3) { builder.version(HTTP_3); @@ -177,7 +192,7 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters return builder; } - HttpResponse headRequest(HttpClient client) + static HttpResponse headRequest(HttpClient client) throws IOException, InterruptedException { System.out.println("\n" + now() + "--- Sending HEAD request ----\n"); @@ -186,26 +201,15 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters var request = newRequestBuilder(http3URI_head) .HEAD().version(HTTP_2).build(); var response = client.send(request, BodyHandlers.ofString()); - assertEquals(response.statusCode(), 200); - assertEquals(response.version(), HTTP_2); + assertEquals(200, response.statusCode()); + assertEquals(HTTP_2, response.version()); System.out.println("\n" + now() + "--- HEAD request succeeded ----\n"); System.err.println("\n" + now() + "--- HEAD request succeeded ----\n"); return response; } - @BeforeMethod - void beforeMethod(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - if (skiptests.get() == null) { - SkipException skip = new SkipException("some tests failed"); - skip.setStackTrace(new StackTraceElement[0]); - skiptests.compareAndSet(null, skip); - } - } - } - - @AfterClass - static final void printFailedTests(ITestContext context) { + @AfterAll + static final void printFailedTests() { out.println("\n========================="); try { // Exceptions should already have been added to FAILURES @@ -230,7 +234,7 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters } } - private String[] uris() { + private static String[] uris() { return new String[] { http3URI_fixed, http3URI_chunk, @@ -245,10 +249,9 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters }; } - static AtomicLong URICOUNT = new AtomicLong(); + static final AtomicLong URICOUNT = new AtomicLong(); - @DataProvider(name = "sanity") - public Object[][] sanity() { + public static Object[][] sanity() { String[] uris = uris(); Object[][] result = new Object[uris.length * 2][]; int i = 0; @@ -261,11 +264,7 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters return result; } - @DataProvider(name = "variants") - public Object[][] variants(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] variants() { String[] uris = uris(); Object[][] result = new Object[uris.length * 2 * 2][]; int i = 0; @@ -282,9 +281,9 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters return result; } - private HttpClient makeNewClient() { + private static HttpClient makeNewClient() { clientCount.incrementAndGet(); - HttpClient client = newClientBuilderForH3() + HttpClient client = HttpServerAdapters.createClientBuilderForH3() .proxy(HttpClient.Builder.NO_PROXY) .executor(executor) .sslContext(sslContext) @@ -292,11 +291,11 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters return TRACKER.track(client); } - HttpClient newHttpClient(boolean share) { + static HttpClient newHttpClient(boolean share) { if (!share) return makeNewClient(); HttpClient shared = sharedClient; if (shared != null) return shared; - synchronized (this) { + synchronized (AbstractThrowingSubscribers.class) { shared = sharedClient; if (shared == null) { shared = sharedClient = makeNewClient(); @@ -357,7 +356,7 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters HttpResponse response = client.send(req, handler); String body = response.body(); Stream.of(body.split("\n")).forEach(u -> - assertEquals(URI.create(u).getPath(), URI.create(uri2).getPath())); + assertEquals(URI.create(uri2).getPath(), URI.create(u).getPath())); if (!sameClient) { // Wait for the client to be garbage collected. // we use the ReferenceTracker API rather than HttpClient::close here, @@ -469,7 +468,6 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters boolean async, EnumSet excludes) throws Exception { - checkSkip(); out.printf("%n%s%s%n", now(), name); try { testThrowing(uri, sameClient, handlers, finisher, thrower, async, excludes); @@ -551,7 +549,6 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters if (error != null) throw error; System.out.println(now() + "operation finished normally: " + tracker.getName()); System.err.println(now() + "operation finished normally: " + tracker.getName()); - } } } @@ -819,15 +816,11 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters } - @BeforeTest - public void setup() throws Exception { + @BeforeAll + public static void setup() throws Exception { 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 @@ -902,8 +895,8 @@ public abstract class AbstractThrowingSubscribers implements HttpServerAdapters System.err.println(now() + "setup done"); } - @AfterTest - public void teardown() throws Exception { + @AfterAll + public static void teardown() throws Exception { System.out.println(now() + "teardown"); System.err.println(now() + "teardown"); 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/ThrowingPublishersCustomAfterCancel.java b/test/jdk/java/net/httpclient/ThrowingPublishersCustomAfterCancel.java index 796c0b8df02..2c1aa2fd9b4 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersCustomAfterCancel.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersCustomAfterCancel.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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersCustomAfterCancel * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersCustomAfterCancel */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersCustomAfterCancel extends AbstractThrowingPublishers { - @Test(dataProvider = "afterCancelProviderCustom") + @ParameterizedTest + @MethodSource("afterCancelProviderCustom") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersCustomBeforeCancel.java b/test/jdk/java/net/httpclient/ThrowingPublishersCustomBeforeCancel.java index 06343d222b8..ba734185464 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersCustomBeforeCancel.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersCustomBeforeCancel.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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersCustomBeforeCancel * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersCustomBeforeCancel */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersCustomBeforeCancel extends AbstractThrowingPublishers { - @Test(dataProvider = "beforeCancelProviderCustom") + @ParameterizedTest + @MethodSource("beforeCancelProviderCustom") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersIOAfterCancel.java b/test/jdk/java/net/httpclient/ThrowingPublishersIOAfterCancel.java index 7ed649b2546..a5e819942b4 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersIOAfterCancel.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersIOAfterCancel.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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersIOAfterCancel * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersIOAfterCancel */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersIOAfterCancel extends AbstractThrowingPublishers { - @Test(dataProvider = "afterCancelProviderIO") + @ParameterizedTest + @MethodSource("afterCancelProviderIO") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersIOBeforeCancel.java b/test/jdk/java/net/httpclient/ThrowingPublishersIOBeforeCancel.java index 3be2eb061cc..e68f83052bd 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersIOBeforeCancel.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersIOBeforeCancel.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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersIOBeforeCancel * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersIOBeforeCancel */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersIOBeforeCancel extends AbstractThrowingPublishers { - @Test(dataProvider = "beforeCancelProviderIO") + @ParameterizedTest + @MethodSource("beforeCancelProviderIO") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersInNextRequest.java b/test/jdk/java/net/httpclient/ThrowingPublishersInNextRequest.java index eb07b359fc9..62d06fd6019 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersInNextRequest.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersInNextRequest.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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersInNextRequest * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersInNextRequest */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersInNextRequest extends AbstractThrowingPublishers { - @Test(dataProvider = "nextRequestProvider") + @ParameterizedTest + @MethodSource("nextRequestProvider") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersInRequest.java b/test/jdk/java/net/httpclient/ThrowingPublishersInRequest.java index ef05e4e0da6..f863f3598ed 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersInRequest.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersInRequest.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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersInRequest * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersInRequest */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersInRequest extends AbstractThrowingPublishers { - @Test(dataProvider = "requestProvider") + @ParameterizedTest + @MethodSource("requestProvider") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersInSubscribe.java b/test/jdk/java/net/httpclient/ThrowingPublishersInSubscribe.java index f14c5167024..ce1ad89dc05 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersInSubscribe.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersInSubscribe.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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersInSubscribe * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersInSubscribe */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersInSubscribe extends AbstractThrowingPublishers { - @Test(dataProvider = "subscribeProvider") + @ParameterizedTest + @MethodSource("subscribeProvider") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersSanity.java b/test/jdk/java/net/httpclient/ThrowingPublishersSanity.java index 30549083310..eee2f9ab7fb 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersSanity.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersSanity.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 @@ -29,16 +29,18 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersSanity * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersSanity */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersSanity extends AbstractThrowingPublishers { - @Test(dataProvider = "sanity") + @ParameterizedTest + @MethodSource("sanity") public void testSanity(String uri, boolean sameClient) throws Exception { super.testSanityImpl(uri,sameClient); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamCustom.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamCustom.java index 0b66a8e913e..797507ac7ad 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamCustom.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamCustom.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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsInputStreamCustom * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsInputStreamCustom + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsInputStreamCustom */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsInputStreamCustom extends AbstractThrowingPushPromises { - @Test(dataProvider = "customVariants") + @ParameterizedTest + @MethodSource("customVariants") public void testThrowingAsInputStream(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsInputStreamImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamIO.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamIO.java index 89cf1162bc3..309f60c0f22 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamIO.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamIO.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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsInputStreamIO * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsInputStreamIO + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsInputStreamIO */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsInputStreamIO extends AbstractThrowingPushPromises { - @Test(dataProvider = "ioVariants") + @ParameterizedTest + @MethodSource("ioVariants") public void testThrowingAsInputStream(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsInputStreamImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesCustom.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesCustom.java index d1fb7d34258..77c87151e19 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesCustom.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesCustom.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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsLinesCustom * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsLinesCustom + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsLinesCustom */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsLinesCustom extends AbstractThrowingPushPromises { - @Test(dataProvider = "customVariants") + @ParameterizedTest + @MethodSource("customVariants") public void testThrowingAsLines(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsLinesImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesIO.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesIO.java index 88afaf3dbd5..69deeec533a 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesIO.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesIO.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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsLinesIO * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsLinesIO + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsLinesIO */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsLinesIO extends AbstractThrowingPushPromises { - @Test(dataProvider = "ioVariants") + @ParameterizedTest + @MethodSource("ioVariants") public void testThrowingAsLines(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsLinesImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringCustom.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringCustom.java index c40af0ab0b0..de38cf4f782 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringCustom.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringCustom.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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsStringCustom * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsStringCustom + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsStringCustom */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsStringCustom extends AbstractThrowingPushPromises { - @Test(dataProvider = "customVariants") + @ParameterizedTest + @MethodSource("customVariants") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsStringImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringIO.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringIO.java index 6485e82af8f..ec4d682d73f 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringIO.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringIO.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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsStringIO * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsStringIO + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsStringIO */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsStringIO extends AbstractThrowingPushPromises { - @Test(dataProvider = "ioVariants") + @ParameterizedTest + @MethodSource("ioVariants") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsStringImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesSanity.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesSanity.java index 7fdb6dcb19d..92f2ab3726d 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesSanity.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesSanity.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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesSanity * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesSanity + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesSanity */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesSanity extends AbstractThrowingPushPromises { - @Test(dataProvider = "sanity") + @ParameterizedTest + @MethodSource("sanity") public void testSanity(String uri, boolean sameClient) throws Exception { super.testSanityImpl(uri, sameClient); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStream.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStream.java index 35ac1fd3f9c..a4c0fc72004 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStream.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStream.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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsInputStream AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsInputStream + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsInputStream */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsInputStream extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsInputStream(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsInputStreamImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStreamAsync.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStreamAsync.java index db25ebaca3e..aec4641917c 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStreamAsync.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStreamAsync.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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsInputStreamAsync AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsInputStreamAsync + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsInputStreamAsync */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsInputStreamAsync extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsInputStreamAsync(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsInputStreamAsyncImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLimiting.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLimiting.java index 11ced214ece..603a8558856 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLimiting.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLimiting.java @@ -35,18 +35,20 @@ * ReferenceTracker * jdk.httpclient.test.lib.common.HttpServerAdapters * jdk.test.lib.net.SimpleSSLContext - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLimiting + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLimiting */ -import org.testng.annotations.Test; import java.net.http.HttpResponse; import java.util.function.Supplier; import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsLimiting extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void test(String uri, boolean sameClient, Thrower thrower) throws Exception { test(uri, sameClient, thrower, false); } diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLimitingAsync.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLimitingAsync.java index 00e00c12db5..e45c6d6487e 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLimitingAsync.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLimitingAsync.java @@ -35,15 +35,17 @@ * ReferenceTracker * jdk.httpclient.test.lib.common.HttpServerAdapters * jdk.test.lib.net.SimpleSSLContext - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLimitingAsync + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLimitingAsync */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsLimitingAsync extends ThrowingSubscribersAsLimiting { @Override - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void test(String uri, boolean sameClient, Thrower thrower) throws Exception { test(uri, sameClient, thrower, true); } diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLines.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLines.java index f303ef12b54..ba594166b72 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLines.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLines.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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsLines AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLines + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLines */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsLines extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsLines(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsLinesImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLinesAsync.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLinesAsync.java index 2e1fc942a73..a76ff882463 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLinesAsync.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLinesAsync.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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsLinesAsync AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLinesAsync + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLinesAsync */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsLinesAsync extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsLinesAsync(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsLinesAsyncImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsString.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsString.java index 56e444f09c2..ba550675096 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsString.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsString.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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsString AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsString + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsString */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsString extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsStringImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsStringAsync.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsStringAsync.java index 563fe39bd69..304d98e6939 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsStringAsync.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsStringAsync.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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsStringAsync AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsStringAsync + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsStringAsync */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsStringAsync extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsStringAsync(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsStringAsyncImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersSanity.java b/test/jdk/java/net/httpclient/ThrowingSubscribersSanity.java index c480d55e147..296e9151c9e 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersSanity.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersSanity.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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersSanity AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersSanity + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersSanity */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersSanity extends AbstractThrowingSubscribers { - @Test(dataProvider = "sanity") + @ParameterizedTest + @MethodSource("sanity") public void testSanity(String uri, boolean sameClient) throws Exception { super.testSanityImpl(uri, sameClient); 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/TimeoutResponseBodyTest.java b/test/jdk/java/net/httpclient/TimeoutResponseBodyTest.java new file mode 100644 index 00000000000..093885a6ba0 --- /dev/null +++ b/test/jdk/java/net/httpclient/TimeoutResponseBodyTest.java @@ -0,0 +1,285 @@ +/* + * 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. + */ + +import jdk.internal.net.http.common.Logger; +import jdk.internal.net.http.common.Utils; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.InputStream; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + +import static jdk.internal.net.http.HttpClientTimerAccess.assertNoResponseTimerEventRegistrations; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.fail; + +/* + * @test id=retriesDisabled + * @bug 8208693 + * @summary Verifies `HttpRequest::timeout` is effective for *response body* + * timeouts when all retry mechanisms are disabled. + * + * @library /test/lib + * /test/jdk/java/net/httpclient/lib + * access + * @build TimeoutResponseTestSupport + * java.net.http/jdk.internal.net.http.HttpClientTimerAccess + * jdk.httpclient.test.lib.common.HttpServerAdapters + * jdk.test.lib.net.SimpleSSLContext + * + * @run junit/othervm + * -Djdk.httpclient.auth.retrylimit=0 + * -Djdk.httpclient.disableRetryConnect + * -Djdk.httpclient.redirects.retrylimit=0 + * -Dtest.requestTimeoutMillis=1000 + * TimeoutResponseBodyTest + */ + +/* + * @test id=retriesEnabledForResponseFailure + * @bug 8208693 + * @summary Verifies `HttpRequest::timeout` is effective for *response body* + * timeouts, where some initial responses are intentionally configured + * to fail to trigger retries. + * + * @library /test/lib + * /test/jdk/java/net/httpclient/lib + * access + * @build TimeoutResponseTestSupport + * java.net.http/jdk.internal.net.http.HttpClientTimerAccess + * jdk.httpclient.test.lib.common.HttpServerAdapters + * jdk.test.lib.net.SimpleSSLContext + * + * @run junit/othervm + * -Djdk.httpclient.auth.retrylimit=0 + * -Djdk.httpclient.disableRetryConnect + * -Djdk.httpclient.redirects.retrylimit=3 + * -Dtest.requestTimeoutMillis=1000 + * -Dtest.responseFailureWaitDurationMillis=600 + * TimeoutResponseBodyTest + */ + +/** + * Verifies {@link HttpRequest#timeout() HttpRequest.timeout()} is effective + * for response body timeouts. + * + * @implNote + * + * Using a response body subscriber (i.e., {@link InputStream}) of type that + * allows gradual consumption of the response body after successfully building + * an {@link HttpResponse} instance to ensure timeouts are propagated even + * after the {@code HttpResponse} construction. + *

+ * Each test is provided a pristine ephemeral client to avoid any unexpected + * effects due to pooling. + */ +class TimeoutResponseBodyTest extends TimeoutResponseTestSupport { + + private static final Logger LOGGER = Utils.getDebugLogger( + TimeoutResponseBodyTest.class.getSimpleName()::toString, Utils.DEBUG); + + /** + * Tests timeouts using + * {@link HttpClient#send(HttpRequest, HttpResponse.BodyHandler) HttpClient::send} + * against a server blocking without delivering the response body. + */ + @ParameterizedTest + @MethodSource("serverRequestPairs") + void testSendOnMissingBody(ServerRequestPair pair) throws Exception { + + ServerRequestPair.SERVER_HANDLER_BEHAVIOUR = + ServerRequestPair.ServerHandlerBehaviour.BLOCK_BEFORE_BODY_DELIVERY; + + try (var client = pair.createClientWithEstablishedConnection()) { + assertTimeoutPreemptively(REQUEST_TIMEOUT.multipliedBy(2), () -> { + LOGGER.log("Sending the request"); + var response = client.send(pair.request(), HttpResponse.BodyHandlers.ofInputStream()); + LOGGER.log("Consuming the obtained response"); + verifyResponseBodyDoesNotArrive(response); + }); + LOGGER.log("Verifying the registered response timer events"); + assertNoResponseTimerEventRegistrations(client); + } + + } + + /** + * Tests timeouts using + * {@link HttpClient#sendAsync(HttpRequest, HttpResponse.BodyHandler) HttpClient::sendAsync} + * against a server blocking without delivering the response body. + */ + @ParameterizedTest + @MethodSource("serverRequestPairs") + void testSendAsyncOnMissingBody(ServerRequestPair pair) throws Exception { + + ServerRequestPair.SERVER_HANDLER_BEHAVIOUR = + ServerRequestPair.ServerHandlerBehaviour.BLOCK_BEFORE_BODY_DELIVERY; + + try (var client = pair.createClientWithEstablishedConnection()) { + assertTimeoutPreemptively(REQUEST_TIMEOUT.multipliedBy(2), () -> { + LOGGER.log("Sending the request asynchronously"); + var responseFuture = client.sendAsync(pair.request(), HttpResponse.BodyHandlers.ofInputStream()); + LOGGER.log("Obtaining the response"); + var response = responseFuture.get(); + LOGGER.log("Consuming the obtained response"); + verifyResponseBodyDoesNotArrive(response); + }); + LOGGER.log("Verifying the registered response timer events"); + assertNoResponseTimerEventRegistrations(client); + } + + } + + private static void verifyResponseBodyDoesNotArrive(HttpResponse response) { + assertEquals(200, response.statusCode()); + assertThrowsHttpTimeoutException(() -> { + try (var responseBodyStream = response.body()) { + var readByte = responseBodyStream.read(); + fail("Unexpected read byte: " + readByte); + } + }); + } + + /** + * Tests timeouts using + * {@link HttpClient#send(HttpRequest, HttpResponse.BodyHandler) HttpClient::send} + * against a server delivering the response body very slowly. + */ + @ParameterizedTest + @MethodSource("serverRequestPairs") + void testSendOnSlowBody(ServerRequestPair pair) throws Exception { + + ServerRequestPair.SERVER_HANDLER_BEHAVIOUR = + ServerRequestPair.ServerHandlerBehaviour.DELIVER_BODY_SLOWLY; + + try (var client = pair.createClientWithEstablishedConnection()) { + assertTimeoutPreemptively(REQUEST_TIMEOUT.multipliedBy(2), () -> { + LOGGER.log("Sending the request"); + var response = client.send(pair.request(), HttpResponse.BodyHandlers.ofInputStream()); + LOGGER.log("Consuming the obtained response"); + verifyResponseBodyArrivesSlow(response); + }); + LOGGER.log("Verifying the registered response timer events"); + assertNoResponseTimerEventRegistrations(client); + } + + } + + /** + * Tests timeouts using + * {@link HttpClient#sendAsync(HttpRequest, HttpResponse.BodyHandler) HttpClient::sendAsync} + * against a server delivering the response body very slowly. + */ + @ParameterizedTest + @MethodSource("serverRequestPairs") + void testSendAsyncOnSlowBody(ServerRequestPair pair) throws Exception { + + ServerRequestPair.SERVER_HANDLER_BEHAVIOUR = + ServerRequestPair.ServerHandlerBehaviour.DELIVER_BODY_SLOWLY; + + try (var client = pair.createClientWithEstablishedConnection()) { + assertTimeoutPreemptively(REQUEST_TIMEOUT.multipliedBy(2), () -> { + LOGGER.log("Sending the request asynchronously"); + var responseFuture = client.sendAsync(pair.request(), HttpResponse.BodyHandlers.ofInputStream()); + LOGGER.log("Obtaining the response"); + var response = responseFuture.get(); + LOGGER.log("Consuming the obtained response"); + verifyResponseBodyArrivesSlow(response); + }); + LOGGER.log("Verifying the registered response timer events"); + assertNoResponseTimerEventRegistrations(client); + } + + } + + private static void verifyResponseBodyArrivesSlow(HttpResponse response) { + assertEquals(200, response.statusCode()); + assertThrowsHttpTimeoutException(() -> { + try (var responseBodyStream = response.body()) { + int i = 0; + int l = ServerRequestPair.CONTENT_LENGTH; + for (; i < l; i++) { + LOGGER.log("Reading byte %s/%s", i, l); + var readByte = responseBodyStream.read(); + if (readByte < 0) { + break; + } + assertEquals(i, readByte); + } + fail("Should not have reached here! (i=%s)".formatted(i)); + } + }); + } + + /** + * Tests timeouts using + * {@link HttpClient#send(HttpRequest, HttpResponse.BodyHandler) HttpClient::send} + * against a server delivering 204, i.e., no content, which is handled + * through a specialized path served by {@code MultiExchange::handleNoBody}. + */ + @ParameterizedTest + @MethodSource("serverRequestPairs") + void testSendOnNoBody(ServerRequestPair pair) throws Exception { + + ServerRequestPair.SERVER_HANDLER_BEHAVIOUR = + ServerRequestPair.ServerHandlerBehaviour.DELIVER_NO_BODY; + + try (var client = pair.createClientWithEstablishedConnection()) { + assertTimeoutPreemptively(REQUEST_TIMEOUT.multipliedBy(2), () -> { + LOGGER.log("Sending the request"); + client.send(pair.request(), HttpResponse.BodyHandlers.discarding()); + }); + LOGGER.log("Verifying the registered response timer events"); + assertNoResponseTimerEventRegistrations(client); + } + + } + + /** + * Tests timeouts using + * {@link HttpClient#sendAsync(HttpRequest, HttpResponse.BodyHandler) HttpClient::sendAsync} + * against a server delivering 204, i.e., no content, which is handled + * through a specialized path served by {@code MultiExchange::handleNoBody}. + */ + @ParameterizedTest + @MethodSource("serverRequestPairs") + void testSendAsyncOnNoBody(ServerRequestPair pair) throws Exception { + + ServerRequestPair.SERVER_HANDLER_BEHAVIOUR = + ServerRequestPair.ServerHandlerBehaviour.DELIVER_NO_BODY; + + try (var client = pair.createClientWithEstablishedConnection()) { + assertTimeoutPreemptively(REQUEST_TIMEOUT.multipliedBy(2), () -> { + LOGGER.log("Sending the request asynchronously"); + client.sendAsync(pair.request(), HttpResponse.BodyHandlers.discarding()).get(); + }); + LOGGER.log("Verifying the registered response timer events"); + assertNoResponseTimerEventRegistrations(client); + } + + } + +} diff --git a/test/jdk/java/net/httpclient/TimeoutResponseHeaderTest.java b/test/jdk/java/net/httpclient/TimeoutResponseHeaderTest.java new file mode 100644 index 00000000000..ab562f8eab8 --- /dev/null +++ b/test/jdk/java/net/httpclient/TimeoutResponseHeaderTest.java @@ -0,0 +1,138 @@ +/* + * 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. + */ + +import jdk.internal.net.http.common.Logger; +import jdk.internal.net.http.common.Utils; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + +import static jdk.internal.net.http.HttpClientTimerAccess.assertNoResponseTimerEventRegistrations; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +/* + * @test id=retriesDisabled + * @bug 8208693 + * @summary Verifies `HttpRequest::timeout` is effective for *response header* + * timeouts when all retry mechanisms are disabled. + * + * @library /test/jdk/java/net/httpclient/lib + * /test/lib + * access + * @build TimeoutResponseTestSupport + * java.net.http/jdk.internal.net.http.HttpClientTimerAccess + * jdk.httpclient.test.lib.common.HttpServerAdapters + * jdk.test.lib.net.SimpleSSLContext + * + * @run junit/othervm + * -Djdk.httpclient.auth.retrylimit=0 + * -Djdk.httpclient.disableRetryConnect + * -Djdk.httpclient.redirects.retrylimit=0 + * -Dtest.requestTimeoutMillis=1000 + * TimeoutResponseHeaderTest + */ + +/* + * @test id=retriesEnabledForResponseFailure + * @bug 8208693 + * @summary Verifies `HttpRequest::timeout` is effective for *response header* + * timeouts, where some initial responses are intentionally configured + * to fail to trigger retries. + * + * @library /test/jdk/java/net/httpclient/lib + * /test/lib + * access + * @build TimeoutResponseTestSupport + * java.net.http/jdk.internal.net.http.HttpClientTimerAccess + * jdk.httpclient.test.lib.common.HttpServerAdapters + * jdk.test.lib.net.SimpleSSLContext + * + * @run junit/othervm + * -Djdk.httpclient.auth.retrylimit=0 + * -Djdk.httpclient.disableRetryConnect + * -Djdk.httpclient.redirects.retrylimit=3 + * -Dtest.requestTimeoutMillis=1000 + * -Dtest.responseFailureWaitDurationMillis=600 + * TimeoutResponseHeaderTest + */ + +/** + * Verifies {@link HttpRequest#timeout() HttpRequest.timeout()} is effective + * for response header timeouts. + */ +class TimeoutResponseHeaderTest extends TimeoutResponseTestSupport { + + private static final Logger LOGGER = Utils.getDebugLogger( + TimeoutResponseHeaderTest.class.getSimpleName()::toString, Utils.DEBUG); + + static { + ServerRequestPair.SERVER_HANDLER_BEHAVIOUR = + ServerRequestPair.ServerHandlerBehaviour.BLOCK_BEFORE_HEADER_DELIVERY; + } + + /** + * Tests timeouts using + * {@link HttpClient#send(HttpRequest, HttpResponse.BodyHandler) HttpClient::send} + * against a server blocking without delivering any response headers. + */ + @ParameterizedTest + @MethodSource("serverRequestPairs") + void testSend(ServerRequestPair pair) throws Exception { + try (var client = pair.createClientWithEstablishedConnection()) { + assertTimeoutPreemptively( + REQUEST_TIMEOUT.multipliedBy(2), + () -> assertThrowsHttpTimeoutException(() -> { + LOGGER.log("Sending the request"); + client.send(pair.request(), HttpResponse.BodyHandlers.discarding()); + })); + LOGGER.log("Verifying the registered response timer events"); + assertNoResponseTimerEventRegistrations(client); + } + } + + /** + * Tests timeouts using + * {@link HttpClient#sendAsync(HttpRequest, HttpResponse.BodyHandler) HttpClient::sendAsync} + * against a server blocking without delivering any response headers. + */ + @ParameterizedTest + @MethodSource("serverRequestPairs") + void testSendAsync(ServerRequestPair pair) throws Exception { + try (var client = pair.createClientWithEstablishedConnection()) { + assertTimeoutPreemptively(REQUEST_TIMEOUT.multipliedBy(2), () -> { + LOGGER.log("Sending the request asynchronously"); + var responseFuture = client.sendAsync(pair.request(), HttpResponse.BodyHandlers.discarding()); + assertThrowsHttpTimeoutException(() -> { + LOGGER.log("Obtaining the response"); + responseFuture.get(); + }); + }); + LOGGER.log("Verifying the registered response timer events"); + assertNoResponseTimerEventRegistrations(client); + } + } + +} diff --git a/test/jdk/java/net/httpclient/TimeoutResponseTestSupport.java b/test/jdk/java/net/httpclient/TimeoutResponseTestSupport.java new file mode 100644 index 00000000000..67b993eef0b --- /dev/null +++ b/test/jdk/java/net/httpclient/TimeoutResponseTestSupport.java @@ -0,0 +1,407 @@ +/* + * 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. + */ + +import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestExchange; +import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestHandler; +import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestServer; +import jdk.internal.net.http.common.Logger; +import jdk.internal.net.http.common.Utils; +import jdk.internal.net.http.frame.ErrorFrame; +import jdk.internal.net.http.http3.Http3Error; +import jdk.test.lib.net.SimpleSSLContext; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.function.Executable; + +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpClient.Version; +import java.net.http.HttpOption; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpTimeoutException; +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; + +import static java.net.http.HttpClient.Builder.NO_PROXY; +import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY; +import static jdk.httpclient.test.lib.common.HttpServerAdapters.createClientBuilderFor; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Utilities for {@code TimeoutResponse*Test}s. + * + * @see TimeoutResponseBodyTest Server response body timeout tests + * @see TimeoutResponseHeaderTest Server response header timeout tests + * @see TimeoutBasic Server connection timeout tests + */ +public class TimeoutResponseTestSupport { + + private static final String CLASS_NAME = TimeoutResponseTestSupport.class.getSimpleName(); + + private static final Logger LOGGER = Utils.getDebugLogger(CLASS_NAME::toString, Utils.DEBUG); + + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); + + protected static final Duration REQUEST_TIMEOUT = + Duration.ofMillis(Long.parseLong(System.getProperty("test.requestTimeoutMillis"))); + + static { + assertTrue( + REQUEST_TIMEOUT.isPositive(), + "was expecting `test.requestTimeoutMillis > 0`, found: " + REQUEST_TIMEOUT); + } + + protected static final int RETRY_LIMIT = + Integer.parseInt(System.getProperty("jdk.httpclient.redirects.retrylimit", "0")); + + private static final long RESPONSE_FAILURE_WAIT_DURATION_MILLIS = + Long.parseLong(System.getProperty("test.responseFailureWaitDurationMillis", "0")); + + static { + if (RETRY_LIMIT > 0) { + + // Verify that response failure wait duration is provided + if (RESPONSE_FAILURE_WAIT_DURATION_MILLIS <= 0) { + var message = String.format( + "`jdk.httpclient.redirects.retrylimit` (%s) is greater than zero. " + + "`test.responseFailureWaitDurationMillis` (%s) must be greater than zero too.", + RETRY_LIMIT, RESPONSE_FAILURE_WAIT_DURATION_MILLIS); + throw new AssertionError(message); + } + + // Verify that the total response failure waits exceed the request timeout + var totalResponseFailureWaitDuration = Duration + .ofMillis(RESPONSE_FAILURE_WAIT_DURATION_MILLIS) + .multipliedBy(RETRY_LIMIT); + if (totalResponseFailureWaitDuration.compareTo(REQUEST_TIMEOUT) <= 0) { + var message = ("`test.responseFailureWaitDurationMillis * jdk.httpclient.redirects.retrylimit` (%s * %s = %s) " + + "must be greater than `test.requestTimeoutMillis` (%s)") + .formatted( + RESPONSE_FAILURE_WAIT_DURATION_MILLIS, + RETRY_LIMIT, + totalResponseFailureWaitDuration, + REQUEST_TIMEOUT); + throw new AssertionError(message); + } + + } + } + + protected static final ServerRequestPair + HTTP1 = ServerRequestPair.of(Version.HTTP_1_1, false), + HTTPS1 = ServerRequestPair.of(Version.HTTP_1_1, true), + HTTP2 = ServerRequestPair.of(Version.HTTP_2, false), + HTTPS2 = ServerRequestPair.of(Version.HTTP_2, true), + HTTP3 = ServerRequestPair.of(Version.HTTP_3, true); + + protected record ServerRequestPair(HttpTestServer server, HttpRequest request, boolean secure) { + + private static final ExecutorService EXECUTOR = Executors.newVirtualThreadPerTaskExecutor(); + + private static final CountDownLatch SHUT_DOWN_LATCH = new CountDownLatch(1); + + private static final AtomicInteger SERVER_COUNTER = new AtomicInteger(); + + /** + * An arbitrary content length to cause the client wait for it. + * It just needs to be greater than zero, and big enough to trigger a timeout when delivered slowly. + */ + public static final int CONTENT_LENGTH = 1234; + + public enum ServerHandlerBehaviour { + BLOCK_BEFORE_HEADER_DELIVERY, + BLOCK_BEFORE_BODY_DELIVERY, + DELIVER_BODY_SLOWLY, + DELIVER_NO_BODY + } + + public static volatile ServerHandlerBehaviour SERVER_HANDLER_BEHAVIOUR; + + public static volatile int SERVER_HANDLER_PENDING_FAILURE_COUNT = 0; + + private static ServerRequestPair of(Version version, boolean secure) { + + // Create the server and the request URI + var sslContext = secure ? SSL_CONTEXT : null; + var serverId = "" + SERVER_COUNTER.getAndIncrement(); + var server = createServer(version, sslContext); + server.getVersion(); + var handlerPath = "/%s/".formatted(CLASS_NAME); + var requestUriScheme = secure ? "https" : "http"; + var requestUri = URI.create("%s://%s%s-".formatted(requestUriScheme, server.serverAuthority(), handlerPath)); + + // Register the request handler + server.addHandler(createServerHandler(serverId), handlerPath); + + // Create the request + var request = createRequestBuilder(requestUri, version).timeout(REQUEST_TIMEOUT).build(); + + // Create the pair + var pair = new ServerRequestPair(server, request, secure); + pair.server.start(); + LOGGER.log("Server[%s] is started at `%s`", serverId, server.serverAuthority()); + return pair; + + } + + private static HttpTestServer createServer(Version version, SSLContext sslContext) { + try { + return switch (version) { + case HTTP_1_1, HTTP_2 -> HttpTestServer.create(version, sslContext, EXECUTOR); + case HTTP_3 -> HttpTestServer.create(HTTP_3_URI_ONLY, sslContext, EXECUTOR); + }; + } catch (IOException exception) { + throw new UncheckedIOException(exception); + } + } + + private static HttpTestHandler createServerHandler(String serverId) { + return (exchange) -> { + var connectionKey = exchange.getConnectionKey(); + LOGGER.log( + "Server[%s] has received request %s", + serverId, Map.of("connectionKey", connectionKey)); + try (exchange) { + + // Short-circuit on `HEAD` requests. + // They are used for admitting established connections to the pool. + if ("HEAD".equals(exchange.getRequestMethod())) { + LOGGER.log( + "Server[%s] is responding to the `HEAD` request %s", + serverId, Map.of("connectionKey", connectionKey)); + exchange.sendResponseHeaders(200, 0); + return; + } + + // Short-circuit if instructed to fail + synchronized (ServerRequestPair.class) { + if (SERVER_HANDLER_PENDING_FAILURE_COUNT > 0) { + LOGGER.log( + "Server[%s] is prematurely failing as instructed %s", + serverId, + Map.of( + "connectionKey", connectionKey, + "SERVER_HANDLER_PENDING_FAILURE_COUNT", SERVER_HANDLER_PENDING_FAILURE_COUNT)); + // Closing the exchange will trigger an `END_STREAM` without a headers frame. + // This is a protocol violation, hence we must reset the stream first. + // We are doing so using by rejecting the stream, which is known to make the client retry. + if (Version.HTTP_2.equals(exchange.getExchangeVersion())) { + exchange.resetStream(ErrorFrame.REFUSED_STREAM); + } else if (Version.HTTP_3.equals(exchange.getExchangeVersion())) { + exchange.resetStream(Http3Error.H3_REQUEST_REJECTED.code()); + } + SERVER_HANDLER_PENDING_FAILURE_COUNT--; + return; + } + } + + switch (SERVER_HANDLER_BEHAVIOUR) { + + case BLOCK_BEFORE_HEADER_DELIVERY -> sleepIndefinitely(serverId, connectionKey); + + case BLOCK_BEFORE_BODY_DELIVERY -> { + sendResponseHeaders(serverId, exchange, connectionKey); + sleepIndefinitely(serverId, connectionKey); + } + + case DELIVER_BODY_SLOWLY -> { + sendResponseHeaders(serverId, exchange, connectionKey); + sendResponseBodySlowly(serverId, exchange, connectionKey); + } + + case DELIVER_NO_BODY -> sendResponseHeaders(serverId, exchange, connectionKey, 204, 0); + + } + + } catch (Exception exception) { + var message = String.format( + "Server[%s] has failed! %s", + serverId, Map.of("connectionKey", connectionKey)); + LOGGER.log(System.Logger.Level.ERROR, message, exception); + if (exception instanceof InterruptedException) { + // Restore the interrupt + Thread.currentThread().interrupt(); + } + throw new RuntimeException(message, exception); + } + }; + } + + private static void sleepIndefinitely(String serverId, String connectionKey) throws InterruptedException { + LOGGER.log("Server[%s] is sleeping %s", serverId, Map.of("connectionKey", connectionKey)); + SHUT_DOWN_LATCH.await(); + } + + private static void sendResponseHeaders(String serverId, HttpTestExchange exchange, String connectionKey) + throws IOException { + sendResponseHeaders(serverId, exchange, connectionKey, 200, CONTENT_LENGTH); + } + + private static void sendResponseHeaders( + String serverId, + HttpTestExchange exchange, + String connectionKey, + int statusCode, + long contentLength) + throws IOException { + LOGGER.log("Server[%s] is sending headers %s", serverId, Map.of("connectionKey", connectionKey)); + exchange.sendResponseHeaders(statusCode, contentLength); + // Force the headers to be flushed + exchange.getResponseBody().flush(); + } + + private static void sendResponseBodySlowly(String serverId, HttpTestExchange exchange, String connectionKey) + throws Exception { + var perBytePauseDuration = Duration.ofMillis(100); + assertTrue( + perBytePauseDuration.multipliedBy(CONTENT_LENGTH).compareTo(REQUEST_TIMEOUT) > 0, + "Per-byte pause duration (%s) must be long enough to exceed the timeout (%s) when delivering the content (%s bytes)".formatted( + perBytePauseDuration, REQUEST_TIMEOUT, CONTENT_LENGTH)); + try (var responseBody = exchange.getResponseBody()) { + for (int i = 0; i < CONTENT_LENGTH; i++) { + LOGGER.log( + "Server[%s] is sending the body %s/%s %s", + serverId, i, CONTENT_LENGTH, Map.of("connectionKey", connectionKey)); + responseBody.write(i); + responseBody.flush(); + Thread.sleep(perBytePauseDuration); + } + throw new AssertionError("Delivery should never have succeeded due to timeout!"); + } catch (IOException _) { + // Client's timeout mechanism is expected to short-circuit and cut the stream. + // Hence, discard I/O failures. + } + } + + public HttpClient createClientWithEstablishedConnection() throws IOException, InterruptedException { + var version = server.getVersion(); + var client = createClientBuilderFor(version) + .version(version) + .sslContext(SSL_CONTEXT) + .proxy(NO_PROXY) + .build(); + // Ensure an established connection is admitted to the pool. This + // helps to cross out any possibilities of a timeout before a + // request makes it to the server handler. For instance, consider + // HTTP/1.1 to HTTP/2 upgrades, or long-running TLS handshakes. + var headRequest = createRequestBuilder(request.uri(), version).HEAD().build(); + client.send(headRequest, HttpResponse.BodyHandlers.discarding()); + return client; + } + + private static HttpRequest.Builder createRequestBuilder(URI uri, Version version) { + var requestBuilder = HttpRequest.newBuilder(uri).version(version); + if (Version.HTTP_3.equals(version)) { + requestBuilder.setOption(HttpOption.H3_DISCOVERY, HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY); + } + return requestBuilder; + } + + @Override + public String toString() { + var version = server.getVersion(); + var versionString = version.toString(); + return switch (version) { + case HTTP_1_1, HTTP_2 -> secure ? versionString.replaceFirst("_", "S_") : versionString; + case HTTP_3 -> versionString; + }; + } + + } + + @AfterAll + static void closeServers() { + + // Terminate all handlers before shutting down the server, which would block otherwise. + ServerRequestPair.SHUT_DOWN_LATCH.countDown(); + ServerRequestPair.EXECUTOR.shutdown(); + + // Shut down servers + Exception[] exceptionRef = {null}; + serverRequestPairs() + .forEach(pair -> { + try { + pair.server.stop(); + } catch (Exception exception) { + if (exceptionRef[0] == null) { + exceptionRef[0] = exception; + } else { + exceptionRef[0].addSuppressed(exception); + } + } + }); + if (exceptionRef[0] != null) { + throw new RuntimeException("failed closing one or more server resources", exceptionRef[0]); + } + + } + + /** + * Configures how many times the handler should fail. + */ + @BeforeEach + void resetServerHandlerFailureIndex() { + ServerRequestPair.SERVER_HANDLER_PENDING_FAILURE_COUNT = Math.max(0, RETRY_LIMIT - 1); + } + + /** + * Ensures that the handler has failed as many times as instructed. + */ + @AfterEach + void verifyServerHandlerFailureIndex() { + assertEquals(0, ServerRequestPair.SERVER_HANDLER_PENDING_FAILURE_COUNT); + } + + protected static Stream serverRequestPairs() { + return Stream.of(HTTP1, HTTPS1, HTTP2, HTTPS2, HTTP3); + } + + protected static void assertThrowsHttpTimeoutException(Executable executable) { + var rootException = assertThrows(Exception.class, executable); + // Due to intricacies involved in the way exceptions are generated and + // nested, there is no bullet-proof way to determine at which level of + // the causal chain an `HttpTimeoutException` will show up. Hence, we + // scan through the entire causal chain. + Throwable exception = rootException; + while (exception != null) { + if (exception instanceof HttpTimeoutException) { + return; + } + exception = exception.getCause(); + } + throw new AssertionError("was expecting an `HttpTimeoutException` in the causal chain", rootException); + } + +} 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/access/java.net.http/jdk/internal/net/http/HttpClientTimerAccess.java b/test/jdk/java/net/httpclient/access/java.net.http/jdk/internal/net/http/HttpClientTimerAccess.java new file mode 100644 index 00000000000..8bc1fac7b60 --- /dev/null +++ b/test/jdk/java/net/httpclient/access/java.net.http/jdk/internal/net/http/HttpClientTimerAccess.java @@ -0,0 +1,59 @@ +/* + * 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.internal.net.http; + +import java.net.http.HttpClient; + +public enum HttpClientTimerAccess {; + + public static void assertNoResponseTimerEventRegistrations(HttpClient client) { + assertTimerEventRegistrationCount(client, ResponseTimerEvent.class, 0); + } + + private static void assertTimerEventRegistrationCount( + HttpClient client, + Class clazz, + long expectedCount) { + var facade = assertType(HttpClientFacade.class, client); + var actualCount = facade.impl.timers().stream().filter(clazz::isInstance).count(); + if (actualCount != 0) { + throw new AssertionError( + "Found %s occurrences of `%s` timer event registrations while expecting %s.".formatted( + actualCount, clazz.getCanonicalName(), expectedCount)); + } + } + + private static T assertType(Class expectedType, Object instance) { + if (!expectedType.isInstance(instance)) { + var expectedTypeName = expectedType.getCanonicalName(); + var actualTypeName = instance != null ? instance.getClass().getCanonicalName() : null; + throw new AssertionError( + "Was expecting an instance of type `%s`, found: `%s`".formatted( + expectedTypeName, actualTypeName)); + } + @SuppressWarnings("unchecked") + T typedInstance = (T) instance; + return typedInstance; + } + +} diff --git a/test/jdk/java/net/httpclient/altsvc/altsvc-dns-hosts.txt b/test/jdk/java/net/httpclient/altsvc/altsvc-dns-hosts.txt index 67445f3b278..e91402dc6d9 100644 --- a/test/jdk/java/net/httpclient/altsvc/altsvc-dns-hosts.txt +++ b/test/jdk/java/net/httpclient/altsvc/altsvc-dns-hosts.txt @@ -1,4 +1,4 @@ -## 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 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/HpackBinaryTestDriver.java b/test/jdk/java/net/httpclient/http2/HpackBinaryTestDriver.java index 4c63e863fee..ed68695ec77 100644 --- a/test/jdk/java/net/httpclient/http2/HpackBinaryTestDriver.java +++ b/test/jdk/java/net/httpclient/http2/HpackBinaryTestDriver.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 @@ -29,6 +29,6 @@ * @compile/module=java.net.http jdk/internal/net/http/hpack/SpecHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/TestHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/BuffersTestingKit.java - * @run testng/othervm/timeout=240 java.net.http/jdk.internal.net.http.hpack.BinaryPrimitivesTest + * @run junit/othervm/timeout=240 java.net.http/jdk.internal.net.http.hpack.BinaryPrimitivesTest */ public class HpackBinaryTestDriver { } diff --git a/test/jdk/java/net/httpclient/http2/HpackCircularBufferDriver.java b/test/jdk/java/net/httpclient/http2/HpackCircularBufferDriver.java index 64ba1a3d22e..81ee9edc135 100644 --- a/test/jdk/java/net/httpclient/http2/HpackCircularBufferDriver.java +++ b/test/jdk/java/net/httpclient/http2/HpackCircularBufferDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, 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 @@ -29,6 +29,6 @@ * @compile/module=java.net.http jdk/internal/net/http/hpack/SpecHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/TestHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/BuffersTestingKit.java - * @run testng/othervm java.net.http/jdk.internal.net.http.hpack.CircularBufferTest + * @run junit/othervm java.net.http/jdk.internal.net.http.hpack.CircularBufferTest */ public class HpackCircularBufferDriver { } diff --git a/test/jdk/java/net/httpclient/http2/HpackDecoderDriver.java b/test/jdk/java/net/httpclient/http2/HpackDecoderDriver.java index 15bd92a1398..ca04e9895ab 100644 --- a/test/jdk/java/net/httpclient/http2/HpackDecoderDriver.java +++ b/test/jdk/java/net/httpclient/http2/HpackDecoderDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, 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 @@ -29,6 +29,6 @@ * @compile/module=java.net.http jdk/internal/net/http/hpack/SpecHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/TestHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/BuffersTestingKit.java - * @run testng/othervm java.net.http/jdk.internal.net.http.hpack.DecoderTest + * @run junit/othervm java.net.http/jdk.internal.net.http.hpack.DecoderTest */ public class HpackDecoderDriver { } diff --git a/test/jdk/java/net/httpclient/http2/HpackEncoderDriver.java b/test/jdk/java/net/httpclient/http2/HpackEncoderDriver.java index 12475ccbca9..b052e20f085 100644 --- a/test/jdk/java/net/httpclient/http2/HpackEncoderDriver.java +++ b/test/jdk/java/net/httpclient/http2/HpackEncoderDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, 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 @@ -29,6 +29,6 @@ * @compile/module=java.net.http jdk/internal/net/http/hpack/SpecHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/TestHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/BuffersTestingKit.java - * @run testng/othervm java.net.http/jdk.internal.net.http.hpack.EncoderTest + * @run junit/othervm java.net.http/jdk.internal.net.http.hpack.EncoderTest */ public class HpackEncoderDriver { } diff --git a/test/jdk/java/net/httpclient/http2/HpackHeaderTableDriver.java b/test/jdk/java/net/httpclient/http2/HpackHeaderTableDriver.java index ceb31da4f36..5cb1aa2bacc 100644 --- a/test/jdk/java/net/httpclient/http2/HpackHeaderTableDriver.java +++ b/test/jdk/java/net/httpclient/http2/HpackHeaderTableDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, 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 @@ -30,6 +30,6 @@ * @compile/module=java.net.http jdk/internal/net/http/hpack/SpecHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/TestHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/BuffersTestingKit.java - * @run testng/othervm java.net.http/jdk.internal.net.http.hpack.HeaderTableTest + * @run junit/othervm java.net.http/jdk.internal.net.http.hpack.HeaderTableTest */ public class HpackHeaderTableDriver { } diff --git a/test/jdk/java/net/httpclient/http2/HpackHuffmanDriver.java b/test/jdk/java/net/httpclient/http2/HpackHuffmanDriver.java index 650ed706c51..b4c6cff7a2f 100644 --- a/test/jdk/java/net/httpclient/http2/HpackHuffmanDriver.java +++ b/test/jdk/java/net/httpclient/http2/HpackHuffmanDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, 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 @@ -29,6 +29,6 @@ * @compile/module=java.net.http jdk/internal/net/http/hpack/SpecHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/TestHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/BuffersTestingKit.java - * @run testng/othervm/timeout=300 java.net.http/jdk.internal.net.http.hpack.HuffmanTest + * @run junit/othervm/timeout=300 java.net.http/jdk.internal.net.http.hpack.HuffmanTest */ public class HpackHuffmanDriver { } diff --git a/test/jdk/java/net/httpclient/http2/HpackTestHelper.java b/test/jdk/java/net/httpclient/http2/HpackTestHelper.java index 3faa669c57b..09de50eeef9 100644 --- a/test/jdk/java/net/httpclient/http2/HpackTestHelper.java +++ b/test/jdk/java/net/httpclient/http2/HpackTestHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, 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 @@ -29,6 +29,6 @@ * @compile/module=java.net.http jdk/internal/net/http/hpack/SpecHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/TestHelper.java * @compile/module=java.net.http jdk/internal/net/http/hpack/BuffersTestingKit.java - * @run testng/othervm java.net.http/jdk.internal.net.http.hpack.TestHelper + * @run junit/othervm java.net.http/jdk.internal.net.http.hpack.TestHelper */ public class HpackTestHelperDriver { } 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 3e4ee4864f5..3edf0b71305 100644 --- a/test/jdk/java/net/httpclient/http2/StreamFlowControlTest.java +++ b/test/jdk/java/net/httpclient/http2/StreamFlowControlTest.java @@ -76,12 +76,15 @@ 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; String https2URI; final AtomicInteger reqid = new AtomicInteger(); + final static int WINDOW = + Integer.getInteger("jdk.httpclient.windowsize", 2 * 16 * 1024); + @DataProvider(name = "variants") @@ -147,7 +150,11 @@ public class StreamFlowControlTest { // the window is exceeded... long wait = uri.startsWith("https://") ? 800 : 500; try (InputStream is = response.body()) { - sleep(wait); + byte[] discard = new byte[WINDOW/4]; + for (int j=0; j<2; j++) { + sleep(wait); + if (is.read(discard) < 0) break; + } is.readAllBytes(); } // we could fail here if we haven't waited long enough @@ -205,7 +212,11 @@ public class StreamFlowControlTest { sent.join(); long wait = uri.startsWith("https://") ? 800 : 350; try (InputStream is = response.body()) { - sleep(wait); + byte[] discard = new byte[WINDOW/4]; + for (int j=0; j<2; j++) { + sleep(wait); + if (is.read(discard) < 0) break; + } is.readAllBytes(); } // we could fail here if we haven't waited long enough @@ -255,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); @@ -316,17 +323,16 @@ public class StreamFlowControlTest { bytes = "no request body!" .repeat(100).getBytes(StandardCharsets.UTF_8); } - int window = Integer.getInteger("jdk.httpclient.windowsize", 2 * 16 * 1024); final int maxChunkSize; if (t instanceof FCHttp2TestExchange fct) { - maxChunkSize = Math.min(window, fct.conn.getMaxFrameSize()); + maxChunkSize = Math.min(WINDOW, fct.conn.getMaxFrameSize()); } else { - maxChunkSize = Math.min(window, SettingsFrame.MAX_FRAME_SIZE); + maxChunkSize = Math.min(WINDOW, SettingsFrame.MAX_FRAME_SIZE); } byte[] resp = bytes.length <= maxChunkSize ? bytes : Arrays.copyOfRange(bytes, 0, maxChunkSize); - int max = (window / resp.length) + 2; + int max = (WINDOW / resp.length) + 2; // send in chunks t.sendResponseHeaders(200, 0); for (int i = 0; i <= max; i++) { 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/http2/java.net.http/jdk/internal/net/http/hpack/BinaryPrimitivesTest.java b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/BinaryPrimitivesTest.java index d3cf1a59483..66c74565e92 100644 --- a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/BinaryPrimitivesTest.java +++ b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/BinaryPrimitivesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, 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 @@ -22,7 +22,6 @@ */ package jdk.internal.net.http.hpack; -import org.testng.annotations.Test; import java.io.IOException; import java.io.UncheckedIOException; @@ -33,10 +32,11 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; -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 static jdk.internal.net.http.hpack.BuffersTestingKit.*; import static jdk.internal.net.http.hpack.TestHelper.newRandom; +import org.junit.jupiter.api.Test; // // Some of the tests below overlap in what they test. This allows to diagnose @@ -96,7 +96,7 @@ public final class BinaryPrimitivesTest { totalCases++; maxFilling = Math.max(maxFilling, buf.remaining()); r.reset().configure(N).read(buf); - assertEquals(r.get(), expected); + assertEquals(expected, r.get()); buf.clear(); } } @@ -127,7 +127,7 @@ public final class BinaryPrimitivesTest { throw new UncheckedIOException(e); } } - assertEquals(r.get(), expected); + assertEquals(expected, r.get()); r.reset(); }); bb.clear(); @@ -167,7 +167,7 @@ public final class BinaryPrimitivesTest { throw new UncheckedIOException(e); } // TODO: check payload here - assertEquals(r.get(), expected); + assertEquals(expected, r.get()); w.reset(); r.reset(); bb.clear(); @@ -209,7 +209,7 @@ public final class BinaryPrimitivesTest { bytes.flip(); reader.read(bytes, chars); chars.flip(); - assertEquals(chars.toString(), expected); + assertEquals(expected, chars.toString()); reader.reset(); writer.reset(); } @@ -257,7 +257,7 @@ public final class BinaryPrimitivesTest { throw new UncheckedIOException(e); } chars.flip(); - assertEquals(chars.toString(), expected); + assertEquals(expected, chars.toString()); reader.reset(); writer.reset(); chars.clear(); @@ -301,7 +301,7 @@ public final class BinaryPrimitivesTest { buf.position(p0); } chars.flip(); - assertEquals(chars.toString(), expected); + assertEquals(expected, chars.toString()); reader.reset(); chars.clear(); }); @@ -356,7 +356,7 @@ public final class BinaryPrimitivesTest { } catch (IOException e) { throw new UncheckedIOException(e); } - assertEquals(reader.get(), expected); + assertEquals(expected, reader.get()); } private void verifyWrite(byte[] expected, int data, int N) { @@ -364,6 +364,6 @@ public final class BinaryPrimitivesTest { ByteBuffer buf = ByteBuffer.allocate(2 * expected.length); w.configure(data, N, 1).write(buf); buf.flip(); - assertEquals(buf, ByteBuffer.wrap(expected)); + assertEquals(ByteBuffer.wrap(expected), buf); } } diff --git a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/CircularBufferTest.java b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/CircularBufferTest.java index 307cbd77db9..835d261805c 100644 --- a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/CircularBufferTest.java +++ b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/CircularBufferTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, 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 @@ -22,7 +22,6 @@ */ package jdk.internal.net.http.hpack; -import org.testng.annotations.Test; import jdk.internal.net.http.hpack.SimpleHeaderTable.CircularBuffer; import java.util.Arrays; @@ -31,10 +30,11 @@ import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import static jdk.internal.net.http.common.Utils.pow2Size; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static jdk.internal.net.http.hpack.TestHelper.assertVoidThrows; import static jdk.internal.net.http.hpack.TestHelper.newRandom; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; public final class CircularBufferTest { @@ -143,7 +143,7 @@ public final class CircularBufferTest { for (int i = 0; i < gets; i++) { Integer expected = referenceQueue.poll(); Integer actual = buffer.remove(); - assertEquals(actual, expected); + assertEquals(expected, actual); } } } diff --git a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/DecoderTest.java b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/DecoderTest.java index 2f82852ae8a..1e60315469b 100644 --- a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/DecoderTest.java +++ b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/DecoderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, 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 jdk.internal.net.http.hpack; -import org.testng.annotations.Test; import java.io.IOException; import java.io.UncheckedIOException; @@ -33,9 +32,9 @@ import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; import static jdk.internal.net.http.hpack.TestHelper.*; +import org.junit.jupiter.api.Test; // // Tests whose names start with "testX" are the ones captured from real HPACK @@ -402,9 +401,9 @@ public final class DecoderTest { @Test public void sizeUpdate() throws IOException { Decoder d = new Decoder(4096); - assertEquals(d.getTable().maxSize(), 4096); + assertEquals(4096, d.getTable().maxSize()); d.decode(ByteBuffer.wrap(new byte[]{0b00111110}), true, nopCallback()); // newSize = 30 - assertEquals(d.getTable().maxSize(), 30); + assertEquals(30, d.getTable().maxSize()); } @Test @@ -650,8 +649,8 @@ public final class DecoderTest { throw new UncheckedIOException(e); } } while (i.hasNext()); - assertEquals(d.getTable().getStateString(), expectedHeaderTable); - assertEquals(actual.stream().collect(Collectors.joining("\n")), expectedHeaderList); + assertEquals(expectedHeaderTable, d.getTable().getStateString()); + assertEquals(expectedHeaderList, actual.stream().collect(Collectors.joining("\n"))); }); // Now introduce last ByteBuffer which is empty and EOF (mimics idiom @@ -690,8 +689,8 @@ public final class DecoderTest { throw new UncheckedIOException(e); } - assertEquals(d.getTable().getStateString(), expectedHeaderTable); - assertEquals(actual.stream().collect(Collectors.joining("\n")), expectedHeaderList); + assertEquals(expectedHeaderTable, d.getTable().getStateString()); + assertEquals(expectedHeaderList, actual.stream().collect(Collectors.joining("\n"))); }); } @@ -717,8 +716,8 @@ public final class DecoderTest { throw new UncheckedIOException(e); } - assertEquals(d.getTable().getStateString(), expectedHeaderTable); - assertEquals(actual.stream().collect(Collectors.joining("\n")), expectedHeaderList); + assertEquals(expectedHeaderTable, d.getTable().getStateString()); + assertEquals(expectedHeaderList, actual.stream().collect(Collectors.joining("\n"))); } private static DecodingCallback nopCallback() { diff --git a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/EncoderTest.java b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/EncoderTest.java index bf7769c7eb0..cfb5654f163 100644 --- a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/EncoderTest.java +++ b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/EncoderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, 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 @@ -22,7 +22,6 @@ */ package jdk.internal.net.http.hpack; -import org.testng.annotations.Test; import java.io.IOException; import java.nio.Buffer; @@ -40,8 +39,9 @@ import static jdk.internal.net.http.hpack.BuffersTestingKit.forEachSplit; import static jdk.internal.net.http.hpack.SpecHelper.toHexdump; import static jdk.internal.net.http.hpack.TestHelper.assertVoidThrows; import static java.util.Arrays.asList; -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; // TODO: map textual representation of commands from the spec to actual // calls to encoder (actually, this is a good idea for decoder as well) @@ -627,10 +627,10 @@ public final class EncoderTest { String expectedTableState) { String actualTableState = encoder.getHeaderTable().getStateString(); - assertEquals(actualTableState, expectedTableState); + assertEquals(expectedTableState, actualTableState); String actualHexdump = toHexdump(output); - assertEquals(actualHexdump, expectedHexdump.replaceAll("\\n", " ")); + assertEquals(expectedHexdump.replaceAll("\\n", " "), actualHexdump); } // initial size - the size encoder is constructed with @@ -657,7 +657,7 @@ public final class EncoderTest { actual.add(capacity); } }); - assertEquals(actual, expected); + assertEquals(expected, actual); } // diff --git a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/HeaderTableTest.java b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/HeaderTableTest.java index 88987b43d94..0eb1714da35 100644 --- a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/HeaderTableTest.java +++ b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/HeaderTableTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, 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,15 +23,15 @@ package jdk.internal.net.http.hpack; import jdk.internal.net.http.hpack.SimpleHeaderTable.HeaderField; -import org.testng.annotations.Test; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import static org.testng.Assert.assertEquals; -import static org.testng.AssertJUnit.assertTrue; +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; public class HeaderTableTest extends SimpleHeaderTableTest { @@ -61,8 +61,8 @@ public class HeaderTableTest extends SimpleHeaderTableTest { staticHeaderFields.forEach((key, expectedHeaderField) -> { // lookup HeaderField actualHeaderField = table.get(key); - assertEquals(actualHeaderField.name, expectedHeaderField.name); - assertEquals(actualHeaderField.value, expectedHeaderField.value); + assertEquals(expectedHeaderField.name, actualHeaderField.name); + assertEquals(expectedHeaderField.value, actualHeaderField.value); // reverse lookup (name, value) String hName = expectedHeaderField.name; @@ -70,13 +70,13 @@ public class HeaderTableTest extends SimpleHeaderTableTest { int expectedIndex = key; int actualIndex = table.indexOf(hName, hValue); - assertEquals(actualIndex, expectedIndex); + assertEquals(expectedIndex, actualIndex); // reverse lookup (name) Set expectedIndexes = indexes.get(hName); int actualMinimalIndex = table.indexOf(hName, "blah-blah"); - assertTrue(expectedIndexes.contains(-actualMinimalIndex)); + Assertions.assertTrue(expectedIndexes.contains(-actualMinimalIndex)); }); } @@ -88,9 +88,9 @@ public class HeaderTableTest extends SimpleHeaderTableTest { table.put("bender", "rodriguez"); table.put("bender", "rodriguez"); - assertEquals(table.length(), oldLength + 3); // more like an assumption + assertEquals(oldLength + 3, table.length()); // more like an assumption int i = table.indexOf("bender", "rodriguez"); - assertEquals(i, oldLength + 1); + assertEquals(oldLength + 1, i); } @Test @@ -98,13 +98,13 @@ public class HeaderTableTest extends SimpleHeaderTableTest { HeaderTable table = createHeaderTable(256); int oldLength = table.length(); table.put("bender", "rodriguez"); - assertEquals(table.indexOf("bender", "rodriguez"), oldLength + 1); + assertEquals(oldLength + 1, table.indexOf("bender", "rodriguez")); table.put("bender", "rodriguez"); - assertEquals(table.indexOf("bender", "rodriguez"), oldLength + 1); + assertEquals(oldLength + 1, table.indexOf("bender", "rodriguez")); table.evictEntry(); - assertEquals(table.indexOf("bender", "rodriguez"), oldLength + 1); + assertEquals(oldLength + 1, table.indexOf("bender", "rodriguez")); table.evictEntry(); - assertEquals(table.indexOf("bender", "rodriguez"), 0); + assertEquals(0, table.indexOf("bender", "rodriguez")); } @Test @@ -114,9 +114,9 @@ public class HeaderTableTest extends SimpleHeaderTableTest { int idx = rnd.nextInt(oldLength) + 1; HeaderField f = table.get(idx); table.put(f.name, f.value); - assertEquals(table.length(), oldLength + 1); + assertEquals(oldLength + 1, table.length()); int i = table.indexOf(f.name, f.value); - assertEquals(i, idx); + assertEquals(idx, i); } @Test @@ -137,16 +137,16 @@ public class HeaderTableTest extends SimpleHeaderTableTest { String s = String.valueOf(j); int actualIndex = table.indexOf(s, s); int expectedIndex = STATIC_TABLE_LENGTH + NUM_HEADERS - j + 1; - assertEquals(actualIndex, expectedIndex); + assertEquals(expectedIndex, actualIndex); } // as well as for just a name lookup for (int j = 1; j <= NUM_HEADERS; j++) { String s = String.valueOf(j); int actualIndex = table.indexOf(s, "blah"); int expectedIndex = -(STATIC_TABLE_LENGTH + NUM_HEADERS - j + 1); - assertEquals(actualIndex, expectedIndex); + assertEquals(expectedIndex, actualIndex); } // lookup for non-existent name returns 0 - assertEquals(table.indexOf("chupacabra", "1"), 0); + assertEquals(0, table.indexOf("chupacabra", "1")); } } diff --git a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/HuffmanTest.java b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/HuffmanTest.java index ae92e4a4503..4ce10929c24 100644 --- a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/HuffmanTest.java +++ b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/HuffmanTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, 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 @@ -24,7 +24,6 @@ package jdk.internal.net.http.hpack; import jdk.internal.net.http.hpack.Huffman.Reader; import jdk.internal.net.http.hpack.Huffman.Writer; -import org.testng.annotations.Test; import java.io.IOException; import java.io.UncheckedIOException; @@ -39,8 +38,9 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import static jdk.internal.net.http.hpack.HPACK.bytesForBits; -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; public final class HuffmanTest { @@ -412,8 +412,8 @@ public final class HuffmanTest { // might not be printable/visible) int expected = code.sym; int actual = (int) output.charAt(0); - assertEquals(output.length(), 1); // exactly 1 character - assertEquals(actual, expected); + assertEquals(1, output.length()); // exactly 1 character + assertEquals(expected, actual); } } @@ -653,7 +653,7 @@ public final class HuffmanTest { w.from(str, 0, str.length()).write(buffer); Reader r = READER.get(); r.read(buffer.flip(), b, true); - assertEquals(b.toString(), str); + assertEquals(str, b.toString()); } private void roundTrip(int... lengths) throws IOException { @@ -765,7 +765,7 @@ public final class HuffmanTest { } catch (IOException e) { throw new UncheckedIOException(e); } - assertEquals(actual.toString(), decoded); + assertEquals(decoded, actual.toString()); } private static void readExhaustively(String hexdump, String decoded) { @@ -782,7 +782,7 @@ public final class HuffmanTest { } catch (IOException e) { throw new UncheckedIOException(e); } - assertEquals(actual.toString(), decoded); + assertEquals(decoded, actual.toString()); reader.reset(); actual.setLength(0); }); @@ -796,7 +796,7 @@ public final class HuffmanTest { boolean written = writer.write(destination); assertTrue(written); String actual = SpecHelper.toHexdump(destination.flip()); - assertEquals(actual, hexdump); + assertEquals(hexdump, actual); writer.reset(); } @@ -815,7 +815,7 @@ public final class HuffmanTest { assertTrue(written); ByteBuffer concated = BuffersTestingKit.concat(byteBuffers); String actual = SpecHelper.toHexdump(concated); - assertEquals(actual, hexdump); + assertEquals(hexdump, actual); writer.reset(); }); } diff --git a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/SimpleHeaderTableTest.java b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/SimpleHeaderTableTest.java index 79ffed84767..8513916a130 100644 --- a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/SimpleHeaderTableTest.java +++ b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/SimpleHeaderTableTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, 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,7 +23,6 @@ package jdk.internal.net.http.hpack; import jdk.internal.net.http.hpack.SimpleHeaderTable.HeaderField; -import org.testng.annotations.Test; import java.nio.charset.StandardCharsets; import java.util.Collections; @@ -39,7 +38,8 @@ import static jdk.internal.net.http.hpack.TestHelper.assertThrows; import static jdk.internal.net.http.hpack.TestHelper.assertVoidThrows; import static jdk.internal.net.http.hpack.TestHelper.newRandom; import static java.lang.String.format; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; public class SimpleHeaderTableTest { @@ -125,8 +125,8 @@ public class SimpleHeaderTableTest { Map staticHeaderFields = createStaticEntries(); staticHeaderFields.forEach((index, expectedHeaderField) -> { SimpleHeaderTable.HeaderField actualHeaderField = table.get(index); - assertEquals(actualHeaderField.name, expectedHeaderField.name); - assertEquals(actualHeaderField.value, expectedHeaderField.value); + assertEquals(expectedHeaderField.name, actualHeaderField.name); + assertEquals(expectedHeaderField.value, actualHeaderField.value); }); } @@ -134,8 +134,8 @@ public class SimpleHeaderTableTest { public void constructorSetsMaxSize() { int size = rnd.nextInt(64); SimpleHeaderTable table = createHeaderTable(size); - assertEquals(table.size(), 0); - assertEquals(table.maxSize(), size); + assertEquals(0, table.size()); + assertEquals(size, table.maxSize()); } @Test @@ -152,7 +152,7 @@ public class SimpleHeaderTableTest { public void zeroMaximumSize() { SimpleHeaderTable table = createHeaderTable(0); table.setMaxSize(0); - assertEquals(table.maxSize(), 0); + assertEquals(0, table.maxSize()); } @Test @@ -177,7 +177,7 @@ public class SimpleHeaderTableTest { @Test public void length() { SimpleHeaderTable table = createHeaderTable(0); - assertEquals(table.length(), STATIC_TABLE_LENGTH); + assertEquals(STATIC_TABLE_LENGTH, table.length()); } @Test @@ -203,14 +203,14 @@ public class SimpleHeaderTableTest { table.put(name, value); SimpleHeaderTable.HeaderField f = table.get(idx); - assertEquals(f.name, name); - assertEquals(f.value, value); + assertEquals(name, f.name); + assertEquals(value, f.value); } @Test public void staticTableHasZeroSize() { SimpleHeaderTable table = createHeaderTable(0); - assertEquals(table.size(), 0); + assertEquals(0, table.size()); } // TODO: negative indexes check @@ -236,13 +236,13 @@ public class SimpleHeaderTableTest { SimpleHeaderTable.HeaderField f = table.get(STATIC_TABLE_LENGTH + j); int actualName = Integer.parseInt(f.name); int expectedName = NUM_HEADERS - j + 1; - assertEquals(actualName, expectedName); + assertEquals(expectedName, actualName); } // Entries MUST be evicted in the order they were added: // the newer the entry the later it is evicted for (int k = 1; k <= NUM_HEADERS; k++) { SimpleHeaderTable.HeaderField f = table.evictEntry(); - assertEquals(f.name, String.valueOf(k)); + assertEquals(String.valueOf(k), f.name); } } @@ -257,7 +257,7 @@ public class SimpleHeaderTableTest { Locale.setDefault(Locale.FRENCH); try { String s = format("%.1f", 3.1); - assertEquals(s, "3,1"); // assumption of the test, otherwise the test is useless + assertEquals("3,1", s); // assumption of the test, otherwise the test is useless testToString0(); } finally { Locale.setDefault(locale); @@ -272,7 +272,7 @@ public class SimpleHeaderTableTest { String expected = format( "dynamic length: %s, full length: %s, used space: %s/%s (%.1f%%)", 0, STATIC_TABLE_LENGTH, 0, maxSize, 0.0); - assertEquals(table.toString(), expected); + assertEquals(expected, table.toString()); } { @@ -290,7 +290,7 @@ public class SimpleHeaderTableTest { String expected = format( "dynamic length: %s, full length: %s, used space: %s/%s (%.1f%%)", 1, STATIC_TABLE_LENGTH + 1, used, size, ratio); - assertEquals(s, expected); + assertEquals(expected, s); } { @@ -301,7 +301,7 @@ public class SimpleHeaderTableTest { String expected = format("dynamic length: %s, full length: %s, used space: %s/%s (%.1f%%)", 2, STATIC_TABLE_LENGTH + 2, 78, 78, 100.0); - assertEquals(s, expected); + assertEquals(expected, s); } } @@ -310,9 +310,8 @@ public class SimpleHeaderTableTest { SimpleHeaderTable table = createHeaderTable(256); table.put("custom-key", "custom-header"); // @formatter:off - assertEquals(table.getStateString(), - "[ 1] (s = 55) custom-key: custom-header\n" + - " Table size: 55"); + assertEquals("[ 1] (s = 55) custom-key: custom-header\n" + + " Table size: 55", table.getStateString()); // @formatter:on } diff --git a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/TestHelper.java b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/TestHelper.java index 89982a46a1f..b140440b0fa 100644 --- a/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/TestHelper.java +++ b/test/jdk/java/net/httpclient/http2/java.net.http/jdk/internal/net/http/hpack/TestHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, 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 @@ -22,10 +22,10 @@ */ package jdk.internal.net.http.hpack; -import org.testng.annotations.Test; import java.util.Objects; import java.util.Random; +import org.junit.jupiter.api.Test; public final class TestHelper { 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 4315fd36de5..44071ea566d 100644 --- a/test/jdk/java/net/httpclient/http3/H3ErrorHandlingTest.java +++ b/test/jdk/java/net/httpclient/http3/H3ErrorHandlingTest.java @@ -71,6 +71,7 @@ import static org.testng.Assert.*; /* * @test + * @bug 8373409 * @key intermittent * @comment testResetControlStream may fail if the client doesn't read the stream type * before the stream is reset, @@ -87,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; @@ -230,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 881277da1f8..5ef45f8b230 100644 --- a/test/jdk/java/net/httpclient/http3/H3MalformedResponseTest.java +++ b/test/jdk/java/net/httpclient/http3/H3MalformedResponseTest.java @@ -22,410 +22,452 @@ */ import jdk.httpclient.test.lib.common.HttpServerAdapters; -import jdk.httpclient.test.lib.quic.QuicServerConnection; import jdk.httpclient.test.lib.quic.QuicStandaloneServer; -import jdk.internal.net.http.http3.Http3Error; -import jdk.internal.net.http.quic.TerminationCause; +import jdk.internal.net.http.common.Logger; +import jdk.internal.net.http.common.Utils; import jdk.internal.net.quic.QuicVersion; import jdk.test.lib.net.SimpleSSLContext; import jdk.test.lib.net.URIBuilder; -import jdk.test.lib.Utils; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -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.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import javax.net.ssl.SSLContext; +import java.io.IOException; import java.io.OutputStream; -import java.net.URI; -import java.net.URISyntaxException; +import java.net.ProtocolException; import java.net.http.HttpClient; import java.net.http.HttpClient.Version; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.util.HexFormat; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BooleanSupplier; -import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY; +import static java.net.http.HttpClient.Builder.NO_PROXY; import static java.net.http.HttpOption.H3_DISCOVERY; -import static org.testng.Assert.*; +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.assertThrows; /* * @test - * @summary Verifies that the HTTP client correctly handles malformed responses - * @library /test/lib /test/jdk/java/net/httpclient/lib - * @library ../access - * @build jdk.test.lib.net.SimpleSSLContext - * jdk.httpclient.test.lib.common.HttpServerAdapters - * @build java.net.http/jdk.internal.net.http.Http3ConnectionAccess - * @run testng/othervm - * -Djdk.internal.httpclient.debug=true - * -Djdk.httpclient.HttpClient.log=requests,responses,errors H3MalformedResponseTest + * @bug 8369595 + * @summary Verifies that the HTTP/3 malformed responses are correctly handled + * @library /test/jdk/java/net/httpclient/lib + * /test/lib + * @run junit ${test.main.class} */ -public class H3MalformedResponseTest implements HttpServerAdapters { - private SSLContext sslContext; - private QuicStandaloneServer server; - private String requestURIBase; +/// Verifies that the HTTP/3 malformed responses are correctly handled. +/// +/// ### HTTP/3 `HEADERS` frame & QPACK Field Section encoding crash course +/// +/// Consider an HTTP/3 `HEADERS` frame that carries: +/// +/// ``` +/// :status: 200 +/// content-length: 2 +/// ``` +/// +/// This will be encoded as the following byte sequence: +/// +/// ``` +/// 01 06 00 00 D9 54 01 32 +/// ``` +/// +/// Let's start with decoding the HTTP/3 frame: +/// +/// - `01`: Frame Type (`01` denotes `HEADERS``) +/// +/// - `06`: Payload length (6 bytes) +/// +/// Figured this is a `HEADERS` frame containing 6 bytes: `00 00 D9 54 01 32`. +/// Let's decode the QPACK Field Section +/// +/// - `00`: Required Insert Count (0) +/// +/// - `00`: Base (0) +/// +/// - `D9`: +/// QPACK has a static table (indexed from 0) and `:status: 200` is at the +/// static-table index 25. +/// +/// ``` +/// D9 = <1101 1001> +/// = <1> (Indexed Field Line) +/// + <1> (Static Table) +/// + <01 1001> (entry index = 25) +/// ``` +/// +/// - `54 01 32`: +/// `content-length: 2` can be encoded as a *literal field line with name +/// reference* using the static name `content-length` (static index 4) and +/// the literal value `2`. +/// +/// ``` +/// 54 01 32 = <0101 0100 0000 0001 0011 0010> +/// = <0> (Literal Field Line) +/// + <1> (Name Reference) +/// + <0100> (entry index = 4) +/// + <0000 0001> (value length = 1 byte) +/// + <0011 0010> (value = ASCII "2" = 0x32 = 50) +/// ``` +/// +/// Note that the `value length` field (i.e., `0000 0001`) follows a variable +/// coding scheme: +/// +/// | Prefix | Total size | Payload size | Max value | +/// | --------------------- | ---------- | ------------ | ------------- | +/// | `00xx xxxx` | 1 byte | 6 bits | 63 | +/// | `01xx xxxx xxxx xxxx` | 2 bytes | 14 bits | 16,383 | +/// | `10xx xxx…` | 4 bytes | 30 bits | 1,073,741,823 | +/// | `11xx xxx…` | 8 bytes | 62 bits | 4.61e18 | +class H3MalformedResponseTest { - // These responses are malformed and should not be accepted by the client, - // but they should not cause connection closure - @DataProvider - public static Object[][] malformedResponse() { + private static final String CLASS_NAME = H3MalformedResponseTest.class.getSimpleName(); + + private static final Logger LOGGER = Utils.getDebugLogger(CLASS_NAME::toString, Utils.DEBUG); + + private static final SSLContext SSL_CONTEXT = SimpleSSLContext.findSSLContext(); + + private static QuicStandaloneServer SERVER; + + private static HttpRequest REQUEST; + + @BeforeAll + static void setUp() throws Exception { + + // Create and start the server + SERVER = QuicStandaloneServer.newBuilder() + .availableVersions(new QuicVersion[]{QuicVersion.QUIC_V1}) + .sslContext(SSL_CONTEXT) + .alpn("h3") + .build(); + SERVER.start(); + LOGGER.log("Server is started at {}", SERVER.getAddress()); + + // Create the request + var requestURI = URIBuilder.newBuilder() + .scheme("https") + .loopback() + .port(SERVER.getAddress().getPort()) + .path("/" + CLASS_NAME) + .build(); + REQUEST = HttpRequest.newBuilder(requestURI) + .version(Version.HTTP_3) + .setOption(H3_DISCOVERY, HTTP_3_URI_ONLY) + .build(); + + } + + @AfterAll + static void tearDown() { + close("server", SERVER); + } + + private static void close(String name, AutoCloseable closeable) { + if (closeable != null) { + LOGGER.log("Closing {}", name); + try { + closeable.close(); + } catch (Exception e) { + LOGGER.log("Could not close " + name, e); + } + } + } + + /// Malformed responses that should not be accepted by the client, but + /// should neither cause the connection to get closed. + static Object[][] malformedResponsesPreservingConnection() { return new Object[][]{ - new Object[] {"empty", HexFormat.of().parseHex( - "" + {"empty", IOException.class, parseHex("")}, + {"non-final response", IOException.class, parseHex( + "01040000", // headers, length 4, section prefix + "ff00" // :status:100 )}, - new Object[] {"non-final response", HexFormat.of().parseHex( - "01040000"+ // headers, length 4, section prefix - "ff00" // :status:100 + {"uppercase header name", ProtocolException.class, parseHex( + "01090000", // headers, length 9, section prefix + "d9", // :status:200 + "234147450130", // AGE:0 + "000100" // data, 1 byte )}, - new Object[] {"uppercase header name", HexFormat.of().parseHex( - "01090000"+ // headers, length 9, section prefix - "d9"+ // :status:200 - "234147450130"+ // AGE:0 + {"content too long", IOException.class, parseHex( + "01040000", // headers, length 4, section prefix + "d9", // :status:200 + "c4", // content-length:0 + "000100" // data, 1 byte + )}, + {"content too short", IOException.class, parseHex( + "01060000", // headers, length 6, section prefix + "d9", // :status:200 + "540132", // content-length:2 + "000100" // data, 1 byte + )}, + {"text in content-length", ProtocolException.class, parseHex( + "01060000" + // headers, length 6, section prefix + "d9" + // :status:200 + "540161" + // content-length:a "000100" // data, 1 byte )}, - new Object[] {"content too long", HexFormat.of().parseHex( - "01040000"+ // headers, length 4, section prefix - "d9"+ // :status:200 - "c4"+ // content-length:0 - "000100" // data, 1 byte - )}, - new Object[] {"content too short", HexFormat.of().parseHex( - "01060000"+ // headers, length 6, section prefix - "d9"+ // :status:200 - "540132"+ // content-length:2 - "000100" // data, 1 byte - )}, - new Object[] {"text in content-length", HexFormat.of().parseHex( - "01060000"+ // headers, length 6, section prefix - "d9"+ // :status:200 - "540161"+ // content-length:a - "000100" // data, 1 byte - )}, - new Object[] {"connection: close", HexFormat.of().parseHex( - "01150000"+ // headers, length 21, section prefix - "d9"+ // :status:200 - "2703636F6E6E656374696F6E05636C6F7365"+ // connection:close + {"connection: close", ProtocolException.class, parseHex( + "01150000", // headers, length 21, section prefix + "d9", // :status:200 + "2703636F6E6E656374696F6E05636C6F7365" + // connection:close "000100" // data, 1 byte )}, // request pseudo-headers in response - new Object[] {":method in response", HexFormat.of().parseHex( - "01040000"+ // headers, length 4, section prefix - "d9"+ // :status:200 - "d1"+ // :method:get - "000100" // data, 1 byte + {":method in response", ProtocolException.class, parseHex( + "01040000", // headers, length 4, section prefix + "d9", // :status:200 + "d1", // :method:get + "000100" // data, 1 byte )}, - new Object[] {":authority in response", HexFormat.of().parseHex( - "01100000"+ // headers, length 16, section prefix - "d9"+ // :status:200 - "508b089d5c0b8170dc702fbce7"+ // :authority - "000100" // data, 1 byte + {":authority in response", ProtocolException.class, parseHex( + "01100000", // headers, length 16, section prefix + "d9", // :status:200 + "508b089d5c0b8170dc702fbce7", // :authority + "000100" // data, 1 byte )}, - new Object[] {":path in response", HexFormat.of().parseHex( - "010a0000"+ // headers, length 10, section prefix - "d9"+ // :status:200 - "51856272d141ff"+ // :path - "000100" // data, 1 byte + {":path in response", ProtocolException.class, parseHex( + "010a0000", // headers, length 10, section prefix + "d9", // :status:200 + "51856272d141ff", // :path + "000100" // data, 1 byte )}, - new Object[] {":scheme in response", HexFormat.of().parseHex( - "01040000"+ // headers, length 4, section prefix - "d9"+ // :status:200 - "d7"+ // :scheme:https - "000100" // data, 1 byte + {":scheme in response", ProtocolException.class, parseHex( + "01040000", // headers, length 4, section prefix + "d9", // :status:200 + "d7", // :scheme:https + "000100" // data, 1 byte )}, - new Object[] {"undefined pseudo-header", HexFormat.of().parseHex( - "01080000"+ // headers, length 8, section prefix - "d9"+ // :status:200 - "223A6D0130"+ // :m:0 - "000100" // data, 1 byte + {"undefined pseudo-header", ProtocolException.class, parseHex( + "01080000", // headers, length 8, section prefix + "d9", // :status:200 + "223A6D0130", // :m:0 + "000100" // data, 1 byte )}, - new Object[] {"pseudo-header after regular", HexFormat.of().parseHex( - "011a0000"+ // headers, length 26, section prefix - "5f5094ca3ee35a74a6b589418b5258132b1aa496ca8747"+ //user-agent - "d9"+ // :status:200 - "000100" // data, 1 byte + {"pseudo-header after regular", ProtocolException.class, parseHex( + "011a0000", // headers, length 26, section prefix + "5f5094ca3ee35a74a6b589418b5258132b1aa496ca8747", //user-agent + "d9", // :status:200 + "000100" // data, 1 byte )}, - new Object[] {"trailer", HexFormat.of().parseHex( + {"trailer", IOException.class, parseHex( "01020000" // headers, length 2, section prefix )}, - new Object[] {"trailer+data", HexFormat.of().parseHex( - "01020000"+ // headers, length 2, section prefix - "000100" // data, 1 byte + {"trailer+data", IOException.class, parseHex( + "01020000", // headers, length 2, section prefix + "000100" // data, 1 byte )}, // valid characters include \t, 0x20-0x7e, 0x80-0xff (RFC 9110, section 5.5) - new Object[] {"invalid character in field value 00", HexFormat.of().parseHex( - "01060000"+ // headers, length 6, section prefix - "d9"+ // :status:200 - "570100"+ // etag:\0 - "000100" // data, 1 byte + {"invalid character in field value 00", ProtocolException.class, parseHex( + "01060000", // headers, length 6, section prefix + "d9", // :status:200 + "570100", // etag:\0 + "000100" // data, 1 byte )}, - new Object[] {"invalid character in field value 0a", HexFormat.of().parseHex( - "01060000"+ // headers, length 6, section prefix - "d9"+ // :status:200 - "57010a"+ // etag:\n - "000100" // data, 1 byte + {"invalid character in field value 0a", ProtocolException.class, parseHex( + "01060000", // headers, length 6, section prefix + "d9", // :status:200 + "57010a", // etag:\n + "000100" // data, 1 byte )}, - new Object[] {"invalid character in field value 0d", HexFormat.of().parseHex( - "01060000"+ // headers, length 6, section prefix - "d9"+ // :status:200 - "57010d"+ // etag:\r - "000100" // data, 1 byte + {"invalid character in field value 0d", ProtocolException.class, parseHex( + "01060000", // headers, length 6, section prefix + "d9", // :status:200 + "57010d", // etag:\r + "000100" // data, 1 byte )}, - new Object[] {"invalid character in field value 7f", HexFormat.of().parseHex( - "01060000"+ // headers, length 6, section prefix - "d9"+ // :status:200 - "57017f"+ // etag: 0x7f - "000100" // data, 1 byte + {"invalid character in field value 7f", ProtocolException.class, parseHex( + "01060000", // headers, length 6, section prefix + "d9", // :status:200 + "57017f", // etag: 0x7f + "000100" // data, 1 byte )}, }; } - // These responses are malformed and should not be accepted by the client. - // They might or might not cause connection closure (H3_FRAME_UNEXPECTED) - @DataProvider - public static Object[][] malformedResponse2() { + /// Malformed responses that should not be accepted by the client. + /// They might or might not cause the connection to get closed (`H3_FRAME_UNEXPECTED`). + static Object[][] malformedResponses() { // data before headers is covered by H3ErrorHandlingTest return new Object[][]{ - new Object[] {"100+data", HexFormat.of().parseHex( - "01040000"+ // headers, length 4, section prefix - "ff00"+ // :status:100 - "000100" // data, 1 byte + {"100+data", IOException.class, parseHex( + "01040000", // headers, length 4, section prefix + "ff00", // :status:100 + "000100" // data, 1 byte )}, - new Object[] {"100+data+200", HexFormat.of().parseHex( - "01040000"+ // headers, length 4, section prefix - "ff00"+ // :status:100 - "000100"+ // data, 1 byte - "01030000"+ // headers, length 3, section prefix - "d9" // :status:200 + {"100+data+200", IOException.class, parseHex( + "01040000", // headers, length 4, section prefix + "ff00", // :status:100 + "000100", // data, 1 byte + "01030000", // headers, length 3, section prefix + "d9" // :status:200 )}, - new Object[] {"200+data+200", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "000100"+ // data, 1 byte - "01030000"+ // headers, length 3, section prefix - "d9" // :status:200 + {"200+data+200", IOException.class, parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "000100", // data, 1 byte + "01030000", // headers, length 3, section prefix + "d9" // :status:200 )}, - new Object[] {"200+data+100", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "000100"+ // data, 1 byte - "01040000"+ // headers, length 4, section prefix - "ff00" // :status:100 + {"200+data+100", IOException.class, parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "000100", // data, 1 byte + "01040000", // headers, length 4, section prefix + "ff00" // :status:100 )}, - new Object[] {"200+data+trailers+data", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "000100"+ // data, 1 byte - "01020000"+ // trailers, length 2, section prefix - "000100" // data, 1 byte + {"200+data+trailers+data", ProtocolException.class, parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "000100", // data, 1 byte + "01020000", // trailers, length 2, section prefix + "000100" // data, 1 byte )}, - new Object[] {"200+trailers+data", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "01020000"+ // trailers, length 2, section prefix - "000100" // data, 1 byte + {"200+trailers+data", IOException.class, parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "01020000", // trailers, length 2, section prefix + "000100" // data, 1 byte )}, - new Object[] {"200+200", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "01030000"+ // headers, length 3, section prefix - "d9" // :status:200 + {"200+200", IOException.class, parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "01030000", // headers, length 3, section prefix + "d9" // :status:200 )}, - new Object[] {"200+100", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "01040000"+ // headers, length 4, section prefix - "ff00" // :status:100 + {"200+100", IOException.class, parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "01040000", // headers, length 4, section prefix + "ff00" // :status:100 )}, }; } - @DataProvider - public static Object[][] wellformedResponse() { + /// Well-formed responses that should be accepted by the client. + static Object[][] wellFormedResponses() { return new Object[][]{ - new Object[] {"100+200+data+reserved", HexFormat.of().parseHex( - "01040000"+ // headers, length 4, section prefix - "ff00"+ // :status:100 - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "000100"+ // data, 1 byte - "210100" // reserved, 1 byte + {"100+200+data+reserved", parseHex( + "01040000", // headers, length 4, section prefix + "ff00", // :status:100 + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "000100", // data, 1 byte + "210100" // reserved, 1 byte )}, - new Object[] {"200+data+reserved", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "000100"+ // data, 1 byte - "210100" // reserved, 1 byte + {"200+data+reserved", parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "000100", // data, 1 byte + "210100" // reserved, 1 byte )}, - new Object[] {"200+data", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "000100" // data, 1 byte + {"200+data", parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "000100" // data, 1 byte )}, - new Object[] {"200+user-agent+data", HexFormat.of().parseHex( - "011a0000"+ // headers, length 26, section prefix - "d9"+ // :status:200 - "5f5094ca3ee35a74a6b589418b5258132b1aa496ca8747"+ //user-agent - "000100" // data, 1 byte + {"200+user-agent+data", parseHex( + "011a0000", // headers, length 26, section prefix + "d9", // :status:200 + "5f5094ca3ee35a74a6b589418b5258132b1aa496ca8747", //user-agent + "000100" // data, 1 byte )}, - new Object[] {"200", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9" // :status:200 + {"200", parseHex( + "01030000", // headers, length 3, section prefix + "d9" // :status:200 )}, - new Object[] {"200+data+data", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "000100"+ // data, 1 byte - "000100" // data, 1 byte + {"200+data+data", parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "000100", // data, 1 byte + "000100" // data, 1 byte )}, - new Object[] {"200+data+trailers", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "000100"+ // data, 1 byte - "01020000" // trailers, length 2, section prefix + {"200+data+trailers", parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "000100", // data, 1 byte + "01020000" // trailers, length 2, section prefix )}, - new Object[] {"200+trailers", HexFormat.of().parseHex( - "01030000"+ // headers, length 3, section prefix - "d9"+ // :status:200 - "01020000" // trailers, length 2, section prefix + {"200+trailers", parseHex( + "01030000", // headers, length 3, section prefix + "d9", // :status:200 + "01020000" // trailers, length 2, section prefix )}, }; } - @BeforeClass - public void beforeClass() throws Exception { - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) { - throw new AssertionError("Unexpected null sslContext"); + private static byte[] parseHex(String... strings) { + var buffer = new StringBuilder(); + for (String string : strings) { + buffer.append(string); } - server = QuicStandaloneServer.newBuilder() - .availableVersions(new QuicVersion[]{QuicVersion.QUIC_V1}) - .sslContext(sslContext) - .alpn("h3") + return HexFormat.of().parseHex(buffer.toString()); + } + + @ParameterizedTest + @MethodSource("wellFormedResponses") + void testWellFormedResponse(String desc, byte[] serverResponseBytes) throws Exception { + var connectionTerminated = configureServerResponse(serverResponseBytes); + try (var client = createClient()) { + final HttpResponse response = client.send(REQUEST, BodyHandlers.discarding()); + assertEquals(200, response.statusCode()); + assertFalse(connectionTerminated.getAsBoolean(), "Expected the connection to be open"); + } + } + + @ParameterizedTest + @MethodSource("malformedResponsesPreservingConnection") + void testMalformedResponsePreservingConnection( + String desc, + Class exceptionClass, + byte[] serverResponseBytes) { + var connectionTerminated = configureServerResponse(serverResponseBytes); + try (var client = createClient()) { + var exception = assertThrows(exceptionClass, () -> client.send(REQUEST, BodyHandlers.discarding())); + LOGGER.log("Got expected exception for: " + desc, exception); + assertFalse(connectionTerminated.getAsBoolean(), "Expected the connection to be open"); + } + } + + @ParameterizedTest + @MethodSource("malformedResponses") + void testMalformedResponse( + String desc, + Class exceptionClass, + byte[] serverResponseBytes) { + configureServerResponse(serverResponseBytes); + try (var client = createClient()) { + var exception = assertThrows(exceptionClass, () -> client.send(REQUEST, BodyHandlers.discarding())); + LOGGER.log("Got expected exception for: " + desc, exception); + } + } + + private static HttpClient createClient() { + return HttpServerAdapters.createClientBuilderForH3() + .proxy(NO_PROXY) + .version(Version.HTTP_3) + .sslContext(SSL_CONTEXT) .build(); - server.start(); - System.out.println("Server started at " + server.getAddress()); - requestURIBase = URIBuilder.newBuilder().scheme("https").loopback() - .port(server.getAddress().getPort()).build().toString(); } - @AfterClass - public void afterClass() throws Exception { - if (server != null) { - System.out.println("Stopping server " + server.getAddress()); - server.close(); - } - } - - /** - * Server sends a well-formed response - */ - @Test(dataProvider = "wellformedResponse") - public void testWellFormedResponse(String desc, byte[] response) throws Exception { - CompletableFuture errorCF = new CompletableFuture<>(); - server.addHandler((c,s)-> { + private static BooleanSupplier configureServerResponse(byte[] serverResponseBytes) { + var connectionTerminated = new AtomicBoolean(); + SERVER.addHandler((c, s)-> { try (OutputStream outputStream = s.outputStream()) { - outputStream.write(response); + outputStream.write(serverResponseBytes); } - // verify that the connection stays open - completeUponTermination(c, errorCF); + c.futureTerminationCause().handle((_, _) -> { + connectionTerminated.set(true); + return true; + }); }); - HttpClient client = getHttpClient(); - try { - HttpRequest request = getRequest(); - final HttpResponse response1 = client.send( - request, - BodyHandlers.discarding()); - assertEquals(response1.statusCode(), 200); - assertFalse(errorCF.isDone(), "Expected the connection to be open"); - } finally { - client.shutdownNow(); - } + return connectionTerminated::get; } - - /** - * Server sends a malformed response that should not close connection - */ - @Test(dataProvider = "malformedResponse") - public void testMalformedResponse(String desc, byte[] response) throws Exception { - CompletableFuture errorCF = new CompletableFuture<>(); - server.addHandler((c,s)-> { - try (OutputStream outputStream = s.outputStream()) { - outputStream.write(response); - } - // verify that the connection stays open - completeUponTermination(c, errorCF); - }); - HttpClient client = getHttpClient(); - try { - HttpRequest request = getRequest(); - final HttpResponse response1 = client.send( - request, - BodyHandlers.discarding()); - fail("Expected the request to fail, got " + response1); - } catch (Exception e) { - System.out.println("Got expected exception: " +e); - e.printStackTrace(); - assertFalse(errorCF.isDone(), "Expected the connection to be open"); - } finally { - client.shutdownNow(); - } - } - - /** - * Server sends a malformed response that might close connection - */ - @Test(dataProvider = "malformedResponse2") - public void testMalformedResponse2(String desc, byte[] response) throws Exception { - server.addHandler((c,s)-> { - try (OutputStream outputStream = s.outputStream()) { - outputStream.write(response); - } - }); - HttpClient client = getHttpClient(); - try { - HttpRequest request = getRequest(); - final HttpResponse response1 = client.send( - request, - BodyHandlers.discarding()); - fail("Expected the request to fail, got " + response1); - } catch (Exception e) { - System.out.println("Got expected exception: " +e); - e.printStackTrace(); - } finally { - client.shutdownNow(); - } - } - - private HttpRequest getRequest() throws URISyntaxException { - final URI reqURI = new URI(requestURIBase + "/hello"); - final HttpRequest.Builder reqBuilder = HttpRequest.newBuilder(reqURI) - .version(Version.HTTP_3) - .setOption(H3_DISCOVERY, HTTP_3_URI_ONLY); - return reqBuilder.build(); - } - - private HttpClient getHttpClient() { - final HttpClient client = newClientBuilderForH3() - .proxy(HttpClient.Builder.NO_PROXY) - .version(Version.HTTP_3) - .sslContext(sslContext).build(); - return client; - } - - private static String toHexString(final Http3Error error) { - return error.name() + "(0x" + Long.toHexString(error.code()) + ")"; - } - - private static void completeUponTermination(final QuicServerConnection serverConnection, - final CompletableFuture cf) { - serverConnection.futureTerminationCause().handle( - (r,t) -> t != null ? cf.completeExceptionally(t) : cf.complete(r)); - } } 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 862ccf22ddc..14149da7815 100644 --- a/test/jdk/java/net/httpclient/http3/H3MultipleConnectionsToSameHost.java +++ b/test/jdk/java/net/httpclient/http3/H3MultipleConnectionsToSameHost.java @@ -37,7 +37,7 @@ * -Djdk.internal.httpclient.quic.poller.usePlatformThreads=false * -Djdk.httpclient.quic.maxEndpoints=-1 * -Djdk.httpclient.http3.maxStreamLimitTimeout=0 - * -Djdk.httpclient.quic.maxBidiStreams=2 + * -Djdk.internal.httpclient.quic.maxBidiStreams=2 * -Djdk.httpclient.retryOnStreamlimit=50 * -Djdk.httpclient.HttpClient.log=errors,http3,quic:retransmit * -Dsimpleget.requests=100 @@ -61,7 +61,7 @@ * -XX:+UnlockExperimentalVMOptions -XX:-VMContinuations * -Djdk.httpclient.quic.maxEndpoints=-1 * -Djdk.httpclient.http3.maxStreamLimitTimeout=0 - * -Djdk.httpclient.quic.maxBidiStreams=2 + * -Djdk.internal.httpclient.quic.maxBidiStreams=2 * -Djdk.httpclient.retryOnStreamlimit=50 * -Djdk.httpclient.HttpClient.log=errors,http3,quic:retransmit * -Dsimpleget.requests=100 @@ -85,7 +85,7 @@ * -Djdk.internal.httpclient.quic.useNioSelector=true * -Djdk.httpclient.http3.maxStreamLimitTimeout=0 * -Djdk.httpclient.quic.maxEndpoints=1 - * -Djdk.httpclient.quic.maxBidiStreams=2 + * -Djdk.internal.httpclient.quic.maxBidiStreams=2 * -Djdk.httpclient.retryOnStreamlimit=50 * -Djdk.httpclient.HttpClient.log=errors,http3,quic:hs:retransmit * -Dsimpleget.requests=100 @@ -109,7 +109,7 @@ * -Djdk.httpclient.quic.maxPtoBackoff=9 * -Djdk.httpclient.http3.maxStreamLimitTimeout=0 * -Djdk.httpclient.quic.maxEndpoints=1 - * -Djdk.httpclient.quic.maxBidiStreams=2 + * -Djdk.internal.httpclient.quic.maxBidiStreams=2 * -Djdk.httpclient.retryOnStreamlimit=50 * -Djdk.httpclient.HttpClient.log=errors,http3,quic:hs:retransmit * -Dsimpleget.requests=100 @@ -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)) @@ -239,7 +234,7 @@ public class H3MultipleConnectionsToSameHost implements HttpServerAdapters { long done = System.nanoTime(); System.out.println("Initialization and warmup took "+ TimeUnit.NANOSECONDS.toMillis(done-prestart)+" millis"); // Thread.sleep(30000); - int maxBidiStreams = Utils.getIntegerNetProperty("jdk.httpclient.quic.maxBidiStreams", 100); + int maxBidiStreams = Utils.getIntegerNetProperty("jdk.internal.httpclient.quic.maxBidiStreams", 100); long timeout = MAX_STREAM_LIMIT_WAIT_TIMEOUT; Set connections = new ConcurrentSkipListSet<>(); 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 916a6a5221d..a4524b9ae5e 100644 --- a/test/jdk/java/net/httpclient/http3/H3StreamLimitReachedTest.java +++ b/test/jdk/java/net/httpclient/http3/H3StreamLimitReachedTest.java @@ -23,6 +23,24 @@ /* * @test id=with-default-wait + * @summary this test verifies that the correct connection is + * used when a request is retried on a new connection + * due to stream limit reached. + * The maxBidiStreams limit is artificially set to 1. + * This configuration uses the default wait for a stream + * to become available before retrying. + * Different configurations are tested if possible, + * with both HTTP/3 only and HTTP/2 HTTP/3 with altsvc. + * In one case the HTTP/3 only server will be listening + * on the same port as the HTTP/2 server, with the + * HTTP/2 server advertising an AltService on a different + * port. In another case the AltService will be on the + * same port as the HTTP/2 server and the HTTP/3 server + * will be on a different port. In all case, the test + * verifies that the right connection is picked up + * for the retry. + * @bug 8372951 + * @comment this test also tests bug 8372951 * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.http2.Http2TestServer * jdk.test.lib.Asserts @@ -30,12 +48,30 @@ * jdk.test.lib.net.SimpleSSLContext * @run testng/othervm -Djdk.httpclient.HttpClient.log=ssl,requests,responses,errors,http3,quic:control * -Djdk.internal.httpclient.debug=false - * -Djdk.httpclient.quic.maxBidiStreams=1 + * -Djdk.internal.httpclient.quic.maxBidiStreams=1 * H3StreamLimitReachedTest */ /* * @test id=with-no-wait + * @summary this test verifies that the correct connection is + * used when a request is retried on a new connection + * due to stream limit reached. + * The maxBidiStreams limit is artificially set to 1. + * This configuration retries immediately on a new + * connection when no stream is available. + * Different configurations are tested if possible, + * with both HTTP/3 only and HTTP/2 HTTP/3 with altsvc. + * In one case the HTTP/3 only server will be listening + * on the same port as the HTTP/2 server, with the + * HTTP/2 server advertising an AltService on a different + * port. In another case the AltService will be on the + * same port as the HTTP/2 server and the HTTP/3 server + * will be on a different port. In all case, the test + * verifies that the right connection is picked up + * for the retry. + * @bug 8372951 + * @comment this test also tests bug 8372951 * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.http2.Http2TestServer * jdk.test.lib.Asserts @@ -43,7 +79,7 @@ * jdk.test.lib.net.SimpleSSLContext * @run testng/othervm -Djdk.httpclient.HttpClient.log=ssl,requests,responses,errors,http3,quic:control * -Djdk.internal.httpclient.debug=false - * -Djdk.httpclient.quic.maxBidiStreams=1 + * -Djdk.internal.httpclient.quic.maxBidiStreams=1 * -Djdk.httpclient.http3.maxStreamLimitTimeout=0 * -Djdk.httpclient.retryOnStreamlimit=9 * H3StreamLimitReachedTest @@ -93,13 +129,13 @@ import static org.testng.Assert.assertFalse; public class H3StreamLimitReachedTest implements HttpServerAdapters { - private static final String CLASS_NAME = H3ConnectionPoolTest.class.getSimpleName(); + private static final String CLASS_NAME = H3StreamLimitReachedTest.class.getSimpleName(); static int altsvcPort, https2Port, http3Port; 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 { @@ -113,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 d8a920c8544..e0610cf89b8 100644 --- a/test/jdk/java/net/httpclient/http3/StreamLimitTest.java +++ b/test/jdk/java/net/httpclient/http3/StreamLimitTest.java @@ -56,7 +56,10 @@ import static java.net.http.HttpOption.H3_DISCOVERY; /* * @test * @summary verifies that when the Quic stream limit is reached - * then HTTP3 requests are retried on newer connection + * then HTTP3 requests are retried on newer connection. + * This test uses an HTTP/3 only test server, which is + * configured to allow the test to control when a new + * MAX_STREAMS frames is sent to the client. * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.test.lib.net.SimpleSSLContext * jdk.httpclient.test.lib.common.HttpServerAdapters @@ -65,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; @@ -96,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/lib/jdk/httpclient/test/lib/http3/Http3ServerExchange.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerExchange.java index 9a39ba4358d..c127abf3c0f 100644 --- a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerExchange.java +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3ServerExchange.java @@ -108,6 +108,11 @@ public final class Http3ServerExchange implements Http2TestExchange { rspheadersBuilder = new HttpHeadersBuilder(); } + Http3ServerConnection http3Connection() { + return serverConn; + } + + String connectionTag() { return serverConn.quicConnection().logTag(); } diff --git a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3TestServer.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3TestServer.java index ff76c67ed7e..6e81813cac3 100644 --- a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3TestServer.java +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/http3/Http3TestServer.java @@ -55,6 +55,7 @@ import jdk.internal.net.http.http3.ConnectionSettings; import jdk.internal.net.http.http3.Http3Error; import jdk.internal.net.http.http3.frames.SettingsFrame; import jdk.internal.net.quic.QuicTLSContext; +import jdk.internal.net.quic.QuicTransportErrors; import jdk.internal.net.quic.QuicVersion; import static java.nio.charset.StandardCharsets.US_ASCII; @@ -261,7 +262,23 @@ public class Http3TestServer implements QuicServer.ConnectionAcceptor, AutoClose handler.handle(exchange); } catch (Throwable failure) { System.err.println("Failed to handle exchange: " + failure); - failure.printStackTrace(); + boolean noError = false; + if (exchange instanceof Http3ServerExchange http3ServerExchange) { + var quicConnection = http3ServerExchange.http3Connection().quicConnection(); + var cause = quicConnection.terminationCause(); + if (cause != null) { + var code = cause.getCloseCode(); + noError = cause.isAppLayer() + ? Http3Error.isNoError(code) + : code == QuicTransportErrors.NO_ERROR.code(); + } + } + // don't print the full stack trace if the connection + // is terminated with no error, in order to avoid + // cluttering the log. + if (!noError) { + failure.printStackTrace(); + } final var ioException = (failure instanceof IOException) ? (IOException) failure : new IOException(failure); diff --git a/test/jdk/java/net/httpclient/qpack/BlockingDecodingTest.java b/test/jdk/java/net/httpclient/qpack/BlockingDecodingTest.java index c588f8117ae..778783ad64c 100644 --- a/test/jdk/java/net/httpclient/qpack/BlockingDecodingTest.java +++ b/test/jdk/java/net/httpclient/qpack/BlockingDecodingTest.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 @@ -27,8 +27,6 @@ import jdk.internal.net.http.http3.frames.SettingsFrame; import jdk.internal.net.http.qpack.DecodingCallback; import jdk.internal.net.http.qpack.DynamicTable; import jdk.internal.net.http.qpack.Encoder; -import org.testng.Assert; -import org.testng.annotations.Test; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -43,7 +41,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -import static org.testng.Assert.assertNotEquals; +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import org.junit.jupiter.api.Test; /* * @test @@ -59,7 +59,7 @@ import static org.testng.Assert.assertNotEquals; * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 * @build EncoderDecoderConnector - * @run testng/othervm -Djdk.internal.httpclient.qpack.log.level=EXTRA BlockingDecodingTest + * @run junit/othervm -Djdk.internal.httpclient.qpack.log.level=EXTRA BlockingDecodingTest */ @@ -94,7 +94,7 @@ public class BlockingDecodingTest { encoder.header(context, header.name(), header.value(), false, IGNORE_RECEIVED_COUNT_CHECK); headerFrameWriter.write(headersBb); - assertNotEquals(headersBb.position(), 0); + assertNotEquals(0, headersBb.position()); headersBb.flip(); buffers.add(headersBb); @@ -110,8 +110,8 @@ public class BlockingDecodingTest { // and the default number of blocked streams (0) will be exceeded (1). var lastHttp3Error = decodingCallback.lastHttp3Error.get(); System.err.println("Last Http3Error: " + lastHttp3Error); - Assert.assertEquals(lastHttp3Error, Http3Error.QPACK_DECOMPRESSION_FAILED); - Assert.assertFalse(decodingCallback.completed.isDone()); + Assertions.assertEquals(Http3Error.QPACK_DECOMPRESSION_FAILED, lastHttp3Error); + Assertions.assertFalse(decodingCallback.completed.isDone()); } @Test @@ -149,7 +149,7 @@ public class BlockingDecodingTest { encoder.header(context, expectedHeader.name, expectedHeader.value, false, IGNORE_RECEIVED_COUNT_CHECK); headerFrameWriter.write(headersBb); - assertNotEquals(headersBb.position(), 0); + assertNotEquals(0, headersBb.position()); headersBb.flip(); buffers.add(headersBb); @@ -165,12 +165,12 @@ public class BlockingDecodingTest { // and the default number of blocked streams (0) will be exceeded (1). var lastHttp3Error = decodingCallback.lastHttp3Error.get(); System.err.println("Last Http3Error: " + lastHttp3Error); - Assert.assertNull(lastHttp3Error); - Assert.assertNull(decodingCallback.lastThrowable.get()); - Assert.assertTrue(decodingCallback.completed.isDone()); + Assertions.assertNull(lastHttp3Error); + Assertions.assertNull(decodingCallback.lastThrowable.get()); + Assertions.assertTrue(decodingCallback.completed.isDone()); // Check that onDecoded was called for the test entry var decodedHeader = decodingCallback.decodedHeaders.get(0); - Assert.assertEquals(decodedHeader, expectedHeader); + Assertions.assertEquals(expectedHeader, decodedHeader); } @Test @@ -224,7 +224,7 @@ public class BlockingDecodingTest { IGNORE_RECEIVED_COUNT_CHECK); headerFrameWriter.write(headersBb); } - assertNotEquals(headersBb.position(), 0); + assertNotEquals(0, headersBb.position()); headersBb.flip(); buffers.add(headersBb); @@ -261,13 +261,13 @@ public class BlockingDecodingTest { // Check results of each decoding task for (var decodingResultFuture : decodingTaskResults) { var taskCallback = decodingResultFuture.get(); - Assert.assertNull(taskCallback.lastHttp3Error.get()); - Assert.assertNull(taskCallback.lastThrowable.get()); + Assertions.assertNull(taskCallback.lastHttp3Error.get()); + Assertions.assertNull(taskCallback.lastThrowable.get()); long decodingTaskCompleted = taskCallback.completedTimestamp.get(); System.err.println("Decoding task completion timestamp: " + decodingTaskCompleted); - Assert.assertTrue(decodingTaskCompleted >= updateDoneTimeStamp); + Assertions.assertTrue(decodingTaskCompleted >= updateDoneTimeStamp); var decodedHeaders = taskCallback.decodedHeaders; - Assert.assertEquals(decodedHeaders, expectedHeaders); + Assertions.assertEquals(expectedHeaders, decodedHeaders); } } diff --git a/test/jdk/java/net/httpclient/qpack/DecoderSectionSizeLimitTest.java b/test/jdk/java/net/httpclient/qpack/DecoderSectionSizeLimitTest.java index 4b715a46e08..1ad094916d4 100644 --- a/test/jdk/java/net/httpclient/qpack/DecoderSectionSizeLimitTest.java +++ b/test/jdk/java/net/httpclient/qpack/DecoderSectionSizeLimitTest.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 @@ -37,7 +37,7 @@ * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 * @build EncoderDecoderConnector - * @run testng/othervm -Djdk.internal.httpclient.qpack.log.level=NORMAL + * @run junit/othervm -Djdk.internal.httpclient.qpack.log.level=NORMAL * DecoderSectionSizeLimitTest */ @@ -48,18 +48,21 @@ import jdk.internal.net.http.qpack.DecodingCallback; import jdk.internal.net.http.qpack.DynamicTable; import jdk.internal.net.http.qpack.Encoder; import jdk.test.lib.RandomFactory; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicReference; +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; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class DecoderSectionSizeLimitTest { - @Test(dataProvider = "headerSequences") + @ParameterizedTest + @MethodSource("headerSequences") public void fieldSectionSizeLimitExceeded(List headersSequence, long maxFieldSectionSize) { @@ -144,21 +147,20 @@ public class DecoderSectionSizeLimitTest { System.err.printf("Decoding error observed during buffer #%d processing: %s throwable: %s%n", bufferIdx, decodingError, decodingCallback.lastThrowable.get()); if (decoderErrorExpected) { - Assert.assertEquals(decodingError, Http3Error.QPACK_DECOMPRESSION_FAILED); + Assertions.assertEquals(Http3Error.QPACK_DECOMPRESSION_FAILED, decodingError); return; } else { - Assert.fail("No HTTP/3 error was expected"); + Assertions.fail("No HTTP/3 error was expected"); } } else { System.err.println("Buffer #" + bufferIdx + " readout completed without errors"); } } if (decoderErrorExpected) { - Assert.fail("HTTP/3 error was expected but was not observed"); + Assertions.fail("HTTP/3 error was expected but was not observed"); } } - @DataProvider public Object[][] headerSequences() { List testCases = new ArrayList<>(); for (var sequence : generateHeaderSequences()) { diff --git a/test/jdk/java/net/httpclient/qpack/DecoderTest.java b/test/jdk/java/net/httpclient/qpack/DecoderTest.java index 37f87bdda59..15d4bef7cc9 100644 --- a/test/jdk/java/net/httpclient/qpack/DecoderTest.java +++ b/test/jdk/java/net/httpclient/qpack/DecoderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, 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 @@ -31,8 +31,6 @@ import jdk.internal.net.http.qpack.readers.HeaderFrameReader; import jdk.internal.net.http.qpack.writers.IntegerWriter; import jdk.internal.net.http.qpack.StaticTable; import jdk.internal.net.http.qpack.writers.StringWriter; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.io.IOException; import java.nio.ByteBuffer; @@ -40,7 +38,11 @@ import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; -import static org.testng.Assert.*; +import static 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 @@ -51,8 +53,9 @@ import static org.testng.Assert.*; * java.net.http/jdk.internal.net.http.http3.streams * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 - * @run testng/othervm DecoderTest + * @run junit/othervm DecoderTest */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class DecoderTest { private final Random random = new Random(); @@ -78,7 +81,6 @@ public class DecoderTest { return null; } - @DataProvider(name = "indexProvider") public Object[][] indexProvider() { AtomicInteger tableIndex = new AtomicInteger(); return StaticTable.HTTP3_HEADER_FIELDS.stream() @@ -87,7 +89,6 @@ public class DecoderTest { .toArray(Object[][]::new); } - @DataProvider(name = "nameReferenceProvider") public Object[][] nameReferenceProvider() { AtomicInteger tableIndex = new AtomicInteger(); return StaticTable.HTTP3_HEADER_FIELDS.stream() @@ -95,7 +96,6 @@ public class DecoderTest { .map(List::toArray).toArray(Object[][]::new); } - @DataProvider(name = "literalProvider") public Object[][] literalProvider() { var output = new String[100][]; for (int i = 0; i < 100; i++) { @@ -104,7 +104,8 @@ public class DecoderTest { return output; } - @Test(dataProvider = "indexProvider") + @ParameterizedTest + @MethodSource("indexProvider") public void testIndexedOnStaticTable(int index, HeaderField h) throws IOException { var actual = writeIndex(index); var callback = new TestingCallBack(index, h.name(), h.value()); @@ -112,7 +113,8 @@ public class DecoderTest { dr.decoder().decodeHeader(actual, true, dr.reader()); } - @Test(dataProvider = "nameReferenceProvider") + @ParameterizedTest + @MethodSource("nameReferenceProvider") public void testLiteralWithNameReferenceOnStaticTable(int index, String name, String value) throws IOException { boolean sensitive = random.nextBoolean(); @@ -122,7 +124,8 @@ public class DecoderTest { dr.decoder().decodeHeader(actual, true, dr.reader()); } - @Test(dataProvider = "literalProvider") + @ParameterizedTest + @MethodSource("literalProvider") public void testLiteralWithLiteralNameOnStaticTable(String name, String value) throws IOException { boolean sensitive = random.nextBoolean(); @@ -345,30 +348,30 @@ public class DecoderTest { @Override public void onIndexed(long index, CharSequence name, CharSequence value) { - assertEquals(this.index, index); - assertEquals(this.name, name.toString()); - assertEquals(this.value, value.toString()); + assertEquals(index, this.index); + assertEquals(name.toString(), this.name); + assertEquals(value.toString(), this.value); } @Override public void onLiteralWithNameReference(long index, CharSequence name, CharSequence value, boolean huffmanValue, boolean sensitive) { - assertEquals(this.index, index); - assertEquals(this.value, value.toString()); - assertEquals(this.huffmanValue, huffmanValue); - assertEquals(this.sensitive, sensitive); + assertEquals(index, this.index); + assertEquals(value.toString(), this.value); + assertEquals(huffmanValue, this.huffmanValue); + assertEquals(sensitive, this.sensitive); } @Override public void onLiteralWithLiteralName(CharSequence name, boolean huffmanName, CharSequence value, boolean huffmanValue, boolean sensitive) { - assertEquals(this.name, name.toString()); - assertEquals(this.huffmanName, huffmanName); - assertEquals(this.value, value.toString()); - assertEquals(this.huffmanValue, huffmanValue); - assertEquals(this.sensitive, sensitive); + assertEquals(name.toString(), this.name); + assertEquals(huffmanName, this.huffmanName); + assertEquals(value.toString(), this.value); + assertEquals(huffmanValue, this.huffmanValue); + assertEquals(sensitive, this.sensitive); } @Override diff --git a/test/jdk/java/net/httpclient/qpack/DynamicTableFieldLineRepresentationTest.java b/test/jdk/java/net/httpclient/qpack/DynamicTableFieldLineRepresentationTest.java index cdf584d1854..c314688ab52 100644 --- a/test/jdk/java/net/httpclient/qpack/DynamicTableFieldLineRepresentationTest.java +++ b/test/jdk/java/net/httpclient/qpack/DynamicTableFieldLineRepresentationTest.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 @@ -28,7 +28,6 @@ import jdk.internal.net.http.qpack.DecodingCallback; import jdk.internal.net.http.qpack.DynamicTable; import jdk.internal.net.http.qpack.Encoder; import jdk.test.lib.RandomFactory; -import org.testng.annotations.Test; import java.io.IOException; import java.nio.ByteBuffer; @@ -37,7 +36,8 @@ import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicReference; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; /* * @test @@ -55,7 +55,7 @@ import static org.testng.Assert.*; * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 * @build EncoderDecoderConnector - * @run testng/othervm -Djdk.internal.httpclient.qpack.log.level=EXTRA + * @run junit/othervm -Djdk.internal.httpclient.qpack.log.level=EXTRA * -Djdk.http.qpack.allowBlockingEncoding=true * -Djdk.http.qpack.decoderBlockedStreams=4 * DynamicTableFieldLineRepresentationTest @@ -105,7 +105,7 @@ public class DynamicTableFieldLineRepresentationTest { // Write the header headerFrameWriter.write(headersBb); - assertNotEquals(headersBb.position(), 0); + assertNotEquals(0, headersBb.position()); headersBb.flip(); buffers.add(headersBb); @@ -115,7 +115,7 @@ public class DynamicTableFieldLineRepresentationTest { // Decode headers decoder.decodeHeader(buffers.get(0), false, headerFrameReader); decoder.decodeHeader(buffers.get(1), true, headerFrameReader); - assertEquals(callback.lastIndexedName,name); + assertEquals(name, callback.lastIndexedName); } //4.5.3. Indexed Field Line with Post-Base Index @@ -160,7 +160,7 @@ public class DynamicTableFieldLineRepresentationTest { // Write the header headerFrameWriter.write(headersBb); - assertNotEquals(headersBb.position(), 0); + assertNotEquals(0, headersBb.position()); headersBb.flip(); buffers.add(headersBb); @@ -170,8 +170,8 @@ public class DynamicTableFieldLineRepresentationTest { // Decode headers decoder.decodeHeader(buffers.get(0), false, headerFrameReader); decoder.decodeHeader(buffers.get(1), true, headerFrameReader); - assertEquals(callback.lastIndexedName,name); - assertEquals(callback.lastValue,value); + assertEquals(name, callback.lastIndexedName); + assertEquals(value, callback.lastValue); } // 4.5.4. Literal Field Line with Name Reference @@ -221,7 +221,7 @@ public class DynamicTableFieldLineRepresentationTest { // Write the header headerFrameWriter.write(headersBb); - assertNotEquals(headersBb.position(), 0); + assertNotEquals(0, headersBb.position()); headersBb.flip(); buffers.add(headersBb); @@ -231,7 +231,7 @@ public class DynamicTableFieldLineRepresentationTest { // Decode headers decoder.decodeHeader(buffers.get(0), false, headerFrameReader); decoder.decodeHeader(buffers.get(1), true, headerFrameReader); - assertEquals(callback.lastReferenceName, name); + assertEquals(name, callback.lastReferenceName); } //4.5.5. Literal Field Line with Post-Base Name Reference @@ -276,7 +276,7 @@ public class DynamicTableFieldLineRepresentationTest { // Write the header headerFrameWriter.write(headersBb); - assertNotEquals(headersBb.position(), 0); + assertNotEquals(0, headersBb.position()); headersBb.flip(); buffers.add(headersBb); @@ -286,8 +286,8 @@ public class DynamicTableFieldLineRepresentationTest { // Decode headers decoder.decodeHeader(buffers.get(0), false, headerFrameReader); decoder.decodeHeader(buffers.get(1), true, headerFrameReader); - assertEquals(callback.lastReferenceName, name); - assertEquals(callback.lastValue, value); + assertEquals(name, callback.lastReferenceName); + assertEquals(value, callback.lastValue); } private void configureConnector(EncoderDecoderConnector.EncoderDecoderPair connector, int numberOfEntries){ @@ -362,8 +362,8 @@ public class DynamicTableFieldLineRepresentationTest { @Override public void onIndexed(long actualIndex, CharSequence actualName, CharSequence actualValue) { System.out.println("Indexed called"); - assertEquals(actualName, name); - assertEquals(actualValue, value); + assertEquals(name, actualName); + assertEquals(value, actualValue); lastValue = value; lastIndexedName = name; } @@ -375,8 +375,8 @@ public class DynamicTableFieldLineRepresentationTest { boolean valueHuffman, boolean hideIntermediary) { System.out.println("Literal with name reference called"); - assertEquals(actualName.toString(), name); - assertEquals(actualValue.toString(), value); + assertEquals(name, actualName.toString()); + assertEquals(value, actualValue.toString()); lastReferenceName = name; lastValue = value; } @@ -386,8 +386,8 @@ public class DynamicTableFieldLineRepresentationTest { CharSequence actualValue, boolean valueHuffman, boolean hideIntermediary) { System.out.println("Literal with literal name called"); - assertEquals(actualName.toString(), name); - assertEquals(actualValue.toString(), value); + assertEquals(name, actualName.toString()); + assertEquals(value, actualValue.toString()); lastLiteralName = name; lastValue = value; } diff --git a/test/jdk/java/net/httpclient/qpack/DynamicTableTest.java b/test/jdk/java/net/httpclient/qpack/DynamicTableTest.java index 80765e41787..c340a25088a 100644 --- a/test/jdk/java/net/httpclient/qpack/DynamicTableTest.java +++ b/test/jdk/java/net/httpclient/qpack/DynamicTableTest.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 @@ -27,7 +27,7 @@ * @library /test/lib * @modules java.net.http/jdk.internal.net.http.qpack:+open * java.net.http/jdk.internal.net.http.qpack.readers - * @run testng/othervm -Djdk.internal.httpclient.qpack.log.level=NORMAL DynamicTableTest + * @run junit/othervm -Djdk.internal.httpclient.qpack.log.level=NORMAL DynamicTableTest */ import jdk.internal.net.http.qpack.DynamicTable; @@ -35,9 +35,6 @@ import jdk.internal.net.http.qpack.HeaderField; import jdk.internal.net.http.qpack.QPACK; import jdk.internal.net.http.qpack.readers.IntegerReader; import jdk.test.lib.RandomFactory; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; @@ -47,7 +44,13 @@ import java.util.Arrays; import java.util.Random; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.IntStream; +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; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class DynamicTableTest { // Test for addition to the table and that indices are growing monotonically, @@ -74,7 +77,7 @@ public class DynamicTableTest { long addedId = dynamicTable.insert(name, value); // Check that dynamic table put gives back monotonically increasing indexes - Assert.assertEquals(addedId, lastAddedId); + Assertions.assertEquals(lastAddedId, addedId); if (lastAddedId > maxElementsInTable) { // Check that oldest element is available and not reclaimed @@ -98,21 +101,21 @@ public class DynamicTableTest { long onlyNameSearchResult = dynamicTable.search(rName, "notFoundInTable"); long noMatchResult = dynamicTable.search(HEADER_NAME_PREFIX, HEADER_VALUE_PREFIX); - Assert.assertEquals(fullMatchSearchResult - 1, rid); - Assert.assertEquals(-onlyNameSearchResult - 1, rid); - Assert.assertEquals(noMatchResult, 0); + Assertions.assertEquals(rid, fullMatchSearchResult - 1); + Assertions.assertEquals(rid, -onlyNameSearchResult - 1); + Assertions.assertEquals(0, noMatchResult); } } } - @Test(dataProvider = "randomTableResizeData") + @ParameterizedTest + @MethodSource("randomTableResizeData") public void randomTableResize(int initialSize, long tail, long head, int resizeTo) throws Throwable { HeaderField[] initial = generateHeadersArray(initialSize, tail, head); resizeTestRunner(initial, tail, head, resizeTo); } - @DataProvider public Object[][] randomTableResizeData() { return IntStream.range(0, 1000) .boxed() @@ -127,31 +130,29 @@ public class DynamicTableTest { var dynamicTable = new DynamicTable(QPACK.getLogger().subLogger("tableResizeTests")); // Check that the initial array length is DynamicTable.INITIAL_HOLDER_ARRAY_SIZE - Assert.assertEquals(getElementsArrayLength(dynamicTable), - INITIAL_HOLDER_ARRAY_SIZE); + Assertions.assertEquals( INITIAL_HOLDER_ARRAY_SIZE, getElementsArrayLength(dynamicTable)); // Update dynamic table capacity to maximum allowed value and check // that holder array is not changed dynamicTable.setMaxTableCapacity(IntegerReader.QPACK_MAX_INTEGER_VALUE); dynamicTable.setCapacity(IntegerReader.QPACK_MAX_INTEGER_VALUE); - Assert.assertEquals(getElementsArrayLength(dynamicTable), - INITIAL_HOLDER_ARRAY_SIZE); + Assertions.assertEquals( INITIAL_HOLDER_ARRAY_SIZE, getElementsArrayLength(dynamicTable)); // Add DynamicTable.INITIAL_HOLDER_ARRAY_SIZE + 1 element to the dynamic table // and check that its length is increased 2 times for (int i = 0; i <= INITIAL_HOLDER_ARRAY_SIZE; i++) { dynamicTable.insert("name" + i, "value" + i); } - Assert.assertEquals(getElementsArrayLength(dynamicTable), INITIAL_HOLDER_ARRAY_SIZE << 1); + Assertions.assertEquals(INITIAL_HOLDER_ARRAY_SIZE << 1, getElementsArrayLength(dynamicTable)); } // Test for a simple resize that checks that unique indexes still reference the correct entry - @Test(dataProvider = "simpleTableResizeData") + @ParameterizedTest + @MethodSource("simpleTableResizeData") public void simpleTableResize(HeaderField[] array, long tail, long head, int resizeTo) throws Throwable { resizeTestRunner(array, tail, head, resizeTo); } - @DataProvider public Object[][] simpleTableResizeData() { return new Object[][]{ tableResizeScenario1(), tableResizeScenario2(), @@ -270,13 +271,13 @@ public class DynamicTableTest { } private static void checkResizeResult(HeaderField[] initial, HeaderField[] resized, HeaderField[] expected) { - Assert.assertEquals(resized.length, expected.length); + Assertions.assertEquals(expected.length, resized.length); for (int index = 0; index < expected.length; index++) { if (!sameHeaderField(expected[index], resized[index])) { System.err.println("Initial Array:" + Arrays.deepToString(initial)); System.err.println("Resized Array:" + Arrays.deepToString(resized)); System.err.println("Expected Array:" + Arrays.deepToString(expected)); - Assert.fail("DynamicTable.resize failed"); + Assertions.fail("DynamicTable.resize failed"); } } } @@ -299,7 +300,7 @@ public class DynamicTableTest { MethodType mt = MethodType.methodType(void.class, int.class); return DT_LOOKUP.findVirtual(DynamicTable.class, "resize", mt); } catch (Exception e) { - Assert.fail("Failed to initialize DynamicTable.resize MH", e); + Assertions.fail("Failed to initialize DynamicTable.resize MH", e); return null; } } @@ -308,7 +309,7 @@ public class DynamicTableTest { try { return DT_LOOKUP.findVarHandle(DynamicTable.class, fieldName, fieldType); } catch (Exception e) { - Assert.fail("Failed to initialize DynamicTable private Lookup instance", e); + Assertions.fail("Failed to initialize DynamicTable private Lookup instance", e); return null; } } @@ -318,7 +319,7 @@ public class DynamicTableTest { var vh = DT_LOOKUP.findStaticVarHandle(DynamicTable.class, fieldName, fieldType); return (T) vh.get(); } catch (Exception e) { - Assert.fail("Failed to read DynamicTable static field value", e); + Assertions.fail("Failed to read DynamicTable static field value", e); return null; } } @@ -327,7 +328,7 @@ public class DynamicTableTest { try { return MethodHandles.privateLookupIn(DynamicTable.class, MethodHandles.lookup()); } catch (IllegalAccessException e) { - Assert.fail("Failed to initialize DynamicTable private Lookup instance", e); + Assertions.fail("Failed to initialize DynamicTable private Lookup instance", e); return null; } } diff --git a/test/jdk/java/net/httpclient/qpack/EncoderDecoderConnectionTest.java b/test/jdk/java/net/httpclient/qpack/EncoderDecoderConnectionTest.java index 418af9be2ad..c2bed98bc3c 100644 --- a/test/jdk/java/net/httpclient/qpack/EncoderDecoderConnectionTest.java +++ b/test/jdk/java/net/httpclient/qpack/EncoderDecoderConnectionTest.java @@ -27,12 +27,12 @@ import jdk.internal.net.http.http3.frames.SettingsFrame; import jdk.internal.net.http.qpack.TableEntry; import jdk.internal.net.http.qpack.writers.EncoderInstructionsWriter; import jdk.internal.net.http.qpack.writers.HeaderFrameWriter; -import org.testng.Assert; -import org.testng.annotations.Test; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /* * @test @@ -48,7 +48,7 @@ import java.util.concurrent.atomic.AtomicReference; * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 * @build EncoderDecoderConnector - * @run testng/othervm -Djdk.internal.httpclient.qpack.log.level=EXTRA + * @run junit/othervm -Djdk.internal.httpclient.qpack.log.level=EXTRA * EncoderDecoderConnectionTest */ public class EncoderDecoderConnectionTest { @@ -77,17 +77,17 @@ public class EncoderDecoderConnectionTest { encoder.setTableCapacity(capacityToSet); // Check that no errors observed - Assert.assertNull(encoderErrorHandler.error.get()); - Assert.assertNull(encoderErrorHandler.http3Error.get()); - Assert.assertNull(decoderErrorHandler.error.get()); - Assert.assertNull(decoderErrorHandler.http3Error.get()); + Assertions.assertNull(encoderErrorHandler.error.get()); + Assertions.assertNull(encoderErrorHandler.http3Error.get()); + Assertions.assertNull(decoderErrorHandler.error.get()); + Assertions.assertNull(decoderErrorHandler.http3Error.get()); // Check that encoder's table capacity is updated - Assert.assertEquals(conn.encoderTable().capacity(), capacityToSet); + Assertions.assertEquals(capacityToSet, conn.encoderTable().capacity()); // Since encoder/decoder streams are cross-wired we expect see dynamic // table capacity updated for the decoder too - Assert.assertEquals(conn.decoderTable().capacity(), - conn.encoderTable().capacity()); + Assertions.assertEquals(conn.encoderTable().capacity(), + conn.decoderTable().capacity()); } @Test @@ -122,10 +122,10 @@ public class EncoderDecoderConnectionTest { var encoderInstructionWriter = new EncoderInstructionsWriter(); // Check that no errors observed - Assert.assertNull(encoderErrorHandler.error.get()); - Assert.assertNull(encoderErrorHandler.http3Error.get()); - Assert.assertNull(decoderErrorHandler.error.get()); - Assert.assertNull(decoderErrorHandler.http3Error.get()); + Assertions.assertNull(encoderErrorHandler.error.get()); + Assertions.assertNull(encoderErrorHandler.http3Error.get()); + Assertions.assertNull(decoderErrorHandler.error.get()); + Assertions.assertNull(decoderErrorHandler.http3Error.get()); // Issue the insert instruction on encoder stream conn.encoderTable().insertWithEncoderStreamUpdate(entryToInsert, @@ -133,8 +133,8 @@ public class EncoderDecoderConnectionTest { encoder.newEncodingContext(0, 0, new HeaderFrameWriter())); var encoderHeader = conn.encoderTable().get(0); var decoderHeader = conn.decoderTable().get(0); - Assert.assertEquals(encoderHeader.name(), decoderHeader.name()); - Assert.assertEquals(encoderHeader.value(), decoderHeader.value()); + Assertions.assertEquals(decoderHeader.name(), encoderHeader.name()); + Assertions.assertEquals(decoderHeader.value(), encoderHeader.value()); } @Test @@ -160,12 +160,12 @@ public class EncoderDecoderConnectionTest { // QPACK_ENCODER_STREAM_ERROR is expected on the decoder side // since the decoder dynamic table capacity was not updated - Assert.assertEquals(decoderErrorHandler.http3Error.get(), - Http3Error.QPACK_ENCODER_STREAM_ERROR); + Assertions.assertEquals(Http3Error.QPACK_ENCODER_STREAM_ERROR, + decoderErrorHandler.http3Error.get()); // It is expected that http3 error reported to // the decoder error handler only - Assert.assertNull(encoderErrorHandler.http3Error.get()); + Assertions.assertNull(encoderErrorHandler.http3Error.get()); } @Test @@ -208,13 +208,13 @@ public class EncoderDecoderConnectionTest { System.err.println("Decoder Http3 error: " + decoderHttp3Error); if (encoderError == null || !(encoderError instanceof IOException)) { - Assert.fail("Incorrect encoder error type", encoderError); + Assertions.fail("Incorrect encoder error type", encoderError); } if (decoderError == null || !(decoderError instanceof IOException)) { - Assert.fail("Incorrect decoder error type", decoderError); + Assertions.fail("Incorrect decoder error type", decoderError); } - Assert.assertEquals(encoderHttp3Error, Http3Error.QPACK_DECODER_STREAM_ERROR); - Assert.assertEquals(decoderHttp3Error, Http3Error.QPACK_ENCODER_STREAM_ERROR); + Assertions.assertEquals(Http3Error.QPACK_DECODER_STREAM_ERROR, encoderHttp3Error); + Assertions.assertEquals(Http3Error.QPACK_ENCODER_STREAM_ERROR, decoderHttp3Error); } private static ByteBuffer instructionWithOverflowInteger(int N, int payload) { diff --git a/test/jdk/java/net/httpclient/qpack/EncoderDecoderConnector.java b/test/jdk/java/net/httpclient/qpack/EncoderDecoderConnector.java index 3cf185ff8a7..1eba2b2682a 100644 --- a/test/jdk/java/net/httpclient/qpack/EncoderDecoderConnector.java +++ b/test/jdk/java/net/httpclient/qpack/EncoderDecoderConnector.java @@ -44,7 +44,6 @@ import jdk.internal.net.http.quic.streams.QuicSenderStream; import jdk.internal.net.http.quic.streams.QuicStream; import jdk.internal.net.http.quic.streams.QuicStreamWriter; import jdk.internal.net.quic.QuicTLSEngine; -import org.testng.Assert; import java.io.IOException; import java.lang.invoke.MethodHandles; @@ -58,6 +57,7 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Stream; +import org.junit.jupiter.api.Assertions; /** * Instance of this class provides a stubbed Quic Connection implementation that @@ -175,7 +175,7 @@ public class EncoderDecoderConnector { try { return MethodHandles.privateLookupIn(clz, MethodHandles.lookup()); } catch (IllegalAccessException e) { - Assert.fail("Failed to initialize private Lookup instance", e); + Assertions.fail("Failed to initialize private Lookup instance", e); return null; } } @@ -185,7 +185,7 @@ public class EncoderDecoderConnector { try { return lookup.findVarHandle(recv, "dynamicTable", DynamicTable.class); } catch (Exception e) { - Assert.fail("Failed to acquire dynamic table VarHandle instance", e); + Assertions.fail("Failed to acquire dynamic table VarHandle instance", e); return null; } } diff --git a/test/jdk/java/net/httpclient/qpack/EncoderDecoderTest.java b/test/jdk/java/net/httpclient/qpack/EncoderDecoderTest.java index a1fa9745e05..7dc1bf73960 100644 --- a/test/jdk/java/net/httpclient/qpack/EncoderDecoderTest.java +++ b/test/jdk/java/net/httpclient/qpack/EncoderDecoderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, 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,8 +27,6 @@ import jdk.internal.net.http.qpack.Encoder; import jdk.internal.net.http.qpack.HeaderField; import jdk.internal.net.http.hpack.QuickHuffman; import jdk.internal.net.http.qpack.StaticTable; -import org.testng.annotations.Test; -import org.testng.annotations.DataProvider; import java.io.IOException; import java.nio.ByteBuffer; @@ -41,10 +39,13 @@ import java.util.Random; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -import static org.testng.Assert.assertEquals; -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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /* * @test @@ -60,8 +61,9 @@ import static org.testng.Assert.fail; * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 * @build EncoderDecoderConnector - * @run testng/othervm EncoderDecoderTest + * @run junit/othervm EncoderDecoderTest */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class EncoderDecoderTest { private final Random random = new Random(); @@ -72,7 +74,6 @@ public class EncoderDecoderTest { fail(http3Error + "QPACK error:" + http3Error, error); } - @DataProvider(name = "indexProvider") public Object[][] indexProvider() { AtomicLong index = new AtomicLong(); return StaticTable.HTTP3_HEADER_FIELDS.stream() @@ -81,7 +82,6 @@ public class EncoderDecoderTest { .toArray(Object[][]::new); } - @DataProvider(name = "nameReferenceProvider") public Object[][] nameReferenceProvider() { AtomicLong tableIndex = new AtomicLong(); Map> map = new HashMap<>(); @@ -98,7 +98,6 @@ public class EncoderDecoderTest { .map(List::toArray).toArray(Object[][]::new); } - @DataProvider(name = "literalProvider") public Object[][] literalProvider() { var output = new String[100][]; for (int i = 0; i < 100; i++) { @@ -112,7 +111,8 @@ public class EncoderDecoderTest { if (error != null) throw new AssertionError(error); } - @Test(dataProvider = "indexProvider") + @ParameterizedTest + @MethodSource("indexProvider") public void encodeDecodeIndexedOnStaticTable(long index, HeaderField h) throws IOException { var actual = allocateIndexTestBuffer(index); List buffers = new ArrayList<>(); @@ -148,7 +148,7 @@ public class EncoderDecoderTest { // Write the header headerFrameWriter.write(actual); - assertNotEquals(actual.position(), 0); + assertNotEquals(0, actual.position()); actual.flip(); buffers.add(actual); @@ -161,7 +161,8 @@ public class EncoderDecoderTest { assertNotFailed(error); } - @Test(dataProvider = "nameReferenceProvider") + @ParameterizedTest + @MethodSource("nameReferenceProvider") public void encodeDecodeLiteralWithNameRefOnStaticTable(String name, String value, List validIndices) throws IOException { long index = Collections.max(validIndices); boolean sensitive = random.nextBoolean(); @@ -194,7 +195,7 @@ public class EncoderDecoderTest { // Write the header headerFrameWriter.write(actual); - assertNotEquals(actual.position(), 0); + assertNotEquals(0, actual.position()); actual.flip(); buffers.add(actual); @@ -207,7 +208,8 @@ public class EncoderDecoderTest { assertNotFailed(error); } - @Test(dataProvider = "literalProvider") + @ParameterizedTest + @MethodSource("literalProvider") public void encodeDecodeLiteralWithLiteralNameOnStaticTable(String name, String value) throws IOException { boolean sensitive = random.nextBoolean(); List buffers = new ArrayList<>(); @@ -237,7 +239,7 @@ public class EncoderDecoderTest { encoder.header(context, name, value, sensitive); // Write the header headerFrameWriter.write(actual); - assertNotEquals(actual.position(), 0); + assertNotEquals(0, actual.position()); actual.flip(); buffers.add(actual); @@ -412,9 +414,9 @@ public class EncoderDecoderTest { @Override public void onIndexed(long actualIndex, CharSequence actualName, CharSequence actualValue) { - assertEquals(actualIndex, index); - assertEquals(actualName, name); - assertEquals(actualValue, value); + assertEquals(index, actualIndex); + assertEquals(name, actualName); + assertEquals(value, actualValue); } @Override @@ -422,21 +424,21 @@ public class EncoderDecoderTest { CharSequence actualValue, boolean huffmanValue, boolean actualHideIntermediary) { assertTrue(validIndices.contains(actualIndex)); - assertEquals(actualName.toString(), name); - assertEquals(actualValue.toString(), value); + assertEquals(name, actualName.toString()); + assertEquals(value, actualValue.toString()); assertEquals(huffmanValue, huffmanValue); - assertEquals(actualHideIntermediary, sensitive); + assertEquals(sensitive, actualHideIntermediary); } @Override public void onLiteralWithLiteralName(CharSequence actualName, boolean actualHuffmanName, CharSequence actualValue, boolean actualHuffmanValue, boolean actualHideIntermediary) { - assertEquals(actualName.toString(), name); - assertEquals(actualHuffmanName, huffmanName); - assertEquals(actualValue.toString(), value); - assertEquals(actualHuffmanValue, huffmanValue); - assertEquals(actualHideIntermediary, sensitive); + assertEquals(name, actualName.toString()); + assertEquals(huffmanName, actualHuffmanName); + assertEquals(value, actualValue.toString()); + assertEquals(huffmanValue, actualHuffmanValue); + assertEquals(sensitive, actualHideIntermediary); } } } diff --git a/test/jdk/java/net/httpclient/qpack/EncoderTest.java b/test/jdk/java/net/httpclient/qpack/EncoderTest.java index a80a0899420..b721fa3d27a 100644 --- a/test/jdk/java/net/httpclient/qpack/EncoderTest.java +++ b/test/jdk/java/net/httpclient/qpack/EncoderTest.java @@ -46,8 +46,6 @@ import jdk.internal.net.http.quic.streams.QuicSenderStream.SendingStreamState; import jdk.internal.net.http.quic.streams.QuicStream; import jdk.internal.net.http.quic.streams.QuicStreamWriter; import jdk.internal.net.quic.QuicTLSEngine; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.io.IOException; import java.net.InetSocketAddress; @@ -69,7 +67,10 @@ import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Stream; -import static org.testng.Assert.*; +import static 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 @@ -84,15 +85,15 @@ import static org.testng.Assert.*; * java.net.http/jdk.internal.net.http.http3.streams * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 - * @run testng/othervm EncoderTest + * @run junit/othervm EncoderTest */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class EncoderTest { private final Random random = new Random(); private final IntegerWriter intWriter = new IntegerWriter(); private final StringWriter stringWriter = new StringWriter(); private static final int TEST_STR_MAX_LENGTH = 10; - @DataProvider(name = "indexProvider") public Object[][] indexProvider() { AtomicInteger tableIndex = new AtomicInteger(); return StaticTable.HTTP3_HEADER_FIELDS.stream() @@ -101,7 +102,6 @@ public class EncoderTest { .toArray(Object[][]::new); } - @DataProvider public Object[][] staticNameReferenceProvider() { AtomicInteger tableIndex = new AtomicInteger(); Map> map = new HashMap<>(); @@ -117,7 +117,6 @@ public class EncoderTest { .map(List::toArray).toArray(Object[][]::new); } - @DataProvider public Object[][] literalsProvider() { var output = new String[100][]; for (int i = 0; i < 100; i++) { @@ -161,7 +160,8 @@ public class EncoderTest { fail(http3Error + "QPACK error:" + http3Error, error); } - @Test(dataProvider = "indexProvider") + @ParameterizedTest + @MethodSource("indexProvider") public void testFieldLineWriterWithStaticIndex(int index, HeaderField h) { var actual = allocateIndexBuffer(index); var expected = writeIndex(index); @@ -177,14 +177,15 @@ public class EncoderTest { encoder.header(context, h.name(), h.value(), false); headerFrameWriter.write(actual); - assertNotEquals(actual.position(), 0); + assertNotEquals(0, actual.position()); actual.flip(); - assertEquals(actual, expected, debug(h.name(), h.value(), actual, expected)); + assertEquals(expected, actual, debug(h.name(), h.value(), actual, expected)); assertNotFailed(error); } - @Test(dataProvider = "staticNameReferenceProvider") + @ParameterizedTest + @MethodSource("staticNameReferenceProvider") public void testInsertWithStaticTableNameReference(String name, String value, List validIndices) { int index = Collections.max(validIndices); @@ -203,7 +204,7 @@ public class EncoderTest { encoder.newEncodingContext(0, 0, headerFrameWriter); encoder.header(context, name, value, false); headerFrameWriter.write(actual); - assertNotEquals(actual.position(), 0); + assertNotEquals(0, actual.position()); actual.flip(); TestQuicStreamWriter quicStreamWriter = quicConnection.sender.writer; @@ -212,7 +213,8 @@ public class EncoderTest { assertNotFailed(error); } - @Test(dataProvider = "staticNameReferenceProvider") + @ParameterizedTest + @MethodSource("staticNameReferenceProvider") public void testFieldLineWithStaticTableNameReference(String name, String value, List validIndices) { int index = Collections.max(validIndices); boolean sensitive = random.nextBoolean(); @@ -231,14 +233,15 @@ public class EncoderTest { encoder.newEncodingContext(0, 0, headerFrameWriter); encoder.header(context, name, value, sensitive); headerFrameWriter.write(actual); - assertNotEquals(actual.position(), 0); + assertNotEquals(0, actual.position()); actual.flip(); assertTrue(expected.contains(actual), debug(name, value, actual, expected)); assertNotFailed(error); } - @Test(dataProvider = "literalsProvider") + @ParameterizedTest + @MethodSource("literalsProvider") public void testInsertWithLiterals(String name, String value) { var expected = writeInsertLiteral(name, value); var actual = allocateInsertLiteralBuffer(name, value); @@ -255,14 +258,15 @@ public class EncoderTest { encoder.newEncodingContext(0, 0, headerFrameWriter); encoder.header(context, name, value, false); headerFrameWriter.write(actual); - assertNotEquals(actual.position(), 0); + assertNotEquals(0, actual.position()); actual.flip(); TestQuicStreamWriter quicStreamWriter = quicConnection.sender.writer; - assertEquals(quicStreamWriter.get(), expected, debug(name, value, quicStreamWriter.get(), expected)); + assertEquals(expected, quicStreamWriter.get(), debug(name, value, quicStreamWriter.get(), expected)); assertNotFailed(error); } - @Test(dataProvider = "literalsProvider") + @ParameterizedTest + @MethodSource("literalsProvider") public void testFieldLineEncodingWithLiterals(String name, String value) { boolean sensitive = random.nextBoolean(); @@ -280,10 +284,10 @@ public class EncoderTest { encoder.newEncodingContext(0, 0, headerFrameWriter); encoder.header(context, name, value, sensitive); headerFrameWriter.write(actual); - assertNotEquals(actual.position(), 0); + assertNotEquals(0, actual.position()); actual.flip(); - assertEquals(actual, expected, debug(name, value, actual, expected)); + assertEquals(expected, actual, debug(name, value, actual, expected)); assertNotFailed(error); } diff --git a/test/jdk/java/net/httpclient/qpack/EntriesEvictionTest.java b/test/jdk/java/net/httpclient/qpack/EntriesEvictionTest.java index c295ec5d01d..76d15d0ace9 100644 --- a/test/jdk/java/net/httpclient/qpack/EntriesEvictionTest.java +++ b/test/jdk/java/net/httpclient/qpack/EntriesEvictionTest.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 @@ -35,7 +35,7 @@ * java.net.http/jdk.internal.net.http.http3.streams * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 - * @run testng/othervm -Djdk.internal.httpclient.qpack.log.level=EXTRA EntriesEvictionTest + * @run junit/othervm -Djdk.internal.httpclient.qpack.log.level=EXTRA EntriesEvictionTest */ import java.util.ArrayList; @@ -47,13 +47,16 @@ import jdk.internal.net.http.qpack.Encoder.SectionReference; import jdk.internal.net.http.qpack.HeaderField; import jdk.internal.net.http.qpack.QPACK; import jdk.internal.net.http.qpack.QPACK.Logger; -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.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class EntriesEvictionTest { - @Test(dataProvider = "evictionScenarios") + @ParameterizedTest + @MethodSource("evictionScenarios") public void evictionInsertionTest(TestHeader headerToAdd, SectionReference sectionReference, long insertedId, @@ -71,12 +74,12 @@ public class EntriesEvictionTest { // Insert last entry long id = dynamicTable.insert(headerToAdd.name, headerToAdd.value, sectionReference); - Assert.assertEquals(id, insertedId); + Assertions.assertEquals(insertedId, id); if (largestEvictedId != -1) { // Check that evicted entry with the largest absolute index // is not accessible - Assert.assertThrows(() -> dynamicTable.get(largestEvictedId)); + Assertions.assertThrows(Throwable.class, () -> dynamicTable.get(largestEvictedId)); // Check that an entry after that can be acquired with its // absolute index dynamicTable.get(largestEvictedId + 1); @@ -84,12 +87,11 @@ public class EntriesEvictionTest { if (insertedId != -1) { HeaderField insertedField = dynamicTable.get(insertedId); - Assert.assertEquals(insertedField, - new HeaderField(headerToAdd.name(), headerToAdd.value())); + Assertions.assertEquals(new HeaderField(headerToAdd.name(), headerToAdd.value()), + insertedField); } } - @DataProvider public static Object[][] evictionScenarios() { // Header that requires only one entry to be evicted diff --git a/test/jdk/java/net/httpclient/qpack/FieldSectionPrefixTest.java b/test/jdk/java/net/httpclient/qpack/FieldSectionPrefixTest.java index e9a7a86e975..b6fac8291f8 100644 --- a/test/jdk/java/net/httpclient/qpack/FieldSectionPrefixTest.java +++ b/test/jdk/java/net/httpclient/qpack/FieldSectionPrefixTest.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 @@ -30,7 +30,7 @@ * java.net.http/jdk.internal.net.http.http3.streams * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 - * @run testng FieldSectionPrefixTest + * @run junit FieldSectionPrefixTest */ @@ -41,21 +41,26 @@ import jdk.internal.net.http.qpack.FieldSectionPrefix; import jdk.internal.net.http.qpack.QPACK; import jdk.internal.net.http.qpack.readers.HeaderFrameReader; import jdk.internal.net.http.qpack.writers.FieldLineSectionPrefixWriter; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.io.IOException; import java.nio.ByteBuffer; -import java.util.ArrayList; import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Stream; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class FieldSectionPrefixTest { private static final long DT_CAPACITY = 220L; private static final long MAX_ENTRIES = DT_CAPACITY / 32L; - @Test(dataProvider = "encodingCases") + @ParameterizedTest + @MethodSource("encodingCases") public void encodingTest(long base, long requiredInsertCount, byte expectedRic, byte expectedBase) { var fieldSectionPrefix = new FieldSectionPrefix(requiredInsertCount, base); @@ -64,23 +69,23 @@ public class FieldSectionPrefixTest { var byteBuffer = ByteBuffer.allocate(bytesNeeded); writer.write(byteBuffer); byteBuffer.flip(); - Assert.assertEquals(byteBuffer.get(0), expectedRic); - Assert.assertEquals(byteBuffer.get(1), expectedBase); + Assertions.assertEquals(expectedRic, byteBuffer.get(0)); + Assertions.assertEquals(expectedBase, byteBuffer.get(1)); } - @DataProvider(name = "encodingCases") - public Object[][] encodingCases() { - var cases = new ArrayList(); - // Simple with 0 values - cases.add(new Object[]{0L, 0L, (byte) 0x0, (byte) 0x0}); - // Based on RFC-9204: "B.2. Dynamic Table example" - cases.add(new Object[]{0L, 2L, (byte) 0x3, (byte) 0x81}); - // Based on RFC-9204: "Duplicate Instruction, Stream Cancellation" - cases.add(new Object[]{4L, 4L, (byte) 0x5, (byte) 0x0}); - return cases.toArray(Object[][]::new); + public Stream encodingCases() { + return Stream.of( + // Simple with 0 values + Arguments.of(0L, 0L, (byte) 0x0, (byte) 0x0), + // Based on RFC-9204: "B.2. Dynamic Table example" + Arguments.of(0L, 2L, (byte) 0x3, (byte) 0x81), + // Based on RFC-9204: "Duplicate Instruction, Stream Cancellation" + Arguments.of(4L, 4L, (byte) 0x5, (byte) 0x0) + ); } - @Test(dataProvider = "decodingCases") + @ParameterizedTest + @MethodSource("decodingCases") public void decodingTest(long expectedRIC, long expectedBase, byte... bytes) throws IOException { var logger = QPACK.getLogger().subLogger("decodingTest"); var dt = new DynamicTable(logger, false); @@ -117,17 +122,16 @@ public class FieldSectionPrefixTest { System.err.println("Required Insert Count:" + fsp.requiredInsertCount()); System.err.println("Base:" + fsp.base()); - Assert.assertEquals(fsp.requiredInsertCount(), expectedRIC); - Assert.assertEquals(fsp.base(), expectedBase); + Assertions.assertEquals(expectedRIC, fsp.requiredInsertCount()); + Assertions.assertEquals(expectedBase, fsp.base()); } - @DataProvider(name = "decodingCases") - public Object[][] decodingCases() { - var cases = new ArrayList(); - cases.add(new Object[]{0L, 0L, (byte) 0x0, (byte) 0x0}); - cases.add(new Object[]{4L, 4L, (byte) 0x5, (byte) 0x0}); - cases.add(new Object[]{2L, 0L, (byte) 0x3, (byte) 0x81}); - return cases.toArray(Object[][]::new); + public Stream decodingCases() { + return Stream.of( + Arguments.of(0L, 0L, new byte[]{0x0, 0x0}), + Arguments.of(4L, 4L, new byte[]{0x5, 0x0}), + Arguments.of(2L, 0L, new byte[]{0x3, (byte) 0x81}) + ); } } diff --git a/test/jdk/java/net/httpclient/qpack/IntegerReaderMaxValuesTest.java b/test/jdk/java/net/httpclient/qpack/IntegerReaderMaxValuesTest.java index 6f21549f497..ac156e2b547 100644 --- a/test/jdk/java/net/httpclient/qpack/IntegerReaderMaxValuesTest.java +++ b/test/jdk/java/net/httpclient/qpack/IntegerReaderMaxValuesTest.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 @@ -24,12 +24,13 @@ import jdk.internal.net.http.qpack.QPackException; import jdk.internal.net.http.qpack.readers.IntegerReader; import jdk.internal.net.http.qpack.writers.IntegerWriter; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.nio.ByteBuffer; import java.util.stream.IntStream; +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 @@ -39,11 +40,11 @@ import java.util.stream.IntStream; * java.net.http/jdk.internal.net.http.qpack * java.net.http/jdk.internal.net.http.qpack.readers * java.net.http/jdk.internal.net.http.qpack.writers - * @run testng/othervm -Djdk.internal.httpclient.qpack.log.level=INFO + * @run junit/othervm -Djdk.internal.httpclient.qpack.log.level=INFO * IntegerReaderMaxValuesTest */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class IntegerReaderMaxValuesTest { - @DataProvider public Object[][] nValues() { return IntStream.range(1, 8) .boxed() @@ -51,7 +52,8 @@ public class IntegerReaderMaxValuesTest { .toArray(Object[][]::new); } - @Test(dataProvider = "nValues") + @ParameterizedTest + @MethodSource("nValues") public void maxIntegerWriteRead(int N) { IntegerWriter writer = new IntegerWriter(); writer.configure(IntegerReader.QPACK_MAX_INTEGER_VALUE, N, 0); @@ -62,23 +64,26 @@ public class IntegerReaderMaxValuesTest { buffer.flip(); reader.read(buffer); long result = reader.get(); - Assert.assertEquals(result, IntegerReader.QPACK_MAX_INTEGER_VALUE); + Assertions.assertEquals(IntegerReader.QPACK_MAX_INTEGER_VALUE, result); } - @Test(dataProvider = "nValues", expectedExceptions = QPackException.class) + @ParameterizedTest + @MethodSource("nValues") public void overflowInteger(int N) { - // Construct buffer with overflowed integer - ByteBuffer overflowBuffer = ByteBuffer.allocate(11); + Assertions.assertThrows(QPackException.class, () -> { + // Construct buffer with overflowed integer + ByteBuffer overflowBuffer = ByteBuffer.allocate(11); - overflowBuffer.put((byte) ((2 << (N - 1)) - 1)); - for (int i = 0; i < 9; i++) { - overflowBuffer.put((byte) 128); - } - overflowBuffer.put((byte) 10); - overflowBuffer.flip(); - // Read the buffer with IntegerReader - IntegerReader reader = new IntegerReader(); - reader.configure(N); - reader.read(overflowBuffer); + overflowBuffer.put((byte) ((2 << (N - 1)) - 1)); + for (int i = 0; i < 9; i++) { + overflowBuffer.put((byte) 128); + } + overflowBuffer.put((byte) 10); + overflowBuffer.flip(); + // Read the buffer with IntegerReader + IntegerReader reader = new IntegerReader(); + reader.configure(N); + reader.read(overflowBuffer); + }); } } diff --git a/test/jdk/java/net/httpclient/qpack/StaticTableFieldsTest.java b/test/jdk/java/net/httpclient/qpack/StaticTableFieldsTest.java index 662d0c264d8..eea9b31e932 100644 --- a/test/jdk/java/net/httpclient/qpack/StaticTableFieldsTest.java +++ b/test/jdk/java/net/httpclient/qpack/StaticTableFieldsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2023, 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 @@ -24,21 +24,23 @@ /* * @test * @modules java.net.http/jdk.internal.net.http.qpack - * @run testng/othervm -Djdk.internal.httpclient.qpack.log.level=NORMAL StaticTableFieldsTest + * @run junit/othervm -Djdk.internal.httpclient.qpack.log.level=NORMAL StaticTableFieldsTest */ import jdk.internal.net.http.qpack.StaticTable; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class StaticTableFieldsTest { - @BeforeTest + @BeforeAll public void setUp() { // Populate expected table as defined by RFC expectedTable = new ArrayList<>(); @@ -66,10 +68,10 @@ public class StaticTableFieldsTest { @Test public void testStaticTable() { - assertEquals(actualTable.size(), expectedTable.size()); + assertEquals(expectedTable.size(), actualTable.size()); for (int i = 0; i < expectedTable.size(); i++) { - assertEquals(actualTable.get(i).name(), expectedTable.get(i).name()); - assertEquals(actualTable.get(i).value(), expectedTable.get(i).value()); + assertEquals(expectedTable.get(i).name(), actualTable.get(i).name()); + assertEquals(expectedTable.get(i).value(), actualTable.get(i).value()); } } diff --git a/test/jdk/java/net/httpclient/qpack/StringLengthLimitsTest.java b/test/jdk/java/net/httpclient/qpack/StringLengthLimitsTest.java index ade50d2843b..7c94abf1504 100644 --- a/test/jdk/java/net/httpclient/qpack/StringLengthLimitsTest.java +++ b/test/jdk/java/net/httpclient/qpack/StringLengthLimitsTest.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 @@ -34,9 +34,6 @@ import jdk.internal.net.http.qpack.readers.StringReader; import jdk.internal.net.http.qpack.writers.HeaderFrameWriter; import jdk.internal.net.http.qpack.writers.IntegerWriter; import jdk.internal.net.http.qpack.writers.StringWriter; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.io.IOException; import java.net.ProtocolException; @@ -44,6 +41,10 @@ import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; +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 @@ -59,12 +60,12 @@ import java.util.concurrent.atomic.AtomicReference; * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 * @build EncoderDecoderConnector - * @run testng/othervm -Djdk.http.qpack.allowBlockingEncoding=true + * @run junit/othervm -Djdk.http.qpack.allowBlockingEncoding=true * StringLengthLimitsTest */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class StringLengthLimitsTest { - @DataProvider Object[][] stringReaderLimitsData() { return new Object[][]{ {STRING_READER_STRING_LENGTH, STRING_READER_STRING_LENGTH, false, false}, @@ -74,7 +75,8 @@ public class StringLengthLimitsTest { }; } - @Test(dataProvider = "stringReaderLimitsData") + @ParameterizedTest + @MethodSource("stringReaderLimitsData") public void stringReaderLimits(int length, int limit, boolean huffmanBit, boolean exceptionExpected) throws IOException { IntegerWriter intWriter = new IntegerWriter(); @@ -82,26 +84,25 @@ public class StringLengthLimitsTest { var byteBuffer = ByteBuffer.allocate(2); if (!intWriter.write(byteBuffer)) { - Assert.fail("Error with test buffer preparations"); + Assertions.fail("Error with test buffer preparations"); } byteBuffer.flip(); StringReader stringReader = new StringReader(); StringBuilder unusedOutput = new StringBuilder(); if (exceptionExpected) { - QPackException exception = Assert.expectThrows(QPackException.class, + QPackException exception = Assertions.assertThrows(QPackException.class, () -> stringReader.read(byteBuffer, unusedOutput, limit)); Throwable cause = exception.getCause(); - Assert.assertNotNull(cause); - Assert.assertTrue(cause instanceof ProtocolException); + Assertions.assertNotNull(cause); + Assertions.assertTrue(cause instanceof ProtocolException); System.err.println("Got expected ProtocolException: " + cause); } else { boolean done = stringReader.read(byteBuffer, unusedOutput, limit); - Assert.assertFalse(done, "read done"); + Assertions.assertFalse(done, "read done"); } } - @DataProvider Object[][] encoderInstructionLimitsData() { int maxEntrySize = ENCODER_INSTRUCTIONS_DT_CAPACITY - 32; return new Object[][]{ @@ -144,7 +145,8 @@ public class StringLengthLimitsTest { }; } - @Test(dataProvider = "encoderInstructionLimitsData") + @ParameterizedTest + @MethodSource("encoderInstructionLimitsData") public void encoderInstructionLimits(EncoderInstruction instruction, int nameLength, boolean nameHuffman, int valueLength, boolean valueHuffman, @@ -177,9 +179,9 @@ public class StringLengthLimitsTest { } Throwable error = observedError.get(); if (successExpected && error != null) { - Assert.fail("Unexpected error", error); + Assertions.fail("Unexpected error", error); } else if (error == null && !successExpected) { - Assert.fail("Expected error"); + Assertions.fail("Expected error"); } } @@ -244,7 +246,6 @@ public class StringLengthLimitsTest { return instructionBuffers; } - @DataProvider Object[][] fieldLineLimitsData() { return new Object[][]{ // Post-Base Index @@ -273,7 +274,8 @@ public class StringLengthLimitsTest { }; } - @Test(dataProvider = "fieldLineLimitsData") + @ParameterizedTest + @MethodSource("fieldLineLimitsData") public void fieldLineLimits(int nameLength, int valueLength, String name, String value, boolean isPostBase, boolean successExpected) throws IOException { @@ -385,9 +387,9 @@ public class StringLengthLimitsTest { var error = decodingCallbackError.get(); System.err.println("Decoding callback error: " + error); if (successExpected && error != null) { - Assert.fail("Unexpected error", error); + Assertions.fail("Unexpected error", error); } else if (error == null && !successExpected) { - Assert.fail("Error expected"); + Assertions.fail("Error expected"); } } diff --git a/test/jdk/java/net/httpclient/qpack/TablesIndexerTest.java b/test/jdk/java/net/httpclient/qpack/TablesIndexerTest.java index 4ed489ca6dd..1a175342c6b 100644 --- a/test/jdk/java/net/httpclient/qpack/TablesIndexerTest.java +++ b/test/jdk/java/net/httpclient/qpack/TablesIndexerTest.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 @@ -24,7 +24,7 @@ /* * @test * @modules java.net.http/jdk.internal.net.http.qpack - * @run testng/othervm -Djdk.internal.httpclient.qpack.log.level=INFO TablesIndexerTest + * @run junit/othervm -Djdk.internal.httpclient.qpack.log.level=INFO TablesIndexerTest */ import jdk.internal.net.http.qpack.DynamicTable; @@ -33,9 +33,6 @@ import jdk.internal.net.http.qpack.QPACK; import jdk.internal.net.http.qpack.StaticTable; import jdk.internal.net.http.qpack.TableEntry; import jdk.internal.net.http.qpack.TablesIndexer; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; @@ -44,10 +41,14 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import static jdk.internal.net.http.qpack.TableEntry.EntryType; +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; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TablesIndexerTest { - @DataProvider(name = "indicesLookupData") public Object[][] indicesData() { List tcs = new ArrayList<>(); @@ -68,7 +69,8 @@ public class TablesIndexerTest { return tcs.toArray(Object[][]::new); } - @Test(dataProvider = "indicesLookupData") + @ParameterizedTest + @MethodSource("indicesData") public void checkIndicesLookup(String name, String value, String dynamicTableValue, Set indices, EntryType type) { @@ -88,45 +90,46 @@ public class TablesIndexerTest { IGNORE_RECEIVED_COUNT_CHECK); // TableEntry should be for static table only - Assert.assertTrue(tableEntry.isStaticTable()); + Assertions.assertTrue(tableEntry.isStaticTable()); // If value is not equal to dynamicTableValue, the full name:dynamicTableValue // should be found in the dynamic table with index 0 if (!value.equals(dynamicTableValue)) { TableEntry dtEntry = tablesIndexer.entryOf(name, dynamicTableValue, IGNORE_RECEIVED_COUNT_CHECK); - Assert.assertFalse(dtEntry.isStaticTable()); - Assert.assertEquals(dtEntry.type(), EntryType.NAME_VALUE); - Assert.assertEquals(dtEntry.index(), 0L); + Assertions.assertFalse(dtEntry.isStaticTable()); + Assertions.assertEquals(EntryType.NAME_VALUE, dtEntry.type()); + Assertions.assertEquals(0L, dtEntry.index()); } // Check that found index is contained in a set and returned indices match - Assert.assertTrue(indices.contains(tableEntry.index())); + Assertions.assertTrue(indices.contains(tableEntry.index())); // Check that entry type matches - Assert.assertEquals(tableEntry.type(), type); + Assertions.assertEquals(type, tableEntry.type()); var headerField = STATIC_TABLE.get(tableEntry.index()); // Check that name and/or value matches the one that can be acquired by // using looked-up index if (tableEntry.type() == EntryType.NAME) { - Assert.assertEquals(headerField.name(), name); + Assertions.assertEquals(name, headerField.name()); // If only name entry is found huffmanName should be set to false - Assert.assertFalse(tableEntry.huffmanName()); + Assertions.assertFalse(tableEntry.huffmanName()); } else if (tableEntry.type() == EntryType.NAME_VALUE) { - Assert.assertEquals(headerField.name(), name); - Assert.assertEquals(headerField.value(), value); + Assertions.assertEquals(name, headerField.name()); + Assertions.assertEquals(value, headerField.value()); // If "name:value" match is found huffmanName and huffmanValue should // be set to false - Assert.assertFalse(tableEntry.huffmanName()); - Assert.assertFalse(tableEntry.huffmanValue()); + Assertions.assertFalse(tableEntry.huffmanName()); + Assertions.assertFalse(tableEntry.huffmanValue()); } else { - Assert.fail("Unexpected TableEntry type returned:" + tableEntry); + Assertions.fail("Unexpected TableEntry type returned:" + tableEntry); } } - @Test(dataProvider = "unacknowledgedEntriesLookupData") + @ParameterizedTest + @MethodSource("unacknowledgedEntriesLookupData") public void unacknowledgedEntryLookup(String headerName, String headerValue, boolean staticEntryExpected, EntryType expectedType) { @@ -137,12 +140,11 @@ public class TablesIndexerTest { // Search for an entry in the dynamic and the static tables var entry = tablesIndexer.entryOf(headerName, headerValue, TEST_KNOWN_RECEIVED_COUNT); // Check that entry references expected table - Assert.assertEquals(entry.isStaticTable(), staticEntryExpected); + Assertions.assertEquals(staticEntryExpected, entry.isStaticTable()); // And the type of found entry matches expectations - Assert.assertEquals(entry.type(), expectedType); + Assertions.assertEquals(expectedType, entry.type()); } - @DataProvider public Object[][] unacknowledgedEntriesLookupData() { List data = new ArrayList<>(); data.add(new Object[]{USER_AGENT_ST_NAME, "not-in-dynamic", true, EntryType.NAME}); diff --git a/test/jdk/java/net/httpclient/qpack/UnacknowledgedInsertionTest.java b/test/jdk/java/net/httpclient/qpack/UnacknowledgedInsertionTest.java index 7b621e2d69d..5d0129234f3 100644 --- a/test/jdk/java/net/httpclient/qpack/UnacknowledgedInsertionTest.java +++ b/test/jdk/java/net/httpclient/qpack/UnacknowledgedInsertionTest.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 @@ -26,9 +26,6 @@ import jdk.internal.net.http.http3.Http3Error; import jdk.internal.net.http.http3.frames.SettingsFrame; import jdk.internal.net.http.qpack.DecodingCallback; import jdk.internal.net.http.qpack.Encoder; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -38,7 +35,11 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -import static org.testng.Assert.assertNotEquals; +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /* * @test @@ -56,11 +57,13 @@ import static org.testng.Assert.assertNotEquals; * java.net.http/jdk.internal.net.http.http3.frames * java.net.http/jdk.internal.net.http.http3 * @build EncoderDecoderConnector - * @run testng/othervm -Djdk.internal.httpclient.qpack.log.level=EXTRA UnacknowledgedInsertionTest + * @run junit/othervm -Djdk.internal.httpclient.qpack.log.level=EXTRA UnacknowledgedInsertionTest */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class UnacknowledgedInsertionTest { - @Test(dataProvider = "duplicateEntryInsertions") + @ParameterizedTest + @MethodSource("duplicateEntryInsertionsData") public void unacknowledgedDoubleInsertion(long knownReceiveCount, List expectedHeadersEncodingType) throws Exception { // When knownReceiveCount is set to -1 the Encoder.knownReceiveCount() // value is used to encode headers - otherwise the provided value is used @@ -101,10 +104,10 @@ public class UnacknowledgedInsertionTest { } // Only two entries are expected to be inserted to the dynamic table - Assert.assertEquals(ed.decoderTable().insertCount(), 2); + Assertions.assertEquals(2, ed.decoderTable().insertCount()); // Check that headers byte buffer is not empty - assertNotEquals(headersBb.position(), 0); + assertNotEquals(0, headersBb.position()); headersBb.flip(); buffers.add(headersBb); @@ -119,11 +122,10 @@ public class UnacknowledgedInsertionTest { .stream() .map(DecodedHeader::encodingType) .toList(); - Assert.assertEquals(actualHeaderEncodingTypes, expectedHeadersEncodingType); + Assertions.assertEquals(expectedHeadersEncodingType, actualHeaderEncodingTypes); } - @DataProvider(name = "duplicateEntryInsertions") private Object[][] duplicateEntryInsertionsData() { return new Object[][]{ {0, List.of(EncodingType.LITERAL, EncodingType.LITERAL, EncodingType.LITERAL)}, @@ -167,7 +169,7 @@ public class UnacknowledgedInsertionTest { @Override public void onDecoded(CharSequence name, CharSequence value) { - Assert.fail("onDecoded not expected to be called"); + Assertions.fail("onDecoded not expected to be called"); } @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 8eb7a3663d8..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 @@ -47,6 +47,7 @@ import jdk.internal.net.http.common.MinimalFuture; import jdk.internal.net.http.quic.QuicClient; import jdk.internal.net.http.quic.QuicConnectionId; import jdk.internal.net.http.quic.QuicConnectionImpl; +import jdk.internal.net.http.quic.QuicTransportParameters; import jdk.internal.net.http.quic.TerminationCause; import jdk.internal.net.quic.QuicTLSContext; import jdk.internal.net.quic.QuicVersion; @@ -58,11 +59,13 @@ import static jdk.internal.net.http.quic.TerminationCause.forTransportError; import static jdk.internal.net.quic.QuicTransportErrors.NO_VIABLE_PATH; 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.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /* * @test + * @bug 8373877 * @summary verify that when a QUIC (client) connection receives a stateless reset * from the peer, then the connection is properly terminated * @library /test/lib /test/jdk/java/net/httpclient/lib @@ -73,20 +76,20 @@ 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}) .sslContext(sslContext) .build(); + // Use a longer max ack delay to inflate the draining time (3xPTO) + final QuicTransportParameters transportParameters = new QuicTransportParameters(); + transportParameters.setIntParameter(QuicTransportParameters.ParameterId.max_ack_delay, + (1 << 14) - 1); // 16 seconds, maximum allowed server.start(); System.out.println("Server started at " + server.getAddress()); } @@ -179,6 +182,9 @@ public class StatelessResetReceiptTest { conn.close(); // verify connection is no longer open assertFalse(conn.underlyingQuicConnection().isOpen(), "QUIC connection is still open"); + // Check that the (closing) connection is still registered with the endpoint + assertNotEquals(0, conn.endpoint().connectionCount(), + "Expected the QUIC connection to be registered"); // now send a stateless reset from the server connection sendStatelessResetFrom(serverConn); // wait for the stateless reset to be processed @@ -231,12 +237,19 @@ public class StatelessResetReceiptTest { .loggedAs("intentionally closed by server to initiate draining state" + " on client connection"); serverConn.connectionTerminator().terminate(tc); + // send ping in case the connection_close message gets lost + conn.underlyingQuicConnection().requestSendPing(); // wait for client conn to terminate final TerminationCause clientTC = ((QuicConnectionImpl) conn.underlyingQuicConnection()) .futureTerminationCause().get(); // verify connection closed for the right reason assertEquals(NO_VIABLE_PATH.code(), clientTC.getCloseCode(), "unexpected termination cause"); + // wait for a while to let the connection close completely + Thread.sleep(10); + // Check that the (draining) connection is still registered with the endpoint + assertNotEquals(0, conn.endpoint().connectionCount(), + "Expected the QUIC connection to be registered"); // now send a stateless reset from the server connection sendStatelessResetFrom(serverConn); // wait for the stateless reset to be processed 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/DummyWebSocketServer.java b/test/jdk/java/net/httpclient/websocket/DummyWebSocketServer.java index 9034cf9f28a..abc1748e3f2 100644 --- a/test/jdk/java/net/httpclient/websocket/DummyWebSocketServer.java +++ b/test/jdk/java/net/httpclient/websocket/DummyWebSocketServer.java @@ -351,7 +351,14 @@ public class DummyWebSocketServer implements Closeable { if (!started.get()) { throw new IllegalStateException("Not yet started"); } - return URI.create("ws://localhost:" + address.getPort()); + String ip = address.getAddress().isAnyLocalAddress() + ? InetAddress.getLoopbackAddress().getHostAddress() + : address.getAddress().getHostAddress(); + if (ip.indexOf(':') >= 0) { + ip = String.format("[%s]", ip); + } + + return URI.create("ws://" + ip + ":" + address.getPort()); } private boolean readRequest(SocketChannel channel, StringBuilder request) 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/websocket/WebSocketTest.java b/test/jdk/java/net/httpclient/websocket/WebSocketTest.java index 83f8b6eab27..43bcb054b7d 100644 --- a/test/jdk/java/net/httpclient/websocket/WebSocketTest.java +++ b/test/jdk/java/net/httpclient/websocket/WebSocketTest.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 @@ -23,8 +23,10 @@ /* * @test - * @bug 8217429 + * @bug 8217429 8208693 + * @library ../access * @build DummyWebSocketServer + * java.net.http/jdk.internal.net.http.HttpClientTimerAccess * @run testng/othervm * WebSocketTest */ @@ -40,6 +42,7 @@ import java.net.http.WebSocket; import java.net.http.WebSocketHandshakeException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; @@ -48,6 +51,7 @@ import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; @@ -58,6 +62,7 @@ import static java.net.http.HttpClient.Builder.NO_PROXY; import static java.net.http.HttpClient.newBuilder; import static java.net.http.WebSocket.NORMAL_CLOSURE; import static java.nio.charset.StandardCharsets.UTF_8; +import static jdk.internal.net.http.HttpClientTimerAccess.assertNoResponseTimerEventRegistrations; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertThrows; import static org.testng.Assert.fail; @@ -143,6 +148,45 @@ public class WebSocketTest { } } + /** + * Verifies that the internally issued request to establish the WebSocket + * connection does not leave any response timers registered at the client + * after the WebSocket handshake. + */ + @Test + public void responseTimerCleanUp() throws Exception { + try (var server = new DummyWebSocketServer()) { + server.open(); + try (var client = newBuilder().proxy(NO_PROXY).build()) { + var connectionEstablished = new CountDownLatch(1); + var webSocketListener = new WebSocket.Listener() { + + @Override + public void onOpen(WebSocket webSocket) { + connectionEstablished.countDown(); + } + + }; + var webSocket = client + .newWebSocketBuilder() + // Explicitly configure a timeout to get a response + // timer event get registered at the client. The query + // should succeed without timing out. + .connectTimeout(Duration.ofMinutes(2)) + .buildAsync(server.getURI(), webSocketListener) + .join(); + try { + connectionEstablished.await(); + // We expect the response timer event to get evicted once + // the WebSocket handshake headers are received. + assertNoResponseTimerEventRegistrations(client); + } finally { + webSocket.abort(); + } + } + } + } + @Test public void partialBinaryThenText() throws IOException { try (var server = new DummyWebSocketServer()) { 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/net/vthread/BlockingSocketOps.java b/test/jdk/java/net/vthread/BlockingSocketOps.java index 3c6b9cd5276..ef58e06b915 100644 --- a/test/jdk/java/net/vthread/BlockingSocketOps.java +++ b/test/jdk/java/net/vthread/BlockingSocketOps.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 @@ -21,15 +21,15 @@ * questions. */ -/** +/* * @test id=default - * @bug 8284161 + * @bug 8284161 8372958 * @summary Test virtual threads doing blocking I/O on java.net Sockets * @library /test/lib * @run junit BlockingSocketOps */ -/** +/* * @test id=poller-modes * @requires (os.family == "linux") | (os.family == "mac") * @library /test/lib @@ -37,7 +37,7 @@ * @run junit/othervm -Djdk.pollerMode=2 BlockingSocketOps */ -/** +/* * @test id=no-vmcontinuations * @requires vm.continuations * @library /test/lib @@ -60,6 +60,8 @@ import java.net.SocketTimeoutException; import jdk.test.lib.thread.VThreadRunner; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.*; class BlockingSocketOps { @@ -90,19 +92,8 @@ class BlockingSocketOps { /** * Virtual thread blocks in read. */ - @Test - void testSocketRead1() throws Exception { - testSocketRead(0); - } - - /** - * Virtual thread blocks in timed read. - */ - @Test - void testSocketRead2() throws Exception { - testSocketRead(60_000); - } - + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) void testSocketRead(int timeout) throws Exception { VThreadRunner.run(() -> { try (var connection = new Connection()) { @@ -202,19 +193,8 @@ class BlockingSocketOps { /** * Socket close while virtual thread blocked in read. */ - @Test - void testSocketReadAsyncClose1() throws Exception { - testSocketReadAsyncClose(0); - } - - /** - * Socket close while virtual thread blocked in timed read. - */ - @Test - void testSocketReadAsyncClose2() throws Exception { - testSocketReadAsyncClose(0); - } - + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) void testSocketReadAsyncClose(int timeout) throws Exception { VThreadRunner.run(() -> { try (var connection = new Connection()) { @@ -230,7 +210,34 @@ class BlockingSocketOps { try { int n = s.getInputStream().read(); fail("read " + n); - } catch (SocketException expected) { } + } catch (SocketException expected) { + log(expected); + } + } + }); + } + + /** + * Socket shutdownInput while virtual thread blocked in read. + */ + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) + void testSocketReadAsyncShutdownInput(int timeout) throws Exception { + VThreadRunner.run(() -> { + try (var connection = new Connection()) { + Socket s = connection.socket1(); + + // delayed shutdown of input stream + InputStream in = s.getInputStream(); + runAfterParkedAsync(s::shutdownInput); + + // read should return -1 + if (timeout > 0) { + s.setSoTimeout(timeout); + } + assertEquals(-1, in.read()); + assertEquals(0, in.available()); + assertFalse(s.isClosed()); } }); } @@ -238,19 +245,8 @@ class BlockingSocketOps { /** * Virtual thread interrupted while blocked in Socket read. */ - @Test - void testSocketReadInterrupt1() throws Exception { - testSocketReadInterrupt(0); - } - - /** - * Virtual thread interrupted while blocked in Socket read with timeout - */ - @Test - void testSocketReadInterrupt2() throws Exception { - testSocketReadInterrupt(60_000); - } - + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) void testSocketReadInterrupt(int timeout) throws Exception { VThreadRunner.run(() -> { try (var connection = new Connection()) { @@ -269,6 +265,7 @@ class BlockingSocketOps { int n = s.getInputStream().read(); fail("read " + n); } catch (SocketException expected) { + log(expected); assertTrue(Thread.interrupted()); assertTrue(s.isClosed()); } @@ -285,7 +282,7 @@ class BlockingSocketOps { try (var connection = new Connection()) { Socket s = connection.socket1(); - // delayedclose of s + // delayed close of s runAfterParkedAsync(s::close); // write to s should block, then throw @@ -295,7 +292,36 @@ class BlockingSocketOps { for (;;) { out.write(ba); } - } catch (SocketException expected) { } + } catch (SocketException expected) { + log(expected); + } + } + }); + } + + /** + * Socket shutdownOutput while virtual thread blocked in write. + */ + @Test + void testSocketWriteAsyncShutdownOutput() throws Exception { + VThreadRunner.run(() -> { + try (var connection = new Connection()) { + Socket s = connection.socket1(); + + // delayed shutdown of output stream + OutputStream out = s.getOutputStream(); + runAfterParkedAsync(s::shutdownOutput); + + // write to s should block, then throw + try { + byte[] ba = new byte[100*1024]; + for (;;) { + out.write(ba); + } + } catch (SocketException expected) { + log(expected); + } + assertFalse(s.isClosed()); } }); } @@ -321,6 +347,7 @@ class BlockingSocketOps { out.write(ba); } } catch (SocketException expected) { + log(expected); assertTrue(Thread.interrupted()); assertTrue(s.isClosed()); } @@ -355,7 +382,9 @@ class BlockingSocketOps { try { s1.getInputStream().read(ba); fail(); - } catch (SocketTimeoutException expected) { } + } catch (SocketTimeoutException expected) { + log(expected); + } } }); } @@ -384,19 +413,8 @@ class BlockingSocketOps { /** * Virtual thread blocks in accept. */ - @Test - void testServerSocketAccept2() throws Exception { - testServerSocketAccept(0); - } - - /** - * Virtual thread blocks in timed accept. - */ - @Test - void testServerSocketAccept3() throws Exception { - testServerSocketAccept(60_000); - } - + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) void testServerSocketAccept(int timeout) throws Exception { VThreadRunner.run(() -> { try (var listener = new ServerSocket()) { @@ -422,19 +440,8 @@ class BlockingSocketOps { /** * ServerSocket close while virtual thread blocked in accept. */ - @Test - void testServerSocketAcceptAsyncClose1() throws Exception { - testServerSocketAcceptAsyncClose(0); - } - - /** - * ServerSocket close while virtual thread blocked in timed accept. - */ - @Test - void testServerSocketAcceptAsyncClose2() throws Exception { - testServerSocketAcceptAsyncClose(60_000); - } - + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) void testServerSocketAcceptAsyncClose(int timeout) throws Exception { VThreadRunner.run(() -> { try (var listener = new ServerSocket()) { @@ -451,7 +458,9 @@ class BlockingSocketOps { try { listener.accept().close(); fail("connection accepted???"); - } catch (SocketException expected) { } + } catch (SocketException expected) { + log(expected); + } } }); } @@ -459,19 +468,8 @@ class BlockingSocketOps { /** * Virtual thread interrupted while blocked in ServerSocket accept. */ - @Test - void testServerSocketAcceptInterrupt1() throws Exception { - testServerSocketAcceptInterrupt(0); - } - - /** - * Virtual thread interrupted while blocked in ServerSocket accept with timeout. - */ - @Test - void testServerSocketAcceptInterrupt2() throws Exception { - testServerSocketAcceptInterrupt(60_000); - } - + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) void testServerSocketAcceptInterrupt(int timeout) throws Exception { VThreadRunner.run(() -> { try (var listener = new ServerSocket()) { @@ -490,6 +488,7 @@ class BlockingSocketOps { listener.accept().close(); fail("connection accepted???"); } catch (SocketException expected) { + log(expected); assertTrue(Thread.interrupted()); assertTrue(listener.isClosed()); } @@ -529,20 +528,9 @@ class BlockingSocketOps { /** * Virtual thread blocks in DatagramSocket receive. */ - @Test - void testDatagramSocketSendReceive2() throws Exception { - testDatagramSocketSendReceive(0); - } - - /** - * Virtual thread blocks in DatagramSocket receive with timeout. - */ - @Test - void testDatagramSocketSendReceive3() throws Exception { - testDatagramSocketSendReceive(60_000); - } - - private void testDatagramSocketSendReceive(int timeout) throws Exception { + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) + void testDatagramSocketSendReceive(int timeout) throws Exception { VThreadRunner.run(() -> { try (DatagramSocket s1 = new DatagramSocket(null); DatagramSocket s2 = new DatagramSocket(null)) { @@ -585,7 +573,9 @@ class BlockingSocketOps { try { s.receive(p); fail(); - } catch (SocketTimeoutException expected) { } + } catch (SocketTimeoutException expected) { + log(expected); + } } }); } @@ -593,20 +583,9 @@ class BlockingSocketOps { /** * DatagramSocket close while virtual thread blocked in receive. */ - @Test - void testDatagramSocketReceiveAsyncClose1() throws Exception { - testDatagramSocketReceiveAsyncClose(0); - } - - /** - * DatagramSocket close while virtual thread blocked with timeout. - */ - @Test - void testDatagramSocketReceiveAsyncClose2() throws Exception { - testDatagramSocketReceiveAsyncClose(60_000); - } - - private void testDatagramSocketReceiveAsyncClose(int timeout) throws Exception { + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) + void testDatagramSocketReceiveAsyncClose(int timeout) throws Exception { VThreadRunner.run(() -> { try (DatagramSocket s = new DatagramSocket(null)) { InetAddress lh = InetAddress.getLoopbackAddress(); @@ -624,7 +603,9 @@ class BlockingSocketOps { DatagramPacket p = new DatagramPacket(ba, ba.length); s.receive(p); fail(); - } catch (SocketException expected) { } + } catch (SocketException expected) { + log(expected); + } } }); } @@ -632,20 +613,9 @@ class BlockingSocketOps { /** * Virtual thread interrupted while blocked in DatagramSocket receive. */ - @Test - void testDatagramSocketReceiveInterrupt1() throws Exception { - testDatagramSocketReceiveInterrupt(0); - } - - /** - * Virtual thread interrupted while blocked in DatagramSocket receive with timeout. - */ - @Test - void testDatagramSocketReceiveInterrupt2() throws Exception { - testDatagramSocketReceiveInterrupt(60_000); - } - - private void testDatagramSocketReceiveInterrupt(int timeout) throws Exception { + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) + void testDatagramSocketReceiveInterrupt(int timeout) throws Exception { VThreadRunner.run(() -> { try (DatagramSocket s = new DatagramSocket(null)) { InetAddress lh = InetAddress.getLoopbackAddress(); @@ -665,6 +635,7 @@ class BlockingSocketOps { s.receive(p); fail(); } catch (SocketException expected) { + log(expected); assertTrue(Thread.interrupted()); assertTrue(s.isClosed()); } @@ -737,4 +708,11 @@ class BlockingSocketOps { } }); } + + /** + * Log to System.err to inline with the JUnit messages. + */ + static void log(Throwable e) { + System.err.println(e); + } } diff --git a/test/jdk/java/nio/channels/AsynchronousFileChannel/BufferPositions.java b/test/jdk/java/nio/channels/AsynchronousFileChannel/BufferPositions.java new file mode 100644 index 00000000000..661696a0581 --- /dev/null +++ b/test/jdk/java/nio/channels/AsynchronousFileChannel/BufferPositions.java @@ -0,0 +1,189 @@ +/* + * 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 8374382 + * @summary Test AsynchronousFileChannel.read/write with ByteBuffers and varied buffer positions + * @run junit/othervm BufferPositions + */ + +import java.lang.foreign.Arena; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousFileChannel; +import java.nio.channels.CompletionHandler; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Stream; +import static java.nio.file.StandardOpenOption.*; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import static org.junit.jupiter.api.Assertions.*; + +class BufferPositions { + + private static final int BUF_SIZE = 32; + + /** + * The buffers to test. + */ + static Stream buffers() { + List buffers = List.of( + ByteBuffer.allocate(BUF_SIZE), + ByteBuffer.allocateDirect(BUF_SIZE), + ByteBuffer.wrap(new byte[BUF_SIZE]), + Arena.global().allocate(BUF_SIZE).asByteBuffer(), + Arena.ofAuto().allocate(BUF_SIZE).asByteBuffer(), + Arena.ofShared().allocate(BUF_SIZE).asByteBuffer() + ); + Stream slices = buffers.stream() + .map(bb -> bb.slice(1, bb.capacity() - 1)); + return Stream.concat(buffers.stream(), slices); + } + + /** + * Test using an AsynchronousFileChannel to read bytes into the given buffer. + */ + @ParameterizedTest + @MethodSource("buffers") + void testRead(ByteBuffer bb) throws Exception { + Path file = Files.createTempFile(Path.of("."), "test", "dat"); + + // populate temp file + int size = bb.capacity(); + byte[] contents = new byte[size]; + for (int i = 0; i < size; i++) { + contents[i] = (byte)(i + 1); + } + Files.write(file, contents); + + // read bytes using the buffer as the destination and all possible buffer positions + try (AsynchronousFileChannel ch = AsynchronousFileChannel.open(file, READ)) { + for (int filePosition = 0; filePosition < size; filePosition++) { + for (int bufPos = 0; bufPos < size; bufPos++) { + // read one byte + bb.position(bufPos); + bb.limit(bufPos + 1); + int n = read(ch, filePosition, bb); + assertEquals(1, n); + assertEquals(bufPos + 1, bb.position()); + assertEquals(contents[filePosition], bb.get(bufPos)); + } + } + } + } + + /** + * Test using an AsynchronousFileChannel to write bytes from the given buffer. + */ + @ParameterizedTest + @MethodSource("buffers") + void testWrite(ByteBuffer bb) throws Exception { + Path file = Files.createTempFile(Path.of("."), "test", "dat"); + + // populate temp file, all zeros + int size = bb.capacity(); + byte[] contents = new byte[size]; + Files.write(file, contents); + + // write bytes using the buffer as the source and all possible buffer positions + try (AsynchronousFileChannel ch = AsynchronousFileChannel.open(file, READ, WRITE)) { + for (int filePosition = 0; filePosition < size; filePosition++) { + for (int bufPos = 0; bufPos < size; bufPos++) { + // write one byte + byte b = (byte) ThreadLocalRandom.current().nextInt(); + bb.position(bufPos); + bb.limit(bufPos + 1); + bb.put(bufPos, b); + int n = write(ch, filePosition, bb); + assertEquals(1, n); + assertEquals(bufPos + 1, bb.position()); + assertEquals(b, bb.get(bufPos)); + + // check byte was written at the expected file position + ByteBuffer dst = ByteBuffer.allocate(1); + int nread = ch.read(dst, filePosition).get(); + assertEquals(1, nread); + assertEquals(b, dst.get(0)); + } + } + } + } + + /** + * Reads a byte from a channel into the given buffer, at the given file position. + */ + private int read(AsynchronousFileChannel ch, long position, ByteBuffer bb) throws Exception { + if (ThreadLocalRandom.current().nextBoolean()) { + return ch.read(bb, position).get(); + } else { + var handler = new Handler(); + ch.read(bb, position, null, handler); + return handler.result(); + } + } + + /** + * Writes a byte to a channel from the given buffer, at the given file position. + */ + private int write(AsynchronousFileChannel ch, long position, ByteBuffer bb) throws Exception { + if (ThreadLocalRandom.current().nextBoolean()) { + return ch.write(bb, position).get(); + } else { + var handler = new Handler(); + ch.write(bb, position, null, handler); + return handler.result(); + } + } + + /** + * CompletionHandler that defines a method to await the result of an I/O operation. + */ + private static class Handler implements CompletionHandler { + T result; + Throwable ex; + final CountDownLatch done = new CountDownLatch(1); + + @Override + public void completed(T result, Void att) { + this.result = result; + done.countDown(); + } + + @Override + public void failed(Throwable ex, Void att) { + this.ex = ex; + done.countDown(); + } + + T result() throws InterruptedException { + done.await(); + assertNull(ex); + return result; + } + } +} diff --git a/test/jdk/java/nio/channels/Channels/SocketChannelStreams.java b/test/jdk/java/nio/channels/Channels/SocketChannelStreams.java index 72c07392d7c..519de1e725f 100644 --- a/test/jdk/java/nio/channels/Channels/SocketChannelStreams.java +++ b/test/jdk/java/nio/channels/Channels/SocketChannelStreams.java @@ -22,10 +22,10 @@ */ /* @test - * @bug 8279339 - * @run testng SocketChannelStreams + * @bug 8279339 8371718 * @summary Exercise InputStream/OutputStream returned by Channels.newXXXStream * when channel is a SocketChannel + * @run testng SocketChannelStreams */ import java.io.Closeable; @@ -35,6 +35,8 @@ import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.channels.ByteChannel; import java.nio.channels.Channels; import java.nio.channels.IllegalBlockingModeException; import java.nio.channels.ServerSocketChannel; @@ -51,6 +53,9 @@ import static org.testng.Assert.*; @Test public class SocketChannelStreams { + // Maximum size of internal temporary buffer + private static final int MAX_BUFFER_SIZE = 128*1024; + private ScheduledExecutorService executor; @BeforeClass() @@ -379,6 +384,25 @@ public class SocketChannelStreams { }); } + /** + * Test that internal buffers have at most MAX_BUFFER_SIZE bytes remaining. + */ + public void testReadLimit() throws IOException { + InputStream in = Channels.newInputStream(new TestChannel()); + byte[] b = new byte[3*MAX_BUFFER_SIZE]; + int n = in.read(b, 0, b.length); + assertEquals(n, MAX_BUFFER_SIZE); + } + + /** + * Test that internal buffers have at most MAX_BUFFER_SIZE bytes remaining. + */ + public void testWriteLimit() throws IOException { + OutputStream out = Channels.newOutputStream(new TestChannel()); + byte[] b = new byte[3*MAX_BUFFER_SIZE]; + out.write(b, 0, b.length); + } + // -- test infrastructure -- private interface ThrowingTask { @@ -477,4 +501,40 @@ public class SocketChannelStreams { private Future schedule(Runnable task, long delay) { return executor.schedule(task, delay, TimeUnit.MILLISECONDS); } + + /** + * ByteChannel that throws if more than 128k bytes remain + * in the buffer supplied for reading or writing. + */ + private static class TestChannel implements ByteChannel { + @Override + public int read(ByteBuffer bb) throws IOException { + int rem = bb.remaining(); + if (rem > MAX_BUFFER_SIZE) { + throw new IOException("too big"); + } + bb.position(bb.limit()); + return rem; + } + + @Override + public int write(ByteBuffer bb) throws IOException { + int rem = bb.remaining(); + if (rem > MAX_BUFFER_SIZE) { + throw new IOException("too big"); + } + bb.position(bb.limit()); + return rem; + } + + @Override + public boolean isOpen() { + return true; + } + + @Override + public void close() { + throw new UnsupportedOperationException(); + } + } } diff --git a/test/jdk/java/nio/channels/FileChannel/directio/DirectIOTest.java b/test/jdk/java/nio/channels/FileChannel/directio/DirectIOTest.java index b9dd309d0f7..b6c10a592cc 100644 --- a/test/jdk/java/nio/channels/FileChannel/directio/DirectIOTest.java +++ b/test/jdk/java/nio/channels/FileChannel/directio/DirectIOTest.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 diff --git a/test/jdk/java/nio/channels/FileChannel/directio/libDirectIO.c b/test/jdk/java/nio/channels/FileChannel/directio/libDirectIO.c index 5eea51da4c7..f02a2b53c8f 100644 --- a/test/jdk/java/nio/channels/FileChannel/directio/libDirectIO.c +++ b/test/jdk/java/nio/channels/FileChannel/directio/libDirectIO.c @@ -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 diff --git a/test/jdk/java/nio/channels/spi/SelectorProvider/inheritedChannel/InheritedChannelTest.java b/test/jdk/java/nio/channels/spi/SelectorProvider/inheritedChannel/InheritedChannelTest.java index 99a127ca5ad..934bf509d88 100644 --- a/test/jdk/java/nio/channels/spi/SelectorProvider/inheritedChannel/InheritedChannelTest.java +++ b/test/jdk/java/nio/channels/spi/SelectorProvider/inheritedChannel/InheritedChannelTest.java @@ -40,7 +40,6 @@ * @key intermittent */ -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -77,7 +76,7 @@ public class InheritedChannelTest { }; } - @Test(dataProvider = "testCases", timeOut=30000) + @Test(dataProvider = "testCases") public void test(String desc, List opts) throws Throwable { String pathVar = Platform.sharedLibraryPathVariableName(); System.out.println(pathVar + "=" + libraryPath); diff --git a/test/jdk/java/nio/channels/vthread/BlockingChannelOps.java b/test/jdk/java/nio/channels/vthread/BlockingChannelOps.java index f04bece07b6..eb2229d927a 100644 --- a/test/jdk/java/nio/channels/vthread/BlockingChannelOps.java +++ b/test/jdk/java/nio/channels/vthread/BlockingChannelOps.java @@ -66,6 +66,8 @@ import java.util.concurrent.locks.LockSupport; import jdk.test.lib.thread.VThreadRunner; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.*; class BlockingChannelOps { @@ -301,20 +303,9 @@ class BlockingChannelOps { /** * Virtual thread blocks in SocketChannel adaptor read. */ - @Test - void testSocketAdaptorRead1() throws Exception { - testSocketAdaptorRead(0); - } - - /** - * Virtual thread blocks in SocketChannel adaptor read with timeout. - */ - @Test - void testSocketAdaptorRead2() throws Exception { - testSocketAdaptorRead(60_000); - } - - private void testSocketAdaptorRead(int timeout) throws Exception { + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) + void testSocketAdaptorRead(int timeout) throws Exception { VThreadRunner.run(() -> { try (var connection = new Connection()) { SocketChannel sc1 = connection.channel1(); @@ -420,20 +411,9 @@ class BlockingChannelOps { /** * Virtual thread blocks in ServerSocketChannel adaptor accept. */ - @Test - void testSocketChannelAdaptorAccept1() throws Exception { - testSocketChannelAdaptorAccept(0); - } - - /** - * Virtual thread blocks in ServerSocketChannel adaptor accept with timeout. - */ - @Test - void testSocketChannelAdaptorAccept2() throws Exception { - testSocketChannelAdaptorAccept(60_000); - } - - private void testSocketChannelAdaptorAccept(int timeout) throws Exception { + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) + void testSocketChannelAdaptorAccept(int timeout) throws Exception { VThreadRunner.run(() -> { try (var ssc = ServerSocketChannel.open()) { ssc.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); @@ -546,20 +526,9 @@ class BlockingChannelOps { /** * Virtual thread blocks in DatagramSocket adaptor receive. */ - @Test - void testDatagramSocketAdaptorReceive1() throws Exception { - testDatagramSocketAdaptorReceive(0); - } - - /** - * Virtual thread blocks in DatagramSocket adaptor receive with timeout. - */ - @Test - void testDatagramSocketAdaptorReceive2() throws Exception { - testDatagramSocketAdaptorReceive(60_000); - } - - private void testDatagramSocketAdaptorReceive(int timeout) throws Exception { + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) + void testDatagramSocketAdaptorReceive(int timeout) throws Exception { VThreadRunner.run(() -> { try (DatagramChannel dc1 = DatagramChannel.open(); DatagramChannel dc2 = DatagramChannel.open()) { @@ -585,21 +554,9 @@ class BlockingChannelOps { /** * DatagramChannel close while virtual thread blocked in adaptor receive. */ - @Test - void testDatagramSocketAdaptorReceiveAsyncClose1() throws Exception { - testDatagramSocketAdaptorReceiveAsyncClose(0); - } - - /** - * DatagramChannel close while virtual thread blocked in adaptor receive - * with timeout. - */ - @Test - void testDatagramSocketAdaptorReceiveAsyncClose2() throws Exception { - testDatagramSocketAdaptorReceiveAsyncClose(60_1000); - } - - private void testDatagramSocketAdaptorReceiveAsyncClose(int timeout) throws Exception { + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) + void testDatagramSocketAdaptorReceiveAsyncClose(int timeout) throws Exception { VThreadRunner.run(() -> { try (DatagramChannel dc = DatagramChannel.open()) { InetAddress lh = InetAddress.getLoopbackAddress(); @@ -621,21 +578,9 @@ class BlockingChannelOps { /** * Virtual thread interrupted while blocked in DatagramSocket adaptor receive. */ - @Test - void testDatagramSocketAdaptorReceiveInterrupt1() throws Exception { - testDatagramSocketAdaptorReceiveInterrupt(0); - } - - /** - * Virtual thread interrupted while blocked in DatagramSocket adaptor receive - * with timeout. - */ - @Test - void testDatagramSocketAdaptorReceiveInterrupt2() throws Exception { - testDatagramSocketAdaptorReceiveInterrupt(60_1000); - } - - private void testDatagramSocketAdaptorReceiveInterrupt(int timeout) throws Exception { + @ParameterizedTest + @ValueSource(ints = { 0, 60_000 }) + void testDatagramSocketAdaptorReceiveInterrupt(int timeout) throws Exception { VThreadRunner.run(() -> { try (DatagramChannel dc = DatagramChannel.open()) { InetAddress lh = InetAddress.getLoopbackAddress(); diff --git a/test/jdk/java/nio/file/Files/NotADirectory.java b/test/jdk/java/nio/file/Files/NotADirectory.java index bd561ca5c4b..5bae8a6caa2 100644 --- a/test/jdk/java/nio/file/Files/NotADirectory.java +++ b/test/jdk/java/nio/file/Files/NotADirectory.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 @@ -22,9 +22,10 @@ */ /* @test - * @bug 8356678 + * @bug 8356678 8374441 * @requires (os.family != "windows") - * @summary Test Files operations when a path component is not a directory + * @summary Test Files and FileSystemProvider operations when a path component + * is not a directory * @run junit NotADirectory */ @@ -32,10 +33,12 @@ import java.io.IOException; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.FileSystemException; +import java.nio.file.FileSystems; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.PosixFileAttributes; +import java.nio.file.spi.FileSystemProvider; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; @@ -51,10 +54,14 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class NotADirectory { + private static final FileSystemProvider PROVIDER = + FileSystems.getDefault().provider(); + private static final Path ROOT = Path.of("."); private static final Path NOT_EXIST = ROOT.resolve("notExist"); private static final Path DIR = ROOT.resolve("dir"); @@ -143,6 +150,18 @@ public class NotADirectory { () -> Files.readAttributes(BOGUS, PosixFileAttributes.class)); } + @Test + public void readBasicIfExists() throws IOException { + assertNull( + PROVIDER.readAttributesIfExists(BOGUS, BasicFileAttributes.class)); + } + + @Test + public void readPosixIfExists() throws IOException { + assertNull( + PROVIDER.readAttributesIfExists(BOGUS, PosixFileAttributes.class)); + } + @Test public void exists() throws IOException { assertFalse(Files.exists(BOGUS)); diff --git a/test/jdk/java/nio/file/Path/UriImportExport.java b/test/jdk/java/nio/file/Path/UriImportExport.java index 2ab93ee399e..6a0dd1acc8e 100644 --- a/test/jdk/java/nio/file/Path/UriImportExport.java +++ b/test/jdk/java/nio/file/Path/UriImportExport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 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 diff --git a/test/jdk/java/nio/file/attribute/UserDefinedFileAttributeView/Basic.java b/test/jdk/java/nio/file/attribute/UserDefinedFileAttributeView/Basic.java index 92ab35ce5d0..4586c33521f 100644 --- a/test/jdk/java/nio/file/attribute/UserDefinedFileAttributeView/Basic.java +++ b/test/jdk/java/nio/file/attribute/UserDefinedFileAttributeView/Basic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 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 diff --git a/test/jdk/java/nio/file/spi/CustomSystemClassLoader.java b/test/jdk/java/nio/file/spi/CustomSystemClassLoader.java index 8ad9a41c5fd..aa19206bd29 100644 --- a/test/jdk/java/nio/file/spi/CustomSystemClassLoader.java +++ b/test/jdk/java/nio/file/spi/CustomSystemClassLoader.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 diff --git a/test/jdk/java/nio/file/spi/SetDefaultProvider.java b/test/jdk/java/nio/file/spi/SetDefaultProvider.java index 4d74c8fee93..69da5ff0933 100644 --- a/test/jdk/java/nio/file/spi/SetDefaultProvider.java +++ b/test/jdk/java/nio/file/spi/SetDefaultProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 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 diff --git a/test/jdk/java/rmi/server/RemoteServer/AddrInUse.java b/test/jdk/java/rmi/server/RemoteServer/AddrInUse.java index 34e343b6193..86ac5b0313b 100644 --- a/test/jdk/java/rmi/server/RemoteServer/AddrInUse.java +++ b/test/jdk/java/rmi/server/RemoteServer/AddrInUse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -24,7 +24,6 @@ /* @test * @bug 4111507 * @summary retryServerSocket should not retry on BindException - * @author Ann Wollrath * * @run main/othervm AddrInUse */ @@ -33,75 +32,54 @@ import java.net.ServerSocket; import java.rmi.registry.LocateRegistry; import java.rmi.server.ExportException; -public class AddrInUse implements Runnable { +public class AddrInUse { - private static int port = -1; - private static final long TIMEOUT = 10000; - - private boolean exportSucceeded = false; - private Throwable exportException = null; - - public void run() { - - /* - * Attempt to create (i.e. export) a registry on the port that - * has already been bound, and record the result. - */ - try { - LocateRegistry.createRegistry(port); - synchronized (this) { - exportSucceeded = true; - notifyAll(); - } - } catch (Throwable t) { - synchronized (this) { - exportException = t; - notifyAll(); - } - } - } + private static volatile Throwable registryExportFailure = null; public static void main(String[] args) throws Exception { - System.err.println("\nRegression test for bug 4111507\n"); - /* * Bind a server socket to a port. */ - ServerSocket server = new ServerSocket(0); - port = server.getLocalPort(); - System.err.println("Created a ServerSocket on port " + port + "..."); - - /* - * Start a thread that creates a registry on the same port, - * and analyze the result. - */ - System.err.println("create a registry on the same port..."); - System.err.println("(should cause an ExportException)"); - AddrInUse obj = new AddrInUse(); - synchronized (obj) { - (new Thread(obj, "AddrInUse")).start(); + try (ServerSocket server = new ServerSocket(0)) { + int port = server.getLocalPort(); + System.err.println("Created a ServerSocket on port " + port + "..."); /* - * Don't wait forever (original bug is that the export - * hangs). + * Start a thread that creates a registry on the same port, + * and analyze the result. */ - obj.wait(TIMEOUT); + System.err.println("create a registry on the same port..."); + System.err.println("(should cause an ExportException)"); - if (obj.exportSucceeded) { - throw new RuntimeException( - "TEST FAILED: export on already-bound port succeeded"); - } else if (obj.exportException != null) { - obj.exportException.printStackTrace(); - if (obj.exportException instanceof ExportException) { - System.err.println("TEST PASSED"); - } else { - throw new RuntimeException( - "TEST FAILED: unexpected exception occurred", - obj.exportException); + Thread exportRegistryThread = new Thread(() -> { + /* + * Attempt to create (i.e. export) a registry on the port that + * has already been bound, and record the result. + */ + try { + LocateRegistry.createRegistry(port); + } catch (Throwable t) { + registryExportFailure = t; } - } else { - throw new RuntimeException("TEST FAILED: export timed out"); + }, "ExportRegistry-Thread"); + + exportRegistryThread.start(); + + /* + * Wait for the LocateRegistry.createRegistry() call to complete or + * if it blocks forever (due to the original bug), then let jtreg fail + * the test with a timeout + */ + exportRegistryThread.join(); + if (registryExportFailure == null) { + throw new RuntimeException( + "TEST FAILED: export on already-bound port succeeded"); } + if (!(registryExportFailure instanceof ExportException)) { + throw new RuntimeException( + "TEST FAILED: unexpected exception occurred", registryExportFailure); + } + System.err.println("TEST PASSED, received expected exception: " + registryExportFailure); } } } diff --git a/test/jdk/java/security/KeyFactory/KeyFactoryGetKeySpecForInvalidSpec.java b/test/jdk/java/security/KeyFactory/KeyFactoryGetKeySpecForInvalidSpec.java index a8346089db7..5f53b344820 100644 --- a/test/jdk/java/security/KeyFactory/KeyFactoryGetKeySpecForInvalidSpec.java +++ b/test/jdk/java/security/KeyFactory/KeyFactoryGetKeySpecForInvalidSpec.java @@ -1,6 +1,6 @@ /* * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. - * 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 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/text/Format/DateFormat/Bug4407042.java b/test/jdk/java/text/Format/DateFormat/Bug4407042.java index 1960cb2b151..85825ff8b21 100644 --- a/test/jdk/java/text/Format/DateFormat/Bug4407042.java +++ b/test/jdk/java/text/Format/DateFormat/Bug4407042.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, 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,29 +27,31 @@ * @summary Make sure that cloned SimpleDateFormat objects work * independently in multiple threads. * @library /java/text/testlib - * @run main Bug4407042 10 + * @run junit Bug4407042 */ +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; + import java.io.*; import java.text.*; import java.util.*; -// Usage: java Bug4407042 [duration] public class Bug4407042 { static final String TIME_STRING = "2000/11/18 00:01:00"; static final long UTC_LONG = 974534460000L; static SimpleDateFormat masterFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); static boolean runrun = true; - static int duration = 100; + static int duration = 10; + @Test void test() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesAsciiDigits(locale) - || !TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesAsciiDigits(locale), + locale + " does not use ASCII digits"); + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); masterFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); DateParseThread d1 = new DateParseThread(); @@ -124,11 +126,4 @@ public class Bug4407042 { } } } - - public static void main (String[] args) { - if (args.length == 1) { - duration = Math.max(10, Integer.parseInt(args[0])); - } - new Bug4407042().test(); - } } diff --git a/test/jdk/java/text/Format/DateFormat/Bug4845901.java b/test/jdk/java/text/Format/DateFormat/Bug4845901.java index 363a3518bf0..754197dbe0d 100644 --- a/test/jdk/java/text/Format/DateFormat/Bug4845901.java +++ b/test/jdk/java/text/Format/DateFormat/Bug4845901.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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,19 +28,22 @@ * the same time zone abbreviation for standard and daylight saving * time. * @library /java/text/testlib - * @run main Bug4845901 + * @run junit/othervm Bug4845901 */ +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; + import java.util.*; import java.text.SimpleDateFormat; public class Bug4845901 { - public static void main (String args[]) { + + @Test + void test() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); TimeZone savedTZ = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Australia/Sydney")); diff --git a/test/jdk/java/text/Format/DateFormat/Bug6530336.java b/test/jdk/java/text/Format/DateFormat/Bug6530336.java index 552343cb1ba..880e8b3ae2b 100644 --- a/test/jdk/java/text/Format/DateFormat/Bug6530336.java +++ b/test/jdk/java/text/Format/DateFormat/Bug6530336.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -25,93 +25,73 @@ * @test * @bug 6530336 6537997 8008577 8174269 8333582 * @library /java/text/testlib - * @run main Bug6530336 + * @run junit/othervm Bug6530336 */ +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.FieldSource; + import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class Bug6530336 { - public static void main(String[] args) throws Exception { - Locale defaultLocale = Locale.getDefault(); - TimeZone defaultTimeZone = TimeZone.getDefault(); + private static final Locale[] locales = Locale.getAvailableLocales(); + private static final TimeZone[] timezones = { + TimeZone.getTimeZone("America/New_York"), + TimeZone.getTimeZone("America/Denver"), + }; + private static final TimeZone timezone_LA = TimeZone.getTimeZone("America/Los_Angeles"); + private static final String[] expected = { + "Sun Jul 15 12:00:00 PDT 2007", + "Sun Jul 15 14:00:00 PDT 2007", + }; + private static final Date[] dates = new Date[2]; - boolean err = false; - - try { - Locale locales[] = Locale.getAvailableLocales(); - TimeZone timezone_LA = TimeZone.getTimeZone("America/Los_Angeles"); - TimeZone.setDefault(timezone_LA); - - TimeZone timezones[] = { - TimeZone.getTimeZone("America/New_York"), - TimeZone.getTimeZone("America/Denver"), - }; - - String[] expected = { - "Sun Jul 15 12:00:00 PDT 2007", - "Sun Jul 15 14:00:00 PDT 2007", - }; - - Date[] dates = new Date[2]; - - for (int i = 0; i < locales.length; i++) { - Locale locale = locales[i]; - if (!TestUtils.usesGregorianCalendar(locale)) { - continue; - } - - Locale.setDefault(locale); - - for (int j = 0; j < timezones.length; j++) { - Calendar cal = Calendar.getInstance(timezones[j]); - cal.set(2007, 6, 15, 15, 0, 0); - dates[j] = cal.getTime(); - } - - SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); - - for (int j = 0; j < timezones.length; j++) { - sdf.setTimeZone(timezones[j]); - String date = sdf.format(dates[j]); - // CLDR localizes GMT format into for some locales. Ignore those cases - if (date.matches(".*GMT[\\s+-]\\D.*") || - date.contains("UTC") || - date.contains("TMG") || // Interlingue - date.contains("\u07dc\u07ed\u07d5\u07d6") || // N’Ko - date.contains("\ua2e7\ua0c5\ua395\ua3e6\ua12e\ua209") || // Sichuan Yi, Nuosu - date.contains("\u06af\u0631\u06cc\u0646\u06cc\u0686")) { // Central Kurdish - continue; - } - sdf.setTimeZone(timezone_LA); - String date_LA = sdf.parse(date).toString(); - - if (!expected[j].equals(date_LA)) { - System.err.println("Got wrong Pacific time (" + - date_LA + ") for (" + date + ") in " + locale + - " in " + timezones[j] + - ".\nExpected=" + expected[j]); - err = true; - } - } - } - } - catch (Exception e) { - e.printStackTrace(); - err = true; - } - finally { - Locale.setDefault(defaultLocale); - TimeZone.setDefault(defaultTimeZone); - - if (err) { - throw new RuntimeException("Failed."); - } - } + @BeforeAll + static void setup() { + TimeZone.setDefault(timezone_LA); } + @ParameterizedTest + @FieldSource("locales") + void test(Locale locale) { + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); + Locale.setDefault(locale); + + for (int j = 0; j < timezones.length; j++) { + Calendar cal = Calendar.getInstance(timezones[j]); + cal.set(2007, 6, 15, 15, 0, 0); + dates[j] = cal.getTime(); + } + + SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); + + for (int j = 0; j < timezones.length; j++) { + sdf.setTimeZone(timezones[j]); + String date = sdf.format(dates[j]); + // CLDR localizes GMT format into for some locales. Ignore those cases + if (date.matches(".*GMT[\\s+-]\\D.*") || + date.contains("UTC") || + date.contains("TMG") || // Interlingue + date.contains("ߜ߭ߕߖ") || // N’Ko + date.contains("ꋧꃅꎕꏦꄮꈉ") || // Sichuan Yi, Nuosu + date.contains("گرینیچ")) { // Central Kurdish + continue; + } + sdf.setTimeZone(timezone_LA); + String date_LA = assertDoesNotThrow(() -> sdf.parse(date).toString()); + assertEquals(expected[j], date_LA, + "Got wrong Pacific time (%s) for (%s) in %s in %s.".formatted(date_LA, date, locale, timezones[j])); + } + } } diff --git a/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java b/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java index dbd12e66f60..2e3fed17ce5 100644 --- a/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java +++ b/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java @@ -25,6 +25,7 @@ import java.text.*; import java.util.*; import java.io.*; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; @@ -170,10 +171,8 @@ public class DateFormatRegression { @Test public void Test4059917() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesAsciiDigits(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesAsciiDigits(locale), + locale + " does not use ASCII digits"); SimpleDateFormat fmt; String myDate; diff --git a/test/jdk/java/text/Format/MessageFormat/MessageRegression.java b/test/jdk/java/text/Format/MessageFormat/MessageRegression.java index e10e4899202..31aa5189ba2 100644 --- a/test/jdk/java/text/Format/MessageFormat/MessageRegression.java +++ b/test/jdk/java/text/Format/MessageFormat/MessageRegression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -53,6 +53,7 @@ import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.Serializable; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; @@ -126,10 +127,8 @@ public class MessageRegression { @Test public void Test4031438() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesAsciiDigits(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesAsciiDigits(locale), + locale + " does not use ASCII digits"); String pattern1 = "Impossible {1} has occurred -- status code is {0} and message is {2}."; String pattern2 = "Double '' Quotes {0} test and quoted '{1}' test plus 'other {2} stuff'."; diff --git a/test/jdk/java/text/Format/NumberFormat/NumberRegression.java b/test/jdk/java/text/Format/NumberFormat/NumberRegression.java index a0a096e6782..90f60151197 100644 --- a/test/jdk/java/text/Format/NumberFormat/NumberRegression.java +++ b/test/jdk/java/text/Format/NumberFormat/NumberRegression.java @@ -58,6 +58,7 @@ import java.math.BigDecimal; import java.io.*; import java.math.BigInteger; +import org.junit.jupiter.api.Assumptions; import sun.util.resources.LocaleData; import org.junit.jupiter.api.Test; @@ -109,10 +110,8 @@ public class NumberRegression { @Test public void Test4088161 (){ Locale locale = Locale.getDefault(); - if (!TestUtils.usesAsciiDigits(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesAsciiDigits(locale), + locale + " does not use ASCII digits"); DecimalFormat df = new DecimalFormat(); double d = 100; 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 d92d46d62bd..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, 2024, 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/Calendar/CalendarDisplayNamesTest.java b/test/jdk/java/util/Calendar/CalendarDisplayNamesTest.java index 7c40714fc02..171bea55fcf 100644 --- a/test/jdk/java/util/Calendar/CalendarDisplayNamesTest.java +++ b/test/jdk/java/util/Calendar/CalendarDisplayNamesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, 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 @@ -21,21 +21,21 @@ * questions. */ -import org.testng.Assert; -import org.testng.annotations.Test; import java.util.Calendar; import java.util.Locale; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * @test * @bug 8262108 8174269 * @summary Verify the results returned by Calendar.getDisplayNames() API * @comment Locale providers: CLDR,SPI - * @run testng/othervm -Djava.locale.providers=CLDR,SPI CalendarDisplayNamesTest + * @run junit/othervm -Djava.locale.providers=CLDR,SPI CalendarDisplayNamesTest * @comment Locale providers: default - * @run testng CalendarDisplayNamesTest + * @run junit CalendarDisplayNamesTest */ public class CalendarDisplayNamesTest { @@ -55,7 +55,7 @@ public class CalendarDisplayNamesTest { continue; } for (final Integer fieldValue : names.values()) { - Assert.assertTrue(fieldValue == Calendar.AM || fieldValue == Calendar.PM, + Assertions.assertTrue(fieldValue == Calendar.AM || fieldValue == Calendar.PM, "Invalid field value " + fieldValue + " for calendar field AM_PM, in locale " + locale + " with style " + style); } diff --git a/test/jdk/java/util/Calendar/CalendarLimitTest.java b/test/jdk/java/util/Calendar/CalendarLimitTest.java index e8a92f180ec..552aa5f9866 100644 --- a/test/jdk/java/util/Calendar/CalendarLimitTest.java +++ b/test/jdk/java/util/Calendar/CalendarLimitTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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,6 +32,7 @@ import java.util.*; import java.text.*; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; @@ -130,10 +131,8 @@ public class CalendarLimitTest public void TestCalendarLimit() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); ORIGIN = julianDayToMillis(JAN_1_1_JULIAN_DAY); Calendar cal = Calendar.getInstance(); diff --git a/test/jdk/java/util/Calendar/CalendarRegression.java b/test/jdk/java/util/Calendar/CalendarRegression.java index 7b0f2025005..6e5148c0c20 100644 --- a/test/jdk/java/util/Calendar/CalendarRegression.java +++ b/test/jdk/java/util/Calendar/CalendarRegression.java @@ -55,6 +55,7 @@ import java.util.function.Predicate; import static java.util.Calendar.*; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; @@ -575,10 +576,8 @@ public class CalendarRegression { @Test public void Test4100311() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); cal.set(YEAR, 1997); @@ -593,10 +592,8 @@ public class CalendarRegression { @Test public void Test4103271() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); SimpleDateFormat sdf = new SimpleDateFormat(); int numYears = 40, startYear = 1997, numDays = 15; @@ -833,10 +830,8 @@ public class CalendarRegression { @Test public void Test4114578() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); int ONE_HOUR = 60 * 60 * 1000; TimeZone saveZone = TimeZone.getDefault(); @@ -921,10 +916,8 @@ public class CalendarRegression { @Test public void Test4125881() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); DateFormat fmt = new SimpleDateFormat("MMMM d, yyyy G"); @@ -947,10 +940,8 @@ public class CalendarRegression { @Test public void Test4125892() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); DateFormat fmt = new SimpleDateFormat("MMMM d, yyyy G"); @@ -1373,10 +1364,8 @@ public class CalendarRegression { @Test public void Test4173516() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); int[][] fieldsList = { {1997, FEBRUARY, 1, 10, 45, 15, 900}, @@ -1852,11 +1841,10 @@ public class CalendarRegression { @Test public void Test4685354() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesAsciiDigits(locale) - || !TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesAsciiDigits(locale), + locale + " does not use ASCII digits"); + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); Calendar calendar = Calendar.getInstance(Locale.US); DateFormat df = new SimpleDateFormat("yyyy/MM/dd", Locale.US); @@ -1961,10 +1949,8 @@ public class CalendarRegression { @Test public void Test4655637() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); Calendar cal = Calendar.getInstance(); cal.setTime(new Date(1029814211523L)); diff --git a/test/jdk/java/util/Calendar/CalendarTest.java b/test/jdk/java/util/Calendar/CalendarTest.java index 5092c6adec0..0b50b07179d 100644 --- a/test/jdk/java/util/Calendar/CalendarTest.java +++ b/test/jdk/java/util/Calendar/CalendarTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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,6 +48,7 @@ import java.util.TimeZone; import static java.util.Calendar.*; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; @@ -223,10 +224,8 @@ public class CalendarTest { @Test public void TestGenericAPI() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); String str; Date when = new Date(90, APRIL, 15); @@ -625,10 +624,8 @@ public class CalendarTest { @Test public void TestGMTvsLocal4064654() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); // Sample output 1: // % /usr/local/java/jdk1.1.3/solaris/bin/java test 1997 1 1 12 0 0 diff --git a/test/jdk/java/util/Calendar/JapaneseLenientEraTest.java b/test/jdk/java/util/Calendar/JapaneseLenientEraTest.java index 6a909a23a18..ca726afc29b 100644 --- a/test/jdk/java/util/Calendar/JapaneseLenientEraTest.java +++ b/test/jdk/java/util/Calendar/JapaneseLenientEraTest.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 @@ -25,7 +25,7 @@ * @test * @bug 8206120 * @summary Test whether lenient era is accepted in JapaneseImperialCalendar - * @run testng/othervm JapaneseLenientEraTest + * @run junit/othervm JapaneseLenientEraTest */ import java.text.DateFormat; @@ -34,15 +34,15 @@ import java.util.Calendar; import java.util.Date; import java.util.Locale; -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; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class JapaneseLenientEraTest { - @DataProvider(name="lenientEra") - Object[][] names() { + Object[][] lenientEra() { return new Object[][] { // lenient era/year, strict era/year { "Meiji 123", "Heisei 2" }, @@ -51,7 +51,8 @@ public class JapaneseLenientEraTest { }; } - @Test(dataProvider="lenientEra") + @ParameterizedTest + @MethodSource("lenientEra") public void testLenientEra(String lenient, String strict) throws Exception { Calendar c = new Calendar.Builder() .setCalendarType("japanese") @@ -61,6 +62,6 @@ public class JapaneseLenientEraTest { Date lenDate = df.parse(lenient + "-01-01"); df.setLenient(false); Date strDate = df.parse(strict + "-01-01"); - assertEquals(lenDate, strDate); + assertEquals(strDate, lenDate); } } diff --git a/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java b/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java index 8eac4a97ef7..878955fdcc4 100644 --- a/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java +++ b/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java @@ -27,7 +27,7 @@ * @summary Test for jdk.calendar.japanese.supplemental.era support * @library /test/lib * @build SupplementalJapaneseEraTest - * @run testng/othervm SupplementalJapaneseEraTestRun + * @run junit/othervm SupplementalJapaneseEraTestRun */ import java.util.Calendar; @@ -45,11 +45,12 @@ import static java.util.Calendar.YEAR; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.Utils; -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 SupplementalJapaneseEraTestRun { - @DataProvider(name = "validprop") Object[][] validPropertyData() { return new Object[][] { //Tests with valid property values @@ -58,7 +59,6 @@ public class SupplementalJapaneseEraTestRun { }; } - @DataProvider(name = "invalidprop") Object[][] invalidPropertyData() { return new Object[][] { //Tests with invalid property values @@ -76,7 +76,8 @@ public class SupplementalJapaneseEraTestRun { }; } - @Test(dataProvider = "validprop") + @ParameterizedTest + @MethodSource("validPropertyData") public void ValidPropertyValuesTest(String prop) throws Throwable { //get the start time of the fictional next era @@ -84,7 +85,8 @@ public class SupplementalJapaneseEraTestRun { testRun(prop + startTime, List.of("-t")); } - @Test(dataProvider = "invalidprop") + @ParameterizedTest + @MethodSource("invalidPropertyData") public void InvalidPropertyValuesTest(String prop) throws Throwable { //get the start time of the fictional next era diff --git a/test/jdk/java/util/Calendar/bug4409072.java b/test/jdk/java/util/Calendar/bug4409072.java index 617550fe1aa..132934daa98 100644 --- a/test/jdk/java/util/Calendar/bug4409072.java +++ b/test/jdk/java/util/Calendar/bug4409072.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2023, 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 @@ -32,6 +32,7 @@ import java.util.*; import static java.util.Calendar.*; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; @@ -44,10 +45,8 @@ public class bug4409072 { @Test public void Test4409072() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); Locale savedLocale = Locale.getDefault(); TimeZone savedTZ = TimeZone.getDefault(); diff --git a/test/jdk/java/util/Collections/T5078378.java b/test/jdk/java/util/Collections/T5078378.java index d3c9c198e70..1dc78dfe219 100644 --- a/test/jdk/java/util/Collections/T5078378.java +++ b/test/jdk/java/util/Collections/T5078378.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 diff --git a/test/jdk/java/util/EnumSet/EnumSetSpliteratorTest.java b/test/jdk/java/util/EnumSet/EnumSetSpliteratorTest.java new file mode 100644 index 00000000000..eee38846683 --- /dev/null +++ b/test/jdk/java/util/EnumSet/EnumSetSpliteratorTest.java @@ -0,0 +1,97 @@ +/* + * 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 + * @run junit EnumSetSpliteratorTest + * @bug 8179918 + * @summary EnumSet spliterator should report SORTED, ORDERED, NONNULL + */ + +import java.util.EnumSet; +import java.util.List; +import java.util.Spliterator; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class EnumSetSpliteratorTest { + + private enum Empty {} + + private enum Small { + a, b, c, d + } + + private enum Large { + e00, e01, e02, e03, e04, e05, e06, e07, + e08, e09, e0A, e0B, e0C, e0D, e0E, e0F, + e10, e11, e12, e13, e14, e15, e16, e17, + e18, e19, e1A, e1B, e1C, e1D, e1E, e1F, + e20, e21, e22, e23, e24, e25, e26, e27, + e28, e29, e2A, e2B, e2C, e2D, e2E, e2F, + e30, e31, e32, e33, e34, e35, e36, e37, + e38, e39, e3A, e3B, e3C, e3D, e3E, e3F, + e40, e41, e42, e43, e44, e45, e46, e47, + e48, e49, e4A, e4B, e4C, e4D, e4E, e4F + } + + @Test + public void testSpliteratorCharacteristics() { + assertSpliteratorCharacteristics(EnumSet.allOf(Empty.class)); + assertSpliteratorCharacteristics(EnumSet.allOf(Small.class)); + assertSpliteratorCharacteristics(EnumSet.allOf(Large.class)); + assertSpliteratorCharacteristics(EnumSet.noneOf(Empty.class)); + assertSpliteratorCharacteristics(EnumSet.noneOf(Small.class)); + assertSpliteratorCharacteristics(EnumSet.noneOf(Large.class)); + assertSpliteratorCharacteristics(EnumSet.of(Small.a, Small.d)); + assertSpliteratorCharacteristics(EnumSet.range(Small.a, Small.c)); + assertSpliteratorCharacteristics(EnumSet.range(Large.e02, Large.e4D)); + assertSpliteratorCharacteristics(EnumSet.complementOf(EnumSet.of(Small.c))); + assertSpliteratorCharacteristics(EnumSet.complementOf(EnumSet.of(Large.e00, Large.e4F))); + } + + @Test + public void testEncounterOrder() { + assertEquals(List.of(Small.values()), EnumSet.allOf(Small.class).stream().toList()); + assertEquals(List.of(Large.values()), EnumSet.allOf(Large.class).stream().toList()); + } + + private static final int EXPECTED_CHARACTERISTICS = ( + Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED | + Spliterator.NONNULL | Spliterator.SIZED | Spliterator.SUBSIZED); + + private static void assertSpliteratorCharacteristics(EnumSet enumSet) { + Spliterator spliterator = enumSet.spliterator(); + assertTrue(spliterator.hasCharacteristics(Spliterator.DISTINCT), "Missing DISTINCT"); + assertTrue(spliterator.hasCharacteristics(Spliterator.SORTED), "Missing SORTED"); + assertTrue(spliterator.hasCharacteristics(Spliterator.ORDERED), "Missing ORDERED"); + assertTrue(spliterator.hasCharacteristics(Spliterator.NONNULL), "Missing NONNULL"); + assertTrue(spliterator.hasCharacteristics(Spliterator.SIZED), "Missing SIZED"); + assertTrue(spliterator.hasCharacteristics(Spliterator.SUBSIZED), "Missing SUBSIZED"); + assertEquals(EXPECTED_CHARACTERISTICS, spliterator.characteristics(), "Unexpected characteristics"); + } +} \ No newline at end of file diff --git a/test/jdk/java/util/List/ListFactories.java b/test/jdk/java/util/List/ListFactories.java index f02fcb95921..07cd2078e2e 100644 --- a/test/jdk/java/util/List/ListFactories.java +++ b/test/jdk/java/util/List/ListFactories.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, 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 diff --git a/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java b/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java index 12f5a96d3fb..07cc7a412b6 100644 --- a/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java +++ b/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java @@ -25,9 +25,9 @@ * @test * @bug 8025703 8040211 8191404 8203872 8222980 8225435 8241082 8242010 8247432 * 8258795 8267038 8287180 8302512 8304761 8306031 8308021 8313702 8318322 - * 8327631 8332424 8334418 8344589 8348328 + * 8327631 8332424 8334418 8344589 8348328 8362428 * @summary Checks the IANA language subtag registry data update - * (LSR Revision: 2025-05-15) with Locale and Locale.LanguageRange + * (LSR Revision: 2025-08-25) with Locale and Locale.LanguageRange * class methods. * @run main LanguageSubtagRegistryTest */ diff --git a/test/jdk/java/util/Locale/LocaleCategory.java b/test/jdk/java/util/Locale/LocaleCategory.java index ed63203916a..ec4277d43c0 100644 --- a/test/jdk/java/util/Locale/LocaleCategory.java +++ b/test/jdk/java/util/Locale/LocaleCategory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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,14 +29,17 @@ * @library /java/text/testlib * @build TestUtils LocaleCategory * @comment test user.xxx.display user.xxx.format properties - * @run main/othervm -Duser.language.display=ja + * @run junit/othervm -Duser.language.display=ja * -Duser.language.format=zh LocaleCategory * @comment test user.xxx properties overriding user.xxx.display/format - * @run main/othervm -Duser.language=en + * @run junit/othervm -Duser.language=en * -Duser.language.display=ja * -Duser.language.format=zh LocaleCategory */ +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; + import java.util.Locale; public class LocaleCategory { @@ -44,12 +47,11 @@ public class LocaleCategory { private static Locale disp = null; private static Locale fmt = null; - public static void main(String[] args) { + @Test + void test() { Locale reservedLocale = Locale.getDefault(); - if (TestUtils.hasSpecialVariant(reservedLocale)) { - System.out.println("Skipping this test because locale is " + reservedLocale); - return; - } + Assumptions.assumeFalse(TestUtils.hasSpecialVariant(reservedLocale), + reservedLocale + " has special variant"); try { Locale.Builder builder = new Locale.Builder(); diff --git a/test/jdk/java/util/Locale/LocaleProvidersFormat.java b/test/jdk/java/util/Locale/LocaleProvidersFormat.java index 157e92ce8a3..77b65dd6a74 100644 --- a/test/jdk/java/util/Locale/LocaleProvidersFormat.java +++ b/test/jdk/java/util/Locale/LocaleProvidersFormat.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 diff --git a/test/jdk/java/util/Locale/LocaleTest.java b/test/jdk/java/util/Locale/LocaleTest.java index 0cf272f20a0..76fbb83c11a 100644 --- a/test/jdk/java/util/Locale/LocaleTest.java +++ b/test/jdk/java/util/Locale/LocaleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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,7 +26,7 @@ * 4118587 4118595 4122371 4126371 4126880 4135316 4135752 4139504 4139940 4143951 * 4147315 4147317 4147552 4335196 4778440 4940539 5010672 6475525 6544471 6627549 * 6786276 7066203 7085757 8008577 8030696 8170840 8174269 8255086 8263202 8287868 - * 8337603 + * 8337603 8355522 * @summary test Locales * @modules jdk.localedata * @run junit LocaleTest @@ -703,40 +703,21 @@ test commented out pending API-change approval @Test public void TestChangedISO639Codes() { Locale hebrewOld = Locale.of("iw", "IL"); - Locale hebrewNew = Locale.of("he", "IL"); Locale yiddishOld = Locale.of("ji", "IL"); - Locale yiddishNew = Locale.of("yi", "IL"); Locale indonesianOld = Locale.of("in"); - Locale indonesianNew = Locale.of("id"); - if ("true".equalsIgnoreCase(System.getProperty("java.locale.useOldISOCodes"))) { - if (!hebrewNew.getLanguage().equals("iw")) { - fail("Got back wrong language code for new Hebrew: expected \"iw\", got \"" - + hebrewNew.getLanguage() + "\""); - } - if (!yiddishNew.getLanguage().equals("ji")) { - fail("Got back wrong language code for new Yiddish: expected \"ji\", got \"" - + yiddishNew.getLanguage() + "\""); - } - if (!indonesianNew.getLanguage().equals("in")) { - fail("Got back wrong language code for new Indonesian: expected \"in\", got \"" - + indonesianNew.getLanguage() + "\""); - } - } else { - if (!hebrewOld.getLanguage().equals("he")) { - fail("Got back wrong language code for old Hebrew: expected \"he\", got \"" - + hebrewNew.getLanguage() + "\""); - } - if (!yiddishOld.getLanguage().equals("yi")) { - fail("Got back wrong language code for old Yiddish: expected \"yi\", got \"" - + yiddishNew.getLanguage() + "\""); - } - if (!indonesianOld.getLanguage().equals("id")) { - fail("Got back wrong language code for old Indonesian: expected \"id\", got \"" - + indonesianNew.getLanguage() + "\""); - } + if (!hebrewOld.getLanguage().equals("he")) { + fail("Got back wrong language code for old Hebrew: expected \"he\", got \"" + + hebrewOld.getLanguage() + "\""); + } + if (!yiddishOld.getLanguage().equals("yi")) { + fail("Got back wrong language code for old Yiddish: expected \"yi\", got \"" + + yiddishOld.getLanguage() + "\""); + } + if (!indonesianOld.getLanguage().equals("id")) { + fail("Got back wrong language code for old Indonesian: expected \"id\", got \"" + + indonesianOld.getLanguage() + "\""); } - } /** 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/Locale/UseOldISOCodesTest.java b/test/jdk/java/util/Locale/UseOldISOCodesTest.java index 1909497535c..3e836782fc3 100644 --- a/test/jdk/java/util/Locale/UseOldISOCodesTest.java +++ b/test/jdk/java/util/Locale/UseOldISOCodesTest.java @@ -23,7 +23,7 @@ /* * @test - * @bug 8295232 8353118 + * @bug 8295232 8353118 8355522 * @summary Tests for the "java.locale.useOldISOCodes" system property * @library /test/lib * @run junit UseOldISOCodesTest @@ -34,7 +34,7 @@ import jdk.test.lib.process.ProcessTools; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; public class UseOldISOCodesTest { @@ -44,7 +44,7 @@ public class UseOldISOCodesTest { .outputTo(System.out) .errorTo(System.err); oa.shouldHaveExitValue(0); - oa.stderrShouldMatch("WARNING: The use of the system property \"java.locale.useOldISOCodes\" is deprecated. It will be removed in a future release of the JDK."); + oa.stderrShouldMatch("WARNING: The system property \"java.locale.useOldISOCodes\" is no longer supported. Any specified value will be ignored."); } static class Runner { @@ -52,12 +52,9 @@ public class UseOldISOCodesTest { private static final String newCode = "he"; public static void main(String[] args) { - // Ensure java.locale.useOldISOCodes is only interpreted at runtime startup - // Should have no effect - System.setProperty("java.locale.useOldISOCodes", "false"); - Locale locale = Locale.of(newCode); - assertEquals(obsoleteCode, locale.getLanguage(), - "newCode 'he' was not mapped to 'iw' with useOldISOCodes=true"); + // Ensure java.locale.useOldISOCodes should have no effect + assertNotEquals(obsoleteCode, Locale.of(newCode).getLanguage(), + "newCode 'he' was mapped to 'iw' with useOldISOCodes=true"); } } } diff --git a/test/jdk/java/util/Properties/CompatibilityTest.java b/test/jdk/java/util/Properties/CompatibilityTest.java index 29c7be6fbcd..839680806c1 100644 --- a/test/jdk/java/util/Properties/CompatibilityTest.java +++ b/test/jdk/java/util/Properties/CompatibilityTest.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 @@ -24,19 +24,19 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Properties; -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.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /* * @test * @bug 8252354 - * @run testng CompatibilityTest + * @run junit CompatibilityTest * @summary Verify compatibility. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class CompatibilityTest { - @DataProvider(name = "entries") public Object[][] getEntries() throws IOException { return new Object[][]{ {8, 238923}, @@ -53,9 +53,10 @@ public class CompatibilityTest { * @param value the value * @throws IOException */ - @Test(dataProvider = "entries") + @ParameterizedTest + @MethodSource("getEntries") void testThrows(Object key, Object value) throws IOException { - Assert.assertThrows(ClassCastException.class, () -> storeToXML(key, value)); + Assertions.assertThrows(ClassCastException.class, () -> storeToXML(key, value)); } void storeToXML(Object key, Object value) throws IOException { diff --git a/test/jdk/java/util/Properties/EncodingTest.java b/test/jdk/java/util/Properties/EncodingTest.java index d97730a37c7..069d16155f0 100644 --- a/test/jdk/java/util/Properties/EncodingTest.java +++ b/test/jdk/java/util/Properties/EncodingTest.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 @@ -27,19 +27,20 @@ import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Properties; -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.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @test * @bug 8183743 * @summary Test to verify the new overload method with Charset functions the * same as the existing method that takes a charset name. - * @run testng EncodingTest + * @run junit EncodingTest */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class EncodingTest { - @DataProvider(name = "parameters") public Object[][] getParameters() throws IOException { return new Object[][]{ {StandardCharsets.UTF_8.name(), null}, @@ -51,7 +52,8 @@ public class EncodingTest { * encoding name or a charset can be read with Properties#loadFromXML that * returns the same Properties object. */ - @Test(dataProvider = "parameters") + @ParameterizedTest + @MethodSource("getParameters") void testLoadAndStore(String encoding, Charset charset) throws IOException { Properties props = new Properties(); props.put("k0", "\u6C34"); @@ -74,6 +76,6 @@ public class EncodingTest { } } - Assert.assertEquals(props, p); + Assertions.assertEquals(p, props); } } diff --git a/test/jdk/java/util/Properties/InitialCapacity.java b/test/jdk/java/util/Properties/InitialCapacity.java index 81e5421bbef..d684c37adf4 100644 --- a/test/jdk/java/util/Properties/InitialCapacity.java +++ b/test/jdk/java/util/Properties/InitialCapacity.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 @@ -22,18 +22,22 @@ */ import java.util.Properties; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /* * @test * @bug 8189319 * @summary Test that Properties(int initialCapacity) throws exceptions (or doesn't) as expected - * @run testng InitialCapacity + * @run junit InitialCapacity */ public class InitialCapacity { - @Test(expectedExceptions = IllegalArgumentException.class) - public void negativeInitCap() { Properties p = new Properties(-1); } + @Test + public void negativeInitCap() { Assertions.assertThrows(IllegalArgumentException.class, () -> { + Properties p = new Properties(-1); + }); +} @Test public void positiveInitCap() { Properties p = new Properties(10); } diff --git a/test/jdk/java/util/Properties/PropertiesEntrySetTest.java b/test/jdk/java/util/Properties/PropertiesEntrySetTest.java index d7d58be44dd..f3262f734e3 100644 --- a/test/jdk/java/util/Properties/PropertiesEntrySetTest.java +++ b/test/jdk/java/util/Properties/PropertiesEntrySetTest.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 @@ -26,17 +26,17 @@ * @bug 8245694 * @summary tests the entrySet() method of Properties class * @author Yu Li - * @run testng PropertiesEntrySetTest + * @run junit PropertiesEntrySetTest */ -import org.testng.annotations.Test; import java.util.Properties; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertThrows; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; public class PropertiesEntrySetTest { @@ -99,13 +99,13 @@ public class PropertiesEntrySetTest { public void testToString() { Properties a = new Properties(); var aEntrySet = a.entrySet(); - assertEquals(aEntrySet.toString(), "[]"); + assertEquals("[]", aEntrySet.toString()); a.setProperty("p1", "1"); - assertEquals(aEntrySet.toString(), "[p1=1]"); + assertEquals("[p1=1]", aEntrySet.toString()); a.setProperty("p2", "2"); - assertEquals(aEntrySet.size(), 2); + assertEquals(2, aEntrySet.size()); assertTrue(aEntrySet.toString().trim().startsWith("[")); assertTrue(aEntrySet.toString().contains("p1=1")); assertTrue(aEntrySet.toString().contains("p2=2")); @@ -115,18 +115,18 @@ public class PropertiesEntrySetTest { b.setProperty("p2", "2"); b.setProperty("p1", "1"); var bEntrySet = b.entrySet(); - assertEquals(bEntrySet.size(), 2); + assertEquals(2, bEntrySet.size()); assertTrue(bEntrySet.toString().trim().startsWith("[")); assertTrue(bEntrySet.toString().contains("p1=1")); assertTrue(bEntrySet.toString().contains("p2=2")); assertTrue(bEntrySet.toString().trim().endsWith("]")); b.setProperty("p0", "0"); - assertEquals(bEntrySet.size(), 3); + assertEquals(3, bEntrySet.size()); assertTrue(bEntrySet.toString().contains("p0=0")); b.remove("p1"); - assertEquals(bEntrySet.size(), 2); + assertEquals(2, bEntrySet.size()); assertFalse(bEntrySet.toString().contains("p1=1")); assertTrue(bEntrySet.toString().trim().startsWith("[")); assertTrue(bEntrySet.toString().contains("p0=0")); @@ -134,7 +134,7 @@ public class PropertiesEntrySetTest { assertTrue(bEntrySet.toString().trim().endsWith("]")); b.remove("p0", "0"); - assertEquals(bEntrySet.size(), 1); + assertEquals(1, bEntrySet.size()); assertFalse(bEntrySet.toString().contains("p0=0")); assertTrue(bEntrySet.toString().trim().startsWith("[")); assertTrue(bEntrySet.toString().contains("p2=2")); @@ -151,13 +151,13 @@ public class PropertiesEntrySetTest { a.setProperty("p1", "1"); a.setProperty("p2", "2"); var aEntrySet = a.entrySet(); - assertEquals(aEntrySet.size(), 2); + assertEquals(2, aEntrySet.size()); var i = aEntrySet.iterator(); var e1 = i.next(); i.remove(); assertFalse(aEntrySet.contains(e1)); - assertEquals(aEntrySet.size(), 1); + assertEquals(1, aEntrySet.size()); var e2 = i.next(); aEntrySet.remove(e2); @@ -172,14 +172,14 @@ public class PropertiesEntrySetTest { var bEntrySet = b.entrySet(); assertFalse(bEntrySet.containsAll(aEntrySet)); - assertEquals(bEntrySet.size(), 2); + assertEquals(2, bEntrySet.size()); assertTrue(bEntrySet.removeAll(aEntrySet)); - assertEquals(bEntrySet.size(), 1); + assertEquals(1, bEntrySet.size()); assertTrue(bEntrySet.retainAll(aEntrySet)); assertTrue(bEntrySet.isEmpty()); - assertEquals(aEntrySet.size(), 2); + assertEquals(2, aEntrySet.size()); aEntrySet.clear(); assertTrue(aEntrySet.isEmpty()); diff --git a/test/jdk/java/util/Properties/PropertiesStoreTest.java b/test/jdk/java/util/Properties/PropertiesStoreTest.java index b5a5b5a45aa..88c24698a14 100644 --- a/test/jdk/java/util/Properties/PropertiesStoreTest.java +++ b/test/jdk/java/util/Properties/PropertiesStoreTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, 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 @@ -21,9 +21,6 @@ * questions. */ -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.io.BufferedReader; import java.io.IOException; @@ -45,13 +42,18 @@ import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; +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 * @summary tests the order in which the Properties.store() method writes out the properties * @bug 8231640 8282023 - * @run testng/othervm PropertiesStoreTest + * @run junit/othervm PropertiesStoreTest */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class PropertiesStoreTest { private static final String DATE_FORMAT_PATTERN = "EEE MMM dd HH:mm:ss zzz uuuu"; @@ -60,7 +62,6 @@ public class PropertiesStoreTest { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT_PATTERN, Locale.US); private static final Locale PREV_LOCALE = Locale.getDefault(); - @DataProvider(name = "propsProvider") private Object[][] createProps() { final Properties simple = new Properties(); simple.setProperty("1", "one"); @@ -101,7 +102,6 @@ public class PropertiesStoreTest { /** * Returns a {@link Locale} to use for testing */ - @DataProvider(name = "localeProvider") private Object[][] provideLocales() { // pick a non-english locale for testing Set locales = Arrays.stream(Locale.getAvailableLocales()) @@ -122,7 +122,8 @@ public class PropertiesStoreTest { * Tests that the {@link Properties#store(Writer, String)} API writes out the properties * in the expected order */ - @Test(dataProvider = "propsProvider") + @ParameterizedTest + @MethodSource("createProps") public void testStoreWriterKeyOrder(final Properties props, final String[] expectedOrder) throws Exception { // Properties.store(...) to a temp file final Path tmpFile = Files.createTempFile("8231640", "props"); @@ -136,7 +137,8 @@ public class PropertiesStoreTest { * Tests that the {@link Properties#store(OutputStream, String)} API writes out the properties * in the expected order */ - @Test(dataProvider = "propsProvider") + @ParameterizedTest + @MethodSource("createProps") public void testStoreOutputStreamKeyOrder(final Properties props, final String[] expectedOrder) throws Exception { // Properties.store(...) to a temp file final Path tmpFile = Files.createTempFile("8231640", "props"); @@ -161,7 +163,7 @@ public class PropertiesStoreTest { try (final InputStream is = Files.newInputStream(storedProps)) { loaded.load(is); } - Assert.assertEquals(loaded, props, "Unexpected properties loaded from stored state"); + Assertions.assertEquals(props, loaded, "Unexpected properties loaded from stored state"); // now read lines from the stored file and keep track of the order in which the keys were // found in that file. Compare that order with the expected store order of the keys. @@ -169,10 +171,10 @@ public class PropertiesStoreTest { try (final BufferedReader reader = Files.newBufferedReader(storedProps)) { actualOrder = readInOrder(reader); } - Assert.assertEquals(actualOrder.size(), expectedOrder.length, + Assertions.assertEquals(expectedOrder.length, actualOrder.size(), "Unexpected number of keys read from stored properties"); if (!Arrays.equals(actualOrder.toArray(new String[0]), expectedOrder)) { - Assert.fail("Unexpected order of stored property keys. Expected order: " + Arrays.toString(expectedOrder) + Assertions.fail("Unexpected order of stored property keys. Expected order: " + Arrays.toString(expectedOrder) + ", found order: " + actualOrder); } } @@ -180,7 +182,8 @@ public class PropertiesStoreTest { /** * Tests that {@link Properties#store(Writer, String)} writes out a proper date comment */ - @Test(dataProvider = "localeProvider") + @ParameterizedTest + @MethodSource("provideLocales") public void testStoreWriterDateComment(final Locale testLocale) throws Exception { // switch the default locale to the one being tested Locale.setDefault(testLocale); @@ -202,7 +205,8 @@ public class PropertiesStoreTest { /** * Tests that {@link Properties#store(OutputStream, String)} writes out a proper date comment */ - @Test(dataProvider = "localeProvider") + @ParameterizedTest + @MethodSource("provideLocales") public void testStoreOutputStreamDateComment(final Locale testLocale) throws Exception { // switch the default locale to the one being tested Locale.setDefault(testLocale); @@ -232,19 +236,19 @@ public class PropertiesStoreTest { while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { if (comment != null) { - Assert.fail("More than one comment line found in the stored properties file " + file); + Assertions.fail("More than one comment line found in the stored properties file " + file); } comment = line.substring(1); } } } if (comment == null) { - Assert.fail("No comment line found in the stored properties file " + file); + Assertions.fail("No comment line found in the stored properties file " + file); } try { FORMATTER.parse(comment); } catch (DateTimeParseException pe) { - Assert.fail("Unexpected date comment: " + comment, pe); + Assertions.fail("Unexpected date comment: " + comment, pe); } } diff --git a/test/jdk/java/util/ResourceBundle/modules/basic/BasicTest.java b/test/jdk/java/util/ResourceBundle/modules/basic/BasicTest.java index 69f0db83258..c17c4622ecb 100644 --- a/test/jdk/java/util/ResourceBundle/modules/basic/BasicTest.java +++ b/test/jdk/java/util/ResourceBundle/modules/basic/BasicTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, 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 @@ -43,7 +43,7 @@ * jdk.test.lib.compiler.CompilerUtils * jdk.test.lib.process.ProcessTools * ModuleTestUtil - * @run testng BasicTest + * @run junit BasicTest */ import java.nio.file.Path; @@ -54,13 +54,15 @@ import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.Utils; import jdk.test.lib.compiler.CompilerUtils; import jdk.test.lib.process.ProcessTools; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static jdk.test.lib.Asserts.assertEquals; -import static org.testng.Assert.assertTrue; +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; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class BasicTest { private static final String SRC_DIR_APPBASIC = "srcAppbasic"; private static final String SRC_DIR_APPBASIC2 = "srcAppbasic2"; @@ -92,7 +94,6 @@ public class BasicTest { private static final String MAIN = "test/jdk.test.Main"; - @DataProvider(name = "basicTestData") Object[][] basicTestData() { return new Object[][] { // Named module "test" contains resource bundles for root and en, @@ -122,7 +123,8 @@ public class BasicTest { }; } - @Test(dataProvider = "basicTestData") + @ParameterizedTest + @MethodSource("basicTestData") public void runBasicTest(String src, String mod, List moduleList, List localeList, String resFormat) throws Throwable { Path srcPath = Paths.get(Utils.TEST_SRC, src); diff --git a/test/jdk/java/util/ResourceBundle/modules/cache/CacheTest.java b/test/jdk/java/util/ResourceBundle/modules/cache/CacheTest.java index 5655eb5de2d..df72af38855 100644 --- a/test/jdk/java/util/ResourceBundle/modules/cache/CacheTest.java +++ b/test/jdk/java/util/ResourceBundle/modules/cache/CacheTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, 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,7 +27,7 @@ * @library /test/lib * @modules jdk.compiler * @build CacheTest jdk.test.lib.compiler.CompilerUtils - * @run testng CacheTest + * @run junit CacheTest */ import java.nio.file.Files; @@ -37,11 +37,12 @@ import java.nio.file.Paths; import static jdk.test.lib.process.ProcessTools.*; import jdk.test.lib.compiler.CompilerUtils; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +import static 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 CacheTest { private static final String TEST_SRC = System.getProperty("test.src"); @@ -55,7 +56,7 @@ public class CacheTest { private static final String MAIN = "test/jdk.test.Main"; private static final String MAIN_CLASS = "jdk.test.Main"; - @BeforeTest + @BeforeAll public void compileTestModules() throws Exception { for (String mn : new String[] {MAIN_BUNDLES_MODULE, TEST_MODULE}) { diff --git a/test/jdk/java/util/ResourceBundle/modules/casesensitive/CaseInsensitiveNameClash.java b/test/jdk/java/util/ResourceBundle/modules/casesensitive/CaseInsensitiveNameClash.java index 914ebf6bbf0..45f52b512c8 100644 --- a/test/jdk/java/util/ResourceBundle/modules/casesensitive/CaseInsensitiveNameClash.java +++ b/test/jdk/java/util/ResourceBundle/modules/casesensitive/CaseInsensitiveNameClash.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, 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 @@ -28,7 +28,7 @@ * @modules jdk.compiler * @build jdk.test.lib.compiler.CompilerUtils * jdk.test.lib.process.ProcessTools CaseInsensitiveNameClash - * @run testng CaseInsensitiveNameClash + * @run junit CaseInsensitiveNameClash */ import java.nio.file.Files; @@ -37,10 +37,12 @@ import java.nio.file.Paths; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.compiler.CompilerUtils; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class CaseInsensitiveNameClash { private static final String TEST_SRC = System.getProperty("test.src"); @@ -54,7 +56,7 @@ public class CaseInsensitiveNameClash { /** * Compiles the module used by the test */ - @BeforeTest + @BeforeAll public void compileAll() throws Exception { Path msrc = SRC_DIR.resolve(MODULE); assertTrue(CompilerUtils.compile(msrc, MODS_DIR, diff --git a/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java b/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java index e0fdb9a93ab..ee9da88d705 100644 --- a/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java +++ b/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.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 @@ -34,7 +34,7 @@ * jdk.test.lib.compiler.CompilerUtils * jdk.test.lib.process.ProcessTools * ModuleTestUtil - * @run testng VisibilityTest + * @run junit VisibilityTest */ import java.nio.file.Path; @@ -46,13 +46,13 @@ import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.Utils; import jdk.test.lib.process.ProcessTools; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +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; -import static org.testng.Assert.assertEquals; - -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class VisibilityTest { private static final Path SRC_DIR = Paths.get(Utils.TEST_SRC, "src"); private static final Path MODS_DIR = Paths.get(Utils.TEST_CLASSES, "mods"); @@ -63,7 +63,7 @@ public class VisibilityTest { private static final List MODULE_LIST = List.of("embargo", "exported.named.bundles", "named.bundles", "test"); - @BeforeTest + @BeforeAll public void prepareTestEnv() throws Throwable { MODULE_LIST.forEach(mn -> ModuleTestUtil.prepareModule(SRC_DIR, MODS_DIR, mn, ".properties")); @@ -93,7 +93,6 @@ public class VisibilityTest { * "exported.named.bundle" are exported to unnamed modules. */ - @DataProvider(name = "RunWithTestResData") Object[][] RunWithTestResData() { return new Object[][] { // Tests using jdk.test.TestWithNoModuleArg and jdk.embargo.TestWithNoModuleArg. @@ -188,7 +187,6 @@ public class VisibilityTest { }; } - @DataProvider(name = "RunWithExportedResData") Object[][] RunWithExportedResData() { return new Object[][] { // Tests using jdk.test.TestWithNoModuleArg and jdk.embargo.TestWithNoModuleArg @@ -285,7 +283,6 @@ public class VisibilityTest { }; } - @DataProvider(name = "RunWithPkgResData") Object[][] RunWithPkgResData() { return new Object[][] { // jdk.pkg.resources.* are in an unnamed module. @@ -300,10 +297,11 @@ public class VisibilityTest { /** * Test cases with jdk.test.resources.* */ - @Test(dataProvider = "RunWithTestResData") + @ParameterizedTest + @MethodSource("RunWithTestResData") public void RunWithTestRes(List argsList) throws Throwable { int exitCode = runCmd(argsList); - assertEquals(exitCode, 0, "Execution of the tests with " + assertEquals(0, exitCode, "Execution of the tests with " + "jdk.test.resources.* failed. " + "Unexpected exit code: " + exitCode); } @@ -311,10 +309,11 @@ public class VisibilityTest { /** * Test cases with jdk.test.resources.exported.* */ - @Test(dataProvider = "RunWithExportedResData") + @ParameterizedTest + @MethodSource("RunWithExportedResData") public void RunWithExportedRes(List argsList) throws Throwable { int exitCode = runCmd(argsList); - assertEquals(exitCode, 0, "Execution of the tests with " + assertEquals(0, exitCode, "Execution of the tests with " + "jdk.test.resources.exported.* failed. " + "Unexpected exit code: " + exitCode); } @@ -322,10 +321,11 @@ public class VisibilityTest { /** * Test cases with jdk.pkg.resources.* */ - @Test(dataProvider = "RunWithPkgResData") + @ParameterizedTest + @MethodSource("RunWithPkgResData") public void RunWithPkgRes(List argsList) throws Throwable { int exitCode = runCmd(argsList); - assertEquals(exitCode, 0, "Execution of the tests with " + assertEquals(0, exitCode, "Execution of the tests with " + "jdk.pkg.resources.* failed. " + "Unexpected exit code: " + exitCode); } diff --git a/test/jdk/java/util/TimeZone/NegativeDSTTest.java b/test/jdk/java/util/TimeZone/NegativeDSTTest.java index eb46b8d4b29..ab9438f2388 100644 --- a/test/jdk/java/util/TimeZone/NegativeDSTTest.java +++ b/test/jdk/java/util/TimeZone/NegativeDSTTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 @@ -21,7 +21,7 @@ * questions. */ -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Instant; import java.time.LocalDate; @@ -31,18 +31,19 @@ import java.time.ZoneId; import java.util.Date; import java.util.TimeZone; -import org.testng.annotations.Test; -import org.testng.annotations.DataProvider; -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 * @bug 8212970 8324065 * @summary Test whether the savings are positive in time zones that have * negative savings in the source TZ files. - * @run testng NegativeDSTTest + * @run junit NegativeDSTTest */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class NegativeDSTTest { private static final TimeZone DUBLIN = TimeZone.getTimeZone("Europe/Dublin"); @@ -51,7 +52,6 @@ public class NegativeDSTTest { private static final TimeZone CASABLANCA = TimeZone.getTimeZone("Africa/Casablanca"); private static final int ONE_HOUR = 3600_000; - @DataProvider private Object[][] negativeDST () { return new Object[][] { // TimeZone, localDate, offset, isDaylightSavings @@ -88,10 +88,11 @@ public class NegativeDSTTest { }; } - @Test(dataProvider="negativeDST") + @ParameterizedTest + @MethodSource("negativeDST") public void test_NegativeDST(TimeZone tz, LocalDate ld, int offset, boolean isDST) { Date d = Date.from(Instant.from(ZonedDateTime.of(ld, LocalTime.MIN, tz.toZoneId()))); - assertEquals(tz.getOffset(d.getTime()), offset); - assertEquals(tz.inDaylightTime(d), isDST); + assertEquals(offset, tz.getOffset(d.getTime())); + assertEquals(isDST, tz.inDaylightTime(d)); } } 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/java/util/TimeZone/TimeZoneRegression.java b/test/jdk/java/util/TimeZone/TimeZoneRegression.java index 241afd3f7cf..c1b1b98369e 100644 --- a/test/jdk/java/util/TimeZone/TimeZoneRegression.java +++ b/test/jdk/java/util/TimeZone/TimeZoneRegression.java @@ -34,6 +34,7 @@ import java.util.*; import java.io.*; import java.text.*; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; @@ -164,10 +165,8 @@ public class TimeZoneRegression { @Test public void Test4109314() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); // test both SimpleTimeZone and ZoneInfo objects. // @since 1.4 @@ -292,10 +291,8 @@ public class TimeZoneRegression { @Test public void Test4126678() { Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } + Assumptions.assumeTrue(TestUtils.usesGregorianCalendar(locale), + locale + " does not use a Gregorian calendar"); // Note: this test depends on the PST time zone. TimeZone initialZone = TimeZone.getDefault(); diff --git a/test/jdk/java/util/TimeZone/ZoneIdRoundTripTest.java b/test/jdk/java/util/TimeZone/ZoneIdRoundTripTest.java index 0f1eeb88328..16e24f7cb27 100644 --- a/test/jdk/java/util/TimeZone/ZoneIdRoundTripTest.java +++ b/test/jdk/java/util/TimeZone/ZoneIdRoundTripTest.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 @@ -25,20 +25,20 @@ import java.time.ZoneId; import java.time.ZoneOffset; import java.util.TimeZone; -import org.testng.annotations.Test; -import org.testng.annotations.DataProvider; -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 * @bug 8285844 * @summary Checks round-trips between TimeZone and ZoneId are consistent - * @run testng ZoneIdRoundTripTest + * @run junit ZoneIdRoundTripTest */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ZoneIdRoundTripTest { - @DataProvider private Object[][] testZoneIds() { return new Object[][] { {ZoneId.of("Z"), 0}, @@ -60,11 +60,12 @@ public class ZoneIdRoundTripTest { }; } - @Test(dataProvider="testZoneIds") + @ParameterizedTest + @MethodSource("testZoneIds") public void test_ZoneIdRoundTrip(ZoneId zid, int offset) { var tz = TimeZone.getTimeZone(zid); - assertEquals(tz.getRawOffset(), offset); - assertEquals(tz.toZoneId().normalized(), zid.normalized()); + assertEquals(offset, tz.getRawOffset()); + assertEquals(zid.normalized(), tz.toZoneId().normalized()); } } diff --git a/test/jdk/java/util/concurrent/CompletableFuture/CompletableFutureOrTimeoutExceptionallyTest.java b/test/jdk/java/util/concurrent/CompletableFuture/CompletableFutureOrTimeoutExceptionallyTest.java index 210a791aad0..4b48b264714 100644 --- a/test/jdk/java/util/concurrent/CompletableFuture/CompletableFutureOrTimeoutExceptionallyTest.java +++ b/test/jdk/java/util/concurrent/CompletableFuture/CompletableFutureOrTimeoutExceptionallyTest.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 diff --git a/test/jdk/java/util/concurrent/Executors/AutoShutdown.java b/test/jdk/java/util/concurrent/Executors/AutoShutdown.java index ec58a472f7b..d3f277baddf 100644 --- a/test/jdk/java/util/concurrent/Executors/AutoShutdown.java +++ b/test/jdk/java/util/concurrent/Executors/AutoShutdown.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 diff --git a/test/jdk/java/util/concurrent/forkjoin/Starvation.java b/test/jdk/java/util/concurrent/forkjoin/Starvation.java index 8397e852ffa..f3336a3c7e9 100644 --- a/test/jdk/java/util/concurrent/forkjoin/Starvation.java +++ b/test/jdk/java/util/concurrent/forkjoin/Starvation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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,6 +28,7 @@ */ import java.util.concurrent.Callable; import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.ForkJoinTask; import java.util.concurrent.atomic.AtomicInteger; public class Starvation { @@ -42,7 +43,7 @@ public class Starvation { while (count.get() == c) Thread.onSpinWait(); return null; }}; - public static void main(String[] args) throws Exception { + static void testSubmitExternalCallable() throws Exception { try (var pool = new ForkJoinPool(2)) { for (int i = 0; i < 100_000; i++) { var future1 = pool.submit(new AwaitCount(i)); @@ -53,4 +54,21 @@ public class Starvation { } } } + + static void testSubmitAdaptedCallable() throws Exception { + try (var pool = new ForkJoinPool(2)) { + for (int i = 0; i < 100_000; i++) { + var future1 = pool.submit(new AwaitCount(i)); + var future2 = pool.submit(ForkJoinTask.adapt(noop)); + future2.get(); + count.set(i + 1); + future1.get(); + } + } + } + + public static void main(String[] args) throws Exception { + testSubmitExternalCallable(); + testSubmitAdaptedCallable(); + } } diff --git a/test/jdk/java/util/concurrent/locks/StampedLock/OOMEInStampedLock.java b/test/jdk/java/util/concurrent/locks/StampedLock/OOMEInStampedLock.java index 32b77205163..1bec4f21c09 100644 --- a/test/jdk/java/util/concurrent/locks/StampedLock/OOMEInStampedLock.java +++ b/test/jdk/java/util/concurrent/locks/StampedLock/OOMEInStampedLock.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 diff --git a/test/jdk/java/util/regex/TestCases.txt b/test/jdk/java/util/regex/TestCases.txt index 3353335f84d..68a7a6651ad 100644 --- a/test/jdk/java/util/regex/TestCases.txt +++ b/test/jdk/java/util/regex/TestCases.txt @@ -1,5 +1,5 @@ // -// Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved. +// Copyright (c) 1999, 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 diff --git a/test/jdk/java/util/stream/GathererTest.java b/test/jdk/java/util/stream/GathererTest.java index 419347d76c6..5792dbbf1d5 100644 --- a/test/jdk/java/util/stream/GathererTest.java +++ b/test/jdk/java/util/stream/GathererTest.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 diff --git a/test/jdk/java/util/zip/CloseInflaterDeflaterTest.java b/test/jdk/java/util/zip/CloseInflaterDeflaterTest.java index 5c6732503f5..af314581a9e 100644 --- a/test/jdk/java/util/zip/CloseInflaterDeflaterTest.java +++ b/test/jdk/java/util/zip/CloseInflaterDeflaterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, 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 diff --git a/test/jdk/java/util/zip/DeflaterClose.java b/test/jdk/java/util/zip/DeflaterClose.java index a4c4b233b4e..db81e787d92 100644 --- a/test/jdk/java/util/zip/DeflaterClose.java +++ b/test/jdk/java/util/zip/DeflaterClose.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 diff --git a/test/jdk/java/util/zip/InflaterClose.java b/test/jdk/java/util/zip/InflaterClose.java index 7c0e1606ade..515de5cb7ed 100644 --- a/test/jdk/java/util/zip/InflaterClose.java +++ b/test/jdk/java/util/zip/InflaterClose.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, 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 diff --git a/test/jdk/java/util/zip/TotalInOut.java b/test/jdk/java/util/zip/TotalInOut.java index 92ab981def8..1a4d9624186 100644 --- a/test/jdk/java/util/zip/TotalInOut.java +++ b/test/jdk/java/util/zip/TotalInOut.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 diff --git a/test/jdk/javax/management/mxbean/MXBeanInteropTest1.java b/test/jdk/javax/management/mxbean/MXBeanInteropTest1.java index 011bdb144fb..61127a4ee10 100644 --- a/test/jdk/javax/management/mxbean/MXBeanInteropTest1.java +++ b/test/jdk/javax/management/mxbean/MXBeanInteropTest1.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 diff --git a/test/jdk/javax/management/security/HashedPasswordFileTest.java b/test/jdk/javax/management/security/HashedPasswordFileTest.java index 6cef1df4a0a..92c3692870e 100644 --- a/test/jdk/javax/management/security/HashedPasswordFileTest.java +++ b/test/jdk/javax/management/security/HashedPasswordFileTest.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 diff --git a/test/jdk/javax/net/ssl/DTLS/TEST.properties b/test/jdk/javax/net/ssl/DTLS/TEST.properties index a50cba09c0f..ceb6c8c9c42 100644 --- a/test/jdk/javax/net/ssl/DTLS/TEST.properties +++ b/test/jdk/javax/net/ssl/DTLS/TEST.properties @@ -6,4 +6,3 @@ modules = \ java.security.jgss/sun.security.krb5.internal:+open \ java.security.jgss/sun.security.krb5.internal.ktab \ java.base/sun.security.util -maxOutputSize = 2500000 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 d36dfb2630e..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, 2018, 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 @@ -27,7 +27,7 @@ * @library /test/lib * @modules jdk.httpserver * @build jdk.test.lib.net.SimpleSSLContext - * @run main/othervm -Djavax.net.debug=ssl,handshake,record Equals + * @run main/othervm Equals */ import com.sun.net.httpserver.*; import java.net.*; @@ -38,9 +38,24 @@ import jdk.test.lib.net.SimpleSSLContext; public class Equals { - static SSLContext ctx; + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=ssl,handshake,record + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; + + private static final SSLContext ctx = SimpleSSLContext.findSSLContext(); public static void main(String[] args) throws Exception { + if (debug) { + System.setProperty("javax.net.debug", "ssl,handshake,record"); + } + HttpsServer s2 = null; ExecutorService executor = null; try { @@ -50,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 new file mode 100644 index 00000000000..de747922d7b --- /dev/null +++ b/test/jdk/javax/net/ssl/HttpsURLConnection/SubjectAltNameIP.java @@ -0,0 +1,384 @@ +/* + * 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 8369950 + * @summary Test that the HttpsURLConnection does not set IP address literals for + * SNI hostname during TLS handshake + * @library /test/lib + * @modules java.base/sun.net.util + * @comment Insert -Djavax.net.debug=all into the following lines to enable SSL debugging + * @run main/othervm SubjectAltNameIP 127.0.0.1 + * @run main/othervm SubjectAltNameIP ::1 + */ + +import javax.net.ssl.HandshakeCompletedListener; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.net.InetAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.URI; +import java.util.concurrent.CountDownLatch; +import java.util.function.Consumer; + +import jdk.test.lib.Asserts; +import jdk.test.lib.net.IPSupport; +import jdk.test.lib.net.SimpleSSLContext; +import jtreg.SkippedException; +import sun.net.util.IPAddressUtil; + +public class SubjectAltNameIP { + + // Is the server ready to serve? + private final CountDownLatch serverReady = new CountDownLatch(1); + + // Use any free port by default. + volatile int serverPort = 0; + + // Stores an exception thrown by server in a separate thread. + volatile Exception serverException = null; + + // SSLSocket object created by HttpsClient internally. + SSLSocket clientSSLSocket = null; + + // The hostname the server socket is bound to. + String hostName; + + static final byte[] requestEnd = new byte[] {'\r', '\n', '\r', '\n' }; + + // Read until the end of the request. + void readOneRequest(InputStream is) throws IOException { + int requestEndCount = 0, r; + while ((r = is.read()) != -1) { + if (r == requestEnd[requestEndCount]) { + requestEndCount++; + if (requestEndCount == 4) { + break; + } + } else { + requestEndCount = 0; + } + } + } + + /* + * Define the server side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doServerSide() throws Exception { + SSLServerSocketFactory sslssf = + SimpleSSLContext.findSSLContext().getServerSocketFactory(); + SSLServerSocket sslServerSocket = + (SSLServerSocket) sslssf.createServerSocket( + serverPort, 0, + InetAddress.getByName(hostName)); + sslServerSocket.setEnabledProtocols(new String[]{"TLSv1.3"}); + serverPort = sslServerSocket.getLocalPort(); + + /* + * Signal the client, the server is ready to accept connection. + */ + serverReady.countDown(); + + SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); + OutputStream sslOS = sslSocket.getOutputStream(); + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sslOS)); + bw.write("HTTP/1.1 200 OK\r\n\r\n"); + bw.flush(); + readOneRequest(sslSocket.getInputStream()); + sslSocket.close(); + } + + /* + * Define the client side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doClientSide() throws Exception { + + /* + * Wait for server to get started. + */ + serverReady.await(); + if (serverException != null) { + throw new RuntimeException("Server failed to start.", serverException); + } + + SSLSocketFactory sf = SimpleSSLContext.findSSLContext().getSocketFactory(); + URI uri = new URI("https://" + hostName + ":" + serverPort + "/index.html"); + HttpsURLConnection conn = (HttpsURLConnection)uri.toURL().openConnection(); + + /* + * Simulate an external JSSE implementation and store the client SSLSocket + * used internally. + */ + conn.setSSLSocketFactory(wrapSocketFactory(sf, + sslSocket -> { + Asserts.assertEquals(null, clientSSLSocket, "clientSSLSocket is"); + clientSSLSocket = sslSocket; + })); + conn.getInputStream(); + + var sniSN = clientSSLSocket.getSSLParameters().getServerNames(); + if (sniSN != null && !sniSN.isEmpty()) { + throw new RuntimeException("SNI server name '" + + sniSN.getFirst() + "' must not be set."); + } + + if (conn.getResponseCode() == -1) { + throw new RuntimeException("getResponseCode() returns -1"); + } + } + + public static void main(String[] args) throws Exception { + boolean isIpv6Addr = IPAddressUtil.isIPv6LiteralAddress(args[0]); + + if (isIpv6Addr && !IPSupport.hasIPv6()) { + throw new SkippedException("Skipping test - IPv6 is not supported"); + } + /* + * Start the tests. + */ + if (isIpv6Addr) { // use the URL notion wrapper + new SubjectAltNameIP("[" + args[0] + "]"); + } else { + new SubjectAltNameIP(args[0]); + } + } + + Thread serverThread = null; + + /* + * Primary constructor, used to drive remainder of the test. + * + * Fork off the other side, then do your work. + */ + SubjectAltNameIP(String host) throws Exception { + hostName = host; + startServer(); + doClientSide(); + + /* + * Wait for other side to close down. + */ + serverThread.join(); + + if (serverException != null) + throw serverException; + } + + void startServer() { + serverThread = new Thread(() -> { + try { + doServerSide(); + } catch (Exception e) { + /* + * Our server thread just died. + * + * Store the exception and release the client. + */ + serverException = e; + serverReady.countDown(); + } + }); + serverThread.start(); + } + + /* + * Wraps SSLSocketImpl to simulate a different JSSE implementation + */ + private static SSLSocketFactory wrapSocketFactory(final SSLSocketFactory wrap, final Consumer store) { + return new SSLSocketFactory() { + @Override + public String[] getDefaultCipherSuites() { + return wrap.getDefaultCipherSuites(); + } + @Override + public String[] getSupportedCipherSuites() { + return wrap.getSupportedCipherSuites(); + } + @Override + public Socket createSocket(Socket s, String host, int port, boolean autoClose) + throws IOException { + final SSLSocket so = + (SSLSocket) wrap.createSocket(s, host, port, autoClose); + + // store the underlying SSLSocket for later use + store.accept(so); + + return new SSLSocket() { + @Override + public void connect(SocketAddress endpoint, + int timeout) throws IOException { + so.connect(endpoint, timeout); + } + @Override + public String[] getSupportedCipherSuites() { + return so.getSupportedCipherSuites(); + } + @Override + public String[] getEnabledCipherSuites() { + return so.getEnabledCipherSuites(); + } + @Override + public void setEnabledCipherSuites(String[] suites) { + so.setEnabledCipherSuites(suites); + } + @Override + public String[] getSupportedProtocols() { + return so.getSupportedProtocols(); + } + @Override + public String[] getEnabledProtocols() { + return so.getEnabledProtocols(); + } + @Override + public void setEnabledProtocols(String[] protocols) { + so.setEnabledProtocols(protocols); + } + @Override + public SSLSession getSession() { + return so.getSession(); + } + @Override + public SSLSession getHandshakeSession() { + return so.getHandshakeSession(); + } + @Override + public void addHandshakeCompletedListener(HandshakeCompletedListener listener) { + so.addHandshakeCompletedListener(listener); + } + @Override + public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) { + so.removeHandshakeCompletedListener(listener); + } + @Override + public void startHandshake() throws IOException { + so.startHandshake(); + } + @Override + public void setUseClientMode(boolean mode) { + so.setUseClientMode(mode); + } + @Override + public boolean getUseClientMode() { + return so.getUseClientMode(); + } + @Override + public void setNeedClientAuth(boolean need) { + } + @Override + public boolean getNeedClientAuth() { + return false; + } + @Override + public void setWantClientAuth(boolean want) { + } + @Override + public boolean getWantClientAuth() { + return false; + } + @Override + public void setEnableSessionCreation(boolean flag) { + so.setEnableSessionCreation(flag); + } + @Override + public boolean getEnableSessionCreation() { + return so.getEnableSessionCreation(); + } + @Override + public void close() throws IOException { + so.close(); + } + @Override + public boolean isClosed() { + return so.isClosed(); + } + @Override + public void shutdownInput() throws IOException { + so.shutdownInput(); + } + @Override + public boolean isInputShutdown() { + return so.isInputShutdown(); + } + @Override + public void shutdownOutput() throws IOException { + so.shutdownOutput(); + } + @Override + public boolean isOutputShutdown() { + return so.isOutputShutdown(); + } + @Override + public InputStream getInputStream() throws IOException { + return so.getInputStream(); + } + @Override + public OutputStream getOutputStream() throws IOException { + return so.getOutputStream(); + } + @Override + public SSLParameters getSSLParameters() { + return so.getSSLParameters(); + } + @Override + public void setSSLParameters(SSLParameters params) { + so.setSSLParameters(params); + } + }; + } + @Override + public Socket createSocket(String h, int p) { + return null; + } + @Override + public Socket createSocket(String h, int p, InetAddress ipa, int lp) { + return null; + } + @Override + public Socket createSocket(InetAddress h, int p) { + return null; + } + @Override + public Socket createSocket(InetAddress a, int p, InetAddress l, int lp) { + return null; + } + }; + } +} diff --git a/test/jdk/javax/net/ssl/SSLEngine/NoAuthClientAuth.java b/test/jdk/javax/net/ssl/SSLEngine/NoAuthClientAuth.java index 208fb3935ae..95754a4763e 100644 --- a/test/jdk/javax/net/ssl/SSLEngine/NoAuthClientAuth.java +++ b/test/jdk/javax/net/ssl/SSLEngine/NoAuthClientAuth.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -99,7 +99,7 @@ public class NoAuthClientAuth { * including specific handshake messages, and might be best examined * after gaining some familiarity with this application. */ - private static boolean debug = true; + private static boolean debug = false; private SSLContext sslc; diff --git a/test/jdk/javax/net/ssl/SSLSession/ResumeTLS13withSNI.java b/test/jdk/javax/net/ssl/SSLSession/ResumeTLS13withSNI.java index 3d05607bd39..d288fe70200 100644 --- a/test/jdk/javax/net/ssl/SSLSession/ResumeTLS13withSNI.java +++ b/test/jdk/javax/net/ssl/SSLSession/ResumeTLS13withSNI.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 @@ -54,7 +54,7 @@ public class ResumeTLS13withSNI { * including specific handshake messages, and might be best examined * after gaining some familiarity with this application. */ - private static final boolean debug = true; + private static final boolean debug = false; private static final ByteBuffer clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); diff --git a/test/jdk/javax/net/ssl/SSLSession/ServerNameRejectedTLSSessionResumption.java b/test/jdk/javax/net/ssl/SSLSession/ServerNameRejectedTLSSessionResumption.java index f80f3402c7e..de51b9c565e 100644 --- a/test/jdk/javax/net/ssl/SSLSession/ServerNameRejectedTLSSessionResumption.java +++ b/test/jdk/javax/net/ssl/SSLSession/ServerNameRejectedTLSSessionResumption.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 @@ -43,11 +43,20 @@ import javax.net.ssl.StandardConstants; * between the server and the client happens correctly without any * errors * @library /javax/net/ssl/templates - * @run main/othervm -Djavax.net.debug=all - * ServerNameRejectedTLSSessionResumption + * @run main/othervm ServerNameRejectedTLSSessionResumption */ public class ServerNameRejectedTLSSessionResumption extends SSLContextTemplate { + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=all + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; private static final String CLIENT_REQUESTED_SNI = "client.local"; // dummy host, no connection is attempted in this test @@ -56,6 +65,10 @@ public class ServerNameRejectedTLSSessionResumption private static final int PEER_PORT = 12345; public static void main(final String[] args) throws Exception { + if (debug) { + System.setProperty("javax.net.debug", "all"); + } + new ServerNameRejectedTLSSessionResumption().runTest(); } diff --git a/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java b/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java index 16e009ed589..b9386af9e0c 100644 --- a/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java +++ b/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 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 diff --git a/test/jdk/javax/net/ssl/ServerName/SSLEngineExplorerMatchedSNI.java b/test/jdk/javax/net/ssl/ServerName/SSLEngineExplorerMatchedSNI.java index a42134abdb1..bb288684384 100644 --- a/test/jdk/javax/net/ssl/ServerName/SSLEngineExplorerMatchedSNI.java +++ b/test/jdk/javax/net/ssl/ServerName/SSLEngineExplorerMatchedSNI.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 @@ -71,7 +71,7 @@ public class SSLEngineExplorerMatchedSNI extends SSLEngineService { /* * Turn on SSL debugging? */ - static boolean debug = true; + static boolean debug = false; /* * Define the server side of the test. diff --git a/test/jdk/javax/net/ssl/Stapling/HttpsUrlConnClient.java b/test/jdk/javax/net/ssl/Stapling/HttpsUrlConnClient.java index b9829621d68..c34311f1689 100644 --- a/test/jdk/javax/net/ssl/Stapling/HttpsUrlConnClient.java +++ b/test/jdk/javax/net/ssl/Stapling/HttpsUrlConnClient.java @@ -33,7 +33,11 @@ * @run main/othervm HttpsUrlConnClient RSASSA-PSS RSASSA-PSS */ -import java.io.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; @@ -41,7 +45,9 @@ import java.net.Socket; import java.net.URL; import java.net.HttpURLConnection; import java.net.InetAddress; + import javax.net.ssl.*; + import java.security.KeyStore; import java.security.PublicKey; import java.security.Security; @@ -55,7 +61,16 @@ import java.security.cert.X509Certificate; import java.security.cert.PKIXRevocationChecker; import java.security.spec.PKCS8EncodedKeySpec; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import jdk.test.lib.security.SimpleOCSPServer; @@ -92,10 +107,6 @@ public class HttpsUrlConnClient { static String INT_ALIAS = "intermediate"; static String SSL_ALIAS = "ssl"; - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; volatile int serverPort = 0; volatile Exception serverException = null; @@ -164,7 +175,7 @@ public class HttpsUrlConnClient { ClientParameters cliParams = new ClientParameters(); cliParams.protocols = allowedProts; ServerParameters servParams = new ServerParameters(); - serverReady = false; + CountDownLatch serverReady = new CountDownLatch(1); System.out.println("====================================="); System.out.println("Stapling enabled, PKIXParameters with"); @@ -192,7 +203,7 @@ public class HttpsUrlConnClient { Security.setProperty("ocsp.enable", "false"); HttpsUrlConnClient sslTest = new HttpsUrlConnClient(cliParams, - servParams); + servParams, serverReady); TestResult tr = sslTest.getResult(); if (!checkClientValidationFailure(tr.clientExc, BasicReason.REVOKED)) { if (tr.clientExc != null) { @@ -219,10 +230,11 @@ public class HttpsUrlConnClient { /* * Define the server side of the test. * - * If the server prematurely exits, serverReady will be set to true + * If the server prematurely exits, serverReady will be counted down * to avoid infinite hangs. */ - void doServerSide(ServerParameters servParams) throws Exception { + void doServerSide(ServerParameters servParams, CountDownLatch serverReady) + throws Exception { // Selectively enable or disable the feature System.setProperty("jdk.tls.server.enableStatusRequestExtension", @@ -274,7 +286,7 @@ public class HttpsUrlConnClient { /* * Signal Client, we're ready for his connect. */ - serverReady = true; + serverReady.countDown(); try (SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); BufferedReader in = new BufferedReader( @@ -306,18 +318,13 @@ public class HttpsUrlConnClient { /* * Define the client side of the test. * - * If the server prematurely exits, serverReady will be set to true + * If the server prematurely exits, serverReady will be counted down * to avoid infinite hangs. */ - void doClientSide(ClientParameters cliParams) throws Exception { + void doClientSide(ClientParameters cliParams, CountDownLatch serverReady) + throws Exception { - // Wait 5 seconds for server ready - for (int i = 0; (i < 100 && !serverReady); i++) { - Thread.sleep(50); - } - if (!serverReady) { - throw new RuntimeException("Server not ready yet"); - } + serverReady.await(); // Selectively enable or disable the feature System.setProperty("jdk.tls.client.enableStatusRequestExtension", @@ -373,16 +380,16 @@ public class HttpsUrlConnClient { * * Fork off the other side, then do your work. */ - HttpsUrlConnClient(ClientParameters cliParams, - ServerParameters servParams) throws Exception { + HttpsUrlConnClient(ClientParameters cliParams, ServerParameters servParams, + CountDownLatch serverReady) throws Exception { Exception startException = null; try { if (separateServerThread) { - startServer(servParams, true); - startClient(cliParams, false); + startServer(servParams, true, serverReady); + startClient(cliParams, false, serverReady); } else { - startClient(cliParams, true); - startServer(servParams, false); + startClient(cliParams, true, serverReady); + startServer(servParams, false, serverReady); } } catch (Exception e) { startException = e; @@ -453,51 +460,53 @@ public class HttpsUrlConnClient { return tr; } - final void startServer(ServerParameters servParams, boolean newThread) - throws Exception { + final void startServer(ServerParameters servParams, boolean newThread, + CountDownLatch serverReady) throws IOException { if (newThread) { serverThread = new Thread() { @Override public void run() { try { - doServerSide(servParams); + doServerSide(servParams, serverReady); } catch (Exception e) { /* * Our server thread just died. * * Release the client, if not active already... */ - System.err.println("Server died..."); - serverReady = true; + System.err.println("Server died: " + e); serverException = e; + } finally { + serverReady.countDown(); } } }; serverThread.start(); } else { try { - doServerSide(servParams); + doServerSide(servParams, serverReady); } catch (Exception e) { + System.err.println("Server died: " + e); serverException = e; } finally { - serverReady = true; + serverReady.countDown(); } } } - final void startClient(ClientParameters cliParams, boolean newThread) - throws Exception { + final void startClient(ClientParameters cliParams, boolean newThread, + CountDownLatch serverReady) throws Exception { if (newThread) { clientThread = new Thread() { @Override public void run() { try { - doClientSide(cliParams); + doClientSide(cliParams, serverReady); } catch (Exception e) { /* * Our client thread just died. */ - System.err.println("Client died..."); + System.err.println("Client died: " + e); clientException = e; } } @@ -505,9 +514,10 @@ public class HttpsUrlConnClient { clientThread.start(); } else { try { - doClientSide(cliParams); + doClientSide(cliParams, serverReady); } catch (Exception e) { clientException = e; + System.err.println("Client died: " + e); } } } diff --git a/test/jdk/javax/net/ssl/Stapling/SSLEngineWithStapling.java b/test/jdk/javax/net/ssl/Stapling/SSLEngineWithStapling.java index 506e7b00e6d..34398a4b6f8 100644 --- a/test/jdk/javax/net/ssl/Stapling/SSLEngineWithStapling.java +++ b/test/jdk/javax/net/ssl/Stapling/SSLEngineWithStapling.java @@ -99,13 +99,13 @@ public class SSLEngineWithStapling { /* * Enables the JSSE system debugging system property: * - * -Djavax.net.debug=all + * -Djavax.net.debug=ssl,handshake * * This gives a lot of low-level information about operations underway, * including specific handshake messages, and might be best examined * after gaining some familiarity with this application. */ - private static final boolean debug = true; + private static final boolean debug = false; private SSLEngine clientEngine; // client Engine private ByteBuffer clientOut; // write side of clientEngine @@ -151,7 +151,7 @@ public class SSLEngineWithStapling { */ public static void main(String args[]) throws Exception { if (debug) { - System.setProperty("javax.net.debug", "ssl:handshake"); + System.setProperty("javax.net.debug", "ssl,handshake"); } // Create the PKI we will use for the test and start the OCSP servers diff --git a/test/jdk/javax/net/ssl/Stapling/StapleEnableProps.java b/test/jdk/javax/net/ssl/Stapling/StapleEnableProps.java index 90b01d19c03..6bdb610643d 100644 --- a/test/jdk/javax/net/ssl/Stapling/StapleEnableProps.java +++ b/test/jdk/javax/net/ssl/Stapling/StapleEnableProps.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2023, 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 diff --git a/test/jdk/javax/net/ssl/TEST.properties b/test/jdk/javax/net/ssl/TEST.properties new file mode 100644 index 00000000000..741c2565067 --- /dev/null +++ b/test/jdk/javax/net/ssl/TEST.properties @@ -0,0 +1 @@ +maxOutputSize=500000 diff --git a/test/jdk/javax/net/ssl/TLS/TestJSSE.java b/test/jdk/javax/net/ssl/TLS/TestJSSE.java index 29631064011..baabd7f6054 100644 --- a/test/jdk/javax/net/ssl/TLS/TestJSSE.java +++ b/test/jdk/javax/net/ssl/TLS/TestJSSE.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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,17 @@ import java.security.Security; public class TestJSSE { + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=ssl,record + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; + private static final String LOCAL_IP = InetAddress.getLoopbackAddress().getHostAddress(); public static void main(String... args) throws Exception { @@ -35,7 +46,9 @@ public class TestJSSE { Security.setProperty("jdk.tls.disabledAlgorithms", ""); // enable debug output - System.setProperty("javax.net.debug", "ssl,record"); + if (debug) { + System.setProperty("javax.net.debug", "ssl,record"); + } String srvProtocol = System.getProperty("SERVER_PROTOCOL"); String clnProtocol = System.getProperty("CLIENT_PROTOCOL"); diff --git a/test/jdk/javax/net/ssl/TLSCommon/TLSTest.java b/test/jdk/javax/net/ssl/TLSCommon/TLSTest.java index 6aec08deedd..fc6369a2bbc 100644 --- a/test/jdk/javax/net/ssl/TLSCommon/TLSTest.java +++ b/test/jdk/javax/net/ssl/TLSCommon/TLSTest.java @@ -49,98 +49,112 @@ import javax.net.ssl.TrustManagerFactory; * @bug 8205111 * @enablePreview * @summary Test TLS with different types of supported keys. - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pkcs1_sha1 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pkcs1_sha256 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pkcs1_sha384 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pkcs1_sha512 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 ec_rsa_pkcs1_sha256 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 ecdsa_sha1 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 ecdsa_secp384r1_sha384 + * @run main/othervm TLSTest TLSv1.3 rsa_pkcs1_sha1 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 rsa_pkcs1_sha256 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 rsa_pkcs1_sha384 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 rsa_pkcs1_sha512 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 ec_rsa_pkcs1_sha256 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 ecdsa_sha1 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 ecdsa_secp384r1_sha384 * TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 ecdsa_secp521r1_sha512 + * @run main/othervm TLSTest TLSv1.3 ecdsa_secp521r1_sha512 * TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_rsae_sha256 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_rsae_sha384 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_rsae_sha512 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_pss_sha256 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_pss_sha384 TLS_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_pss_sha512 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_rsae_sha256 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_rsae_sha384 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_rsae_sha512 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_pss_sha256 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_pss_sha384 TLS_AES_128_GCM_SHA256 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_pss_sha512 TLS_AES_128_GCM_SHA256 * - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pkcs1_sha1 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pkcs1_sha256 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pkcs1_sha384 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pkcs1_sha512 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 ec_rsa_pkcs1_sha256 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 ecdsa_sha1 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 ecdsa_secp384r1_sha384 + * @run main/othervm TLSTest TLSv1.3 rsa_pkcs1_sha1 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 rsa_pkcs1_sha256 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 rsa_pkcs1_sha384 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 rsa_pkcs1_sha512 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 ec_rsa_pkcs1_sha256 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 ecdsa_sha1 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 ecdsa_secp384r1_sha384 * TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 ecdsa_secp521r1_sha512 + * @run main/othervm TLSTest TLSv1.3 ecdsa_secp521r1_sha512 * TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_rsae_sha256 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_rsae_sha384 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_rsae_sha512 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_pss_sha256 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_pss_sha384 TLS_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.3 rsa_pss_pss_sha512 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_rsae_sha256 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_rsae_sha384 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_rsae_sha512 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_pss_sha256 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_pss_sha384 TLS_AES_256_GCM_SHA384 + * @run main/othervm TLSTest TLSv1.3 rsa_pss_pss_sha512 TLS_AES_256_GCM_SHA384 * - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 rsa_pkcs1_sha1 TLS_RSA_WITH_AES_128_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 rsa_pkcs1_sha256 + * @run main/othervm TLSTest TLSv1.2 rsa_pkcs1_sha1 TLS_RSA_WITH_AES_128_CBC_SHA + * @run main/othervm TLSTest TLSv1.2 rsa_pkcs1_sha256 * TLS_RSA_WITH_AES_128_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 rsa_pkcs1_sha384 + * @run main/othervm TLSTest TLSv1.2 rsa_pkcs1_sha384 * TLS_RSA_WITH_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 rsa_pkcs1_sha512 + * @run main/othervm TLSTest TLSv1.2 rsa_pkcs1_sha512 * TLS_RSA_WITH_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 ec_rsa_pkcs1_sha256 + * @run main/othervm TLSTest TLSv1.2 ec_rsa_pkcs1_sha256 * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 ecdsa_sha1 + * @run main/othervm TLSTest TLSv1.2 ecdsa_sha1 * TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 ecdsa_secp384r1_sha384 + * @run main/othervm TLSTest TLSv1.2 ecdsa_secp384r1_sha384 * TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 ecdsa_secp521r1_sha512 + * @run main/othervm TLSTest TLSv1.2 ecdsa_secp521r1_sha512 * TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 rsa_pss_rsae_sha256 + * @run main/othervm TLSTest TLSv1.2 rsa_pss_rsae_sha256 * TLS_RSA_WITH_AES_256_CBC_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 rsa_pss_rsae_sha384 + * @run main/othervm TLSTest TLSv1.2 rsa_pss_rsae_sha384 * TLS_RSA_WITH_AES_256_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 rsa_pss_rsae_sha512 + * @run main/othervm TLSTest TLSv1.2 rsa_pss_rsae_sha512 * TLS_RSA_WITH_AES_128_CBC_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 rsa_pss_pss_sha256 + * @run main/othervm TLSTest TLSv1.2 rsa_pss_pss_sha256 * TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 rsa_pss_pss_sha384 + * @run main/othervm TLSTest TLSv1.2 rsa_pss_pss_sha384 * TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.2 rsa_pss_pss_sha512 + * @run main/othervm TLSTest TLSv1.2 rsa_pss_pss_sha512 * TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 * - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.1 rsa_pkcs1_sha1 TLS_RSA_WITH_AES_128_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.1 rsa_pkcs1_sha256 + * @run main/othervm TLSTest TLSv1.1 rsa_pkcs1_sha1 TLS_RSA_WITH_AES_128_CBC_SHA + * @run main/othervm TLSTest TLSv1.1 rsa_pkcs1_sha256 * TLS_RSA_WITH_AES_256_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.1 rsa_pkcs1_sha384 + * @run main/othervm TLSTest TLSv1.1 rsa_pkcs1_sha384 * TLS_RSA_WITH_AES_128_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.1 rsa_pkcs1_sha512 + * @run main/othervm TLSTest TLSv1.1 rsa_pkcs1_sha512 * TLS_RSA_WITH_AES_256_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.1 rsa_pss_rsae_sha256 + * @run main/othervm TLSTest TLSv1.1 rsa_pss_rsae_sha256 * TLS_RSA_WITH_AES_128_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.1 rsa_pss_rsae_sha384 + * @run main/othervm TLSTest TLSv1.1 rsa_pss_rsae_sha384 * TLS_RSA_WITH_AES_256_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1.1 rsa_pss_rsae_sha512 + * @run main/othervm TLSTest TLSv1.1 rsa_pss_rsae_sha512 * TLS_RSA_WITH_AES_128_CBC_SHA * - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1 rsa_pkcs1_sha1 TLS_RSA_WITH_AES_128_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1 rsa_pkcs1_sha256 TLS_RSA_WITH_AES_256_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1 rsa_pkcs1_sha384 TLS_RSA_WITH_AES_128_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1 rsa_pkcs1_sha512 TLS_RSA_WITH_AES_256_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1 rsa_pss_rsae_sha256 + * @run main/othervm TLSTest TLSv1 rsa_pkcs1_sha1 TLS_RSA_WITH_AES_128_CBC_SHA + * @run main/othervm TLSTest TLSv1 rsa_pkcs1_sha256 TLS_RSA_WITH_AES_256_CBC_SHA + * @run main/othervm TLSTest TLSv1 rsa_pkcs1_sha384 TLS_RSA_WITH_AES_128_CBC_SHA + * @run main/othervm TLSTest TLSv1 rsa_pkcs1_sha512 TLS_RSA_WITH_AES_256_CBC_SHA + * @run main/othervm TLSTest TLSv1 rsa_pss_rsae_sha256 * TLS_RSA_WITH_AES_128_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1 rsa_pss_rsae_sha384 + * @run main/othervm TLSTest TLSv1 rsa_pss_rsae_sha384 * TLS_RSA_WITH_AES_256_CBC_SHA - * @run main/othervm -Djavax.net.debug=ssl,handshake TLSTest TLSv1 rsa_pss_rsae_sha512 + * @run main/othervm TLSTest TLSv1 rsa_pss_rsae_sha512 * TLS_RSA_WITH_AES_128_CBC_SHA */ public class TLSTest { + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=ssl,handshake + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; + private volatile static boolean clientRenegoReady = false; public static void main(String[] args) throws Exception { + if (debug) { + System.setProperty("javax.net.debug", "ssl,handshake"); + } final String tlsProtocol = args[0]; final KeyType keyType = KeyType.valueOf(args[1]); diff --git a/test/jdk/javax/net/ssl/TLSCommon/TLSWithEdDSA.java b/test/jdk/javax/net/ssl/TLSCommon/TLSWithEdDSA.java index 3fabc5bd73c..f21b7b32b6a 100644 --- a/test/jdk/javax/net/ssl/TLSCommon/TLSWithEdDSA.java +++ b/test/jdk/javax/net/ssl/TLSCommon/TLSWithEdDSA.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 @@ -24,8 +24,6 @@ /* * SunJSSE does not support dynamic system properties, no way to re-use * system properties in samevm/agentvm mode. - * For extra debugging output, add -Djavax.net.debug=ssl:handshake into the - * run directive below. */ /* @@ -74,6 +72,18 @@ import javax.net.ssl.X509KeyManager; import jdk.test.lib.security.SecurityUtils; public class TLSWithEdDSA extends SSLSocketTemplate { + + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=ssl,handshake + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; + private static final String PASSWD = "passphrase"; private static final String DEF_TRUST_ANCHORS = "CA_DSA_1024:CA_DSA_2048:" + "CA_ECDSA_SECP256R1:CA_ECDSA_SECP384R1:CA_ECDSA_SECP521R1:" + @@ -556,6 +566,10 @@ public class TLSWithEdDSA extends SSLSocketTemplate { } public static void main(String[] args) throws Exception { + if (debug) { + System.setProperty("javax.net.debug", "ssl,handshake"); + } + SecurityUtils.removeFromDisabledTlsAlgs("TLSv1.1", "TLSv1"); certFac = CertificateFactory.getInstance("X.509"); String testFormat; diff --git a/test/jdk/javax/net/ssl/TLSCommon/interop/JdkClient.java b/test/jdk/javax/net/ssl/TLSCommon/interop/JdkClient.java index 79476cbb81e..eb6ecbb12b8 100644 --- a/test/jdk/javax/net/ssl/TLSCommon/interop/JdkClient.java +++ b/test/jdk/javax/net/ssl/TLSCommon/interop/JdkClient.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 @@ -25,6 +25,7 @@ import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.net.ssl.SNIHostName; @@ -86,6 +87,16 @@ public class JdkClient extends AbstractClient { if (builder.getAppProtocols() != null) { sslParams.setApplicationProtocols(builder.getAppProtocols()); } + + NamedGroup[] namedGroups = builder.getNamedGroups(); + if (namedGroups != null + && namedGroups.length > 0) { + String[] namedGroupStrs = Arrays.stream(namedGroups) + .map(NamedGroup::name) + .toArray(String[]::new); + sslParams.setNamedGroups(namedGroupStrs); + } + socket.setSSLParameters(sslParams); } diff --git a/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java b/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java index 1521325b65a..20bfffbac7d 100644 --- a/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java +++ b/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.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 @@ -22,9 +22,9 @@ */ import java.io.IOException; -import java.net.InetAddress; import java.net.SocketException; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.net.ssl.SNIHostName; @@ -85,6 +85,16 @@ public class JdkServer extends AbstractServer { System.out.println("appProtocol: " + appProtocol); } } + + NamedGroup[] namedGroups = builder.getNamedGroups(); + if (namedGroups != null + && namedGroups.length > 0) { + String[] namedGroupStrs = Arrays.stream(namedGroups) + .map(NamedGroup::name) + .toArray(String[]::new); + sslParams.setNamedGroups(namedGroupStrs); + } + serverSocket.setSSLParameters(sslParams); } diff --git a/test/jdk/javax/net/ssl/TLSv12/ShortRSAKey512.java b/test/jdk/javax/net/ssl/TLSv12/ShortRSAKey512.java index 4d4331dc973..3f8e5e4e6a5 100644 --- a/test/jdk/javax/net/ssl/TLSv12/ShortRSAKey512.java +++ b/test/jdk/javax/net/ssl/TLSv12/ShortRSAKey512.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 @@ -65,7 +65,7 @@ public class ShortRSAKey512 extends SSLContextTemplate { /* * Turn on SSL debugging? */ - static boolean debug = true; + static boolean debug = false; /* * Define the server side of the test. diff --git a/test/jdk/javax/net/ssl/TLSv13/ClientHelloKeyShares.java b/test/jdk/javax/net/ssl/TLSv13/ClientHelloKeyShares.java index 56f37a9e4f1..efb9895b33c 100644 --- a/test/jdk/javax/net/ssl/TLSv13/ClientHelloKeyShares.java +++ b/test/jdk/javax/net/ssl/TLSv13/ClientHelloKeyShares.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 @@ -22,8 +22,7 @@ */ // SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. For further debugging output -// set the -Djavax.net.debug=ssl:handshake property on the @run lines. +// system properties in samevm/agentvm mode. /* * @test @@ -46,6 +45,17 @@ import java.util.*; public class ClientHelloKeyShares { + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=ssl,handshake + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; + // Some TLS constants we'll use for testing private static final int TLS_REC_HANDSHAKE = 22; private static final int HELLO_EXT_SUPP_GROUPS = 10; @@ -58,6 +68,10 @@ public class ClientHelloKeyShares { private static final int NG_X448 = 0x001E; public static void main(String args[]) throws Exception { + if (debug) { + System.setProperty("javax.net.debug", "ssl,handshake"); + } + // Arguments to this test are an abitrary number of integer // values which will be the expected NamedGroup IDs in the key_share // extension. Expected named group assertions may also be affected diff --git a/test/jdk/javax/net/ssl/TLSv13/HRRKeyShares.java b/test/jdk/javax/net/ssl/TLSv13/HRRKeyShares.java index 313b2c5084b..560faf87049 100644 --- a/test/jdk/javax/net/ssl/TLSv13/HRRKeyShares.java +++ b/test/jdk/javax/net/ssl/TLSv13/HRRKeyShares.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 @@ -22,8 +22,7 @@ */ // SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. For further debugging output -// set the -Djavax.net.debug=ssl:handshake property on the @run lines. +// system properties in samevm/agentvm mode. /* * @test @@ -48,6 +47,16 @@ import jdk.test.lib.Utils; public class HRRKeyShares { + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=ssl,handshake + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; // Some TLS constants we'll use for testing private static final int TLS_REC_HANDSHAKE = 22; @@ -209,6 +218,11 @@ public class HRRKeyShares { } public static void main(String args[]) throws Exception { + + if (debug) { + System.setProperty("javax.net.debug", "ssl,handshake"); + } + System.out.println("Test 1: Good HRR exchange using secp384r1"); hrrKeyShareTest(NG_SECP384R1, true); System.out.println(); diff --git a/test/jdk/javax/net/ssl/compatibility/ClientHelloProcessing.java b/test/jdk/javax/net/ssl/compatibility/ClientHelloProcessing.java index c147f732ec5..4c1b621b180 100644 --- a/test/jdk/javax/net/ssl/compatibility/ClientHelloProcessing.java +++ b/test/jdk/javax/net/ssl/compatibility/ClientHelloProcessing.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,6 +60,17 @@ import java.util.Objects; public class ClientHelloProcessing { + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=ssl:handshake + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; + private static final ByteBuffer SERVOUTBUF = ByteBuffer.wrap("Server Side".getBytes()); @@ -476,7 +487,11 @@ public class ClientHelloProcessing { public static void main(String[] args) throws Exception { boolean allGood = true; - System.setProperty("javax.net.debug", "ssl:handshake"); + + if (debug) { + System.setProperty("javax.net.debug", "ssl:handshake"); + } + trustMgrFac = makeTrustManagerFactory(trustFilename, passwd); keyMgrFac = makeKeyManagerFactory(keyFilename, passwd); diff --git a/test/jdk/javax/net/ssl/templates/SSLEngineTemplate.java b/test/jdk/javax/net/ssl/templates/SSLEngineTemplate.java index 2c1cfaa44ef..fed82d1164f 100644 --- a/test/jdk/javax/net/ssl/templates/SSLEngineTemplate.java +++ b/test/jdk/javax/net/ssl/templates/SSLEngineTemplate.java @@ -54,6 +54,18 @@ import java.nio.ByteBuffer; * produced. */ public class SSLEngineTemplate extends SSLContextTemplate { + + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=all + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; + protected final SSLEngine clientEngine; // client Engine protected final ByteBuffer clientOut; // write side of clientEngine protected final ByteBuffer clientIn; // read side of clientEngine @@ -139,6 +151,10 @@ public class SSLEngineTemplate extends SSLContextTemplate { } public static void main(String[] args) throws Exception { + if (debug) { + System.setProperty("javax.net.debug", "all"); + } + new SSLEngineTemplate().runTest(); } diff --git a/test/jdk/javax/net/ssl/templates/SSLSocketTemplate.java b/test/jdk/javax/net/ssl/templates/SSLSocketTemplate.java index 51706cec927..9d1b1fe94c4 100644 --- a/test/jdk/javax/net/ssl/templates/SSLSocketTemplate.java +++ b/test/jdk/javax/net/ssl/templates/SSLSocketTemplate.java @@ -58,11 +58,26 @@ import java.util.concurrent.TimeUnit; */ public class SSLSocketTemplate extends SSLContextTemplate { + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=all + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; + /* * ================== * Run the test case. */ public static void main(String[] args) throws Exception { + if (debug) { + System.setProperty("javax.net.debug", "all"); + } + (new SSLSocketTemplate()).run(); } diff --git a/test/jdk/javax/sound/midi/MidiDeviceConnectors/TestAllDevices.java b/test/jdk/javax/sound/midi/MidiDeviceConnectors/TestAllDevices.java index afac39b83fb..ed082539ed3 100644 --- a/test/jdk/javax/sound/midi/MidiDeviceConnectors/TestAllDevices.java +++ b/test/jdk/javax/sound/midi/MidiDeviceConnectors/TestAllDevices.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 diff --git a/test/jdk/javax/sound/midi/Sequencer/Looping.java b/test/jdk/javax/sound/midi/Sequencer/Looping.java index 9bcc9254653..6d2845aa61d 100644 --- a/test/jdk/javax/sound/midi/Sequencer/Looping.java +++ b/test/jdk/javax/sound/midi/Sequencer/Looping.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -36,7 +36,7 @@ import javax.sound.midi.Track; * @test * @bug 4204105 * @summary RFE: add loop() method(s) to Sequencer - * @key intermittent + * @key sound */ public class Looping { diff --git a/test/jdk/javax/sound/midi/SysexMessage/SendRawSysexMessage.java b/test/jdk/javax/sound/midi/SysexMessage/SendRawSysexMessage.java index 7b8c4b0a3f2..10770865dea 100644 --- a/test/jdk/javax/sound/midi/SysexMessage/SendRawSysexMessage.java +++ b/test/jdk/javax/sound/midi/SysexMessage/SendRawSysexMessage.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 diff --git a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/ExpectedNPEOnNull.java b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/ExpectedNPEOnNull.java index 05ba16cded5..771860fd7c3 100644 --- a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/ExpectedNPEOnNull.java +++ b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/ExpectedNPEOnNull.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 diff --git a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/FakeInfo.java b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/FakeInfo.java index 71d27c4943c..21b448e60a1 100644 --- a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/FakeInfo.java +++ b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/FakeInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 diff --git a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/UnsupportedInfo.java b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/UnsupportedInfo.java index 5d37759fbad..5d339a0fcb6 100644 --- a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/UnsupportedInfo.java +++ b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/UnsupportedInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 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 diff --git a/test/jdk/javax/sound/sampled/Clip/ClipFlushCrash.java b/test/jdk/javax/sound/sampled/Clip/ClipFlushCrash.java index 2baeb499eac..11c4fad066f 100644 --- a/test/jdk/javax/sound/sampled/Clip/ClipFlushCrash.java +++ b/test/jdk/javax/sound/sampled/Clip/ClipFlushCrash.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 diff --git a/test/jdk/javax/sound/sampled/Clip/IsRunningHang.java b/test/jdk/javax/sound/sampled/Clip/IsRunningHang.java index c417c5ad8d0..181fc94c2ce 100644 --- a/test/jdk/javax/sound/sampled/Clip/IsRunningHang.java +++ b/test/jdk/javax/sound/sampled/Clip/IsRunningHang.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 @@ -36,6 +36,7 @@ import javax.sound.sampled.LineUnavailableException; /** * @test * @bug 8156169 + * @key sound * @run main/othervm/timeout=300 IsRunningHang */ public final class IsRunningHang { diff --git a/test/jdk/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java b/test/jdk/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java index b3198b8ab77..f18c6451433 100644 --- a/test/jdk/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java +++ b/test/jdk/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.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 @@ -32,6 +32,7 @@ import javax.sound.sampled.LineUnavailableException; /** * @test + * @key sound * @bug 8167435 */ public final class OpenNonIntegralNumberOfSampleframes { diff --git a/test/jdk/javax/sound/sampled/DataLine/LongFramePosition.java b/test/jdk/javax/sound/sampled/DataLine/LongFramePosition.java index 079a785de8b..d5252751be9 100644 --- a/test/jdk/javax/sound/sampled/DataLine/LongFramePosition.java +++ b/test/jdk/javax/sound/sampled/DataLine/LongFramePosition.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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,6 +29,7 @@ import javax.sound.sampled.SourceDataLine; /** * @test * @bug 5049129 + * @key sound * @summary DataLine.getLongFramePosition */ public class LongFramePosition { diff --git a/test/jdk/javax/sound/sampled/DirectAudio/bug6372428.java b/test/jdk/javax/sound/sampled/DirectAudio/bug6372428.java index 177ebce85a0..f2c83540a8d 100644 --- a/test/jdk/javax/sound/sampled/DirectAudio/bug6372428.java +++ b/test/jdk/javax/sound/sampled/DirectAudio/bug6372428.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -31,6 +31,7 @@ import javax.sound.sampled.TargetDataLine; /* * @test * @bug 6372428 + * @key sound * @summary playback and capture doesn't interrupt after terminating thread that * calls start() * @run main bug6372428 diff --git a/test/jdk/javax/sound/sampled/LinuxBlock/PlaySine.java b/test/jdk/javax/sound/sampled/LinuxBlock/PlaySine.java index ceead0dae62..6ae635f5d7d 100644 --- a/test/jdk/javax/sound/sampled/LinuxBlock/PlaySine.java +++ b/test/jdk/javax/sound/sampled/LinuxBlock/PlaySine.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 diff --git a/test/jdk/javax/swing/DefaultTableCellRenderer/DefRendererSerialize.java b/test/jdk/javax/swing/DefaultTableCellRenderer/DefRendererSerialize.java new file mode 100644 index 00000000000..07e1b1d51c7 --- /dev/null +++ b/test/jdk/javax/swing/DefaultTableCellRenderer/DefRendererSerialize.java @@ -0,0 +1,136 @@ +/* + * 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 4337898 + * @key headful + * @summary Verifies Serializing DefaultTableCellRenderer doesn't change colors + * @run main DefRendererSerialize + */ + +import java.awt.Color; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import javax.swing.JFrame; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.SwingUtilities; +import java.util.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +public class DefRendererSerialize { + + private static JFrame frame; + private static JTable table; + private static volatile DefaultTableCellRenderer tcr; + private static String[][] rowData = { {"1-1","1-2","1-3"}, + {"2-1","","2-3"}, + {"3-1","3-2","3-3"} }; + + private static String[] columnData = {"Column 1", "Column 2", "Column 3"}; + private static volatile Rectangle tableRect; + private static volatile Point tableOnScreen; + private static volatile Point p; + private static Color fg, bg; + + public static void main (String[] args) throws Exception { + try { + + SwingUtilities.invokeAndWait(() -> { + frame = new JFrame(); + table = new JTable(rowData, columnData); + + DefaultTableCellRenderer tcr = new DefaultTableCellRenderer(); + table.setDefaultRenderer(table.getColumnClass(1), tcr); + + fg = tcr.getForeground(); + bg = tcr.getBackground(); + System.out.println("renderer fg " + fg + " bg " + bg); + tcr = (DefaultTableCellRenderer) table.getDefaultRenderer(table.getColumnClass(1)); + + // If this try block is removed, table text remains black on white. + byte[] serializedObject = null; + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + ObjectOutputStream ostream = new ObjectOutputStream(bytes); + ostream.writeObject(tcr); + ostream.flush(); + serializedObject = bytes.toByteArray(); + } catch (IOException ioex) { + throw new RuntimeException(ioex); + } + + if (serializedObject == null) { + throw new RuntimeException("FAILED: Serialized byte array in null"); + } + try { + DefaultTableCellRenderer destcr; + try (ObjectInputStream inputStream = + new ObjectInputStream(new ByteArrayInputStream(serializedObject))) { + destcr = (DefaultTableCellRenderer) inputStream.readObject(); + } + System.out.println("deserialized renderer fg " + fg + " bg " + bg); + if (!(fg == destcr.getForeground()) || !(bg == destcr.getBackground())) { + throw new RuntimeException("Deserialized foreground and background color not same"); + } + } catch (IOException | ClassNotFoundException e) { + throw new RuntimeException(e); + } + + frame.add(table); + + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + }); + Robot robot = new Robot(); + robot.waitForIdle(); + robot.delay(1000); + SwingUtilities.invokeAndWait(() -> { + tableRect = table.getCellRect(1, 1, true); + tableOnScreen = table.getLocationOnScreen(); + + p = new Point(tableOnScreen.x + tableRect.x + tableRect.width / 2, + tableOnScreen.y + tableRect.y + tableRect.height / 2); + + }); + Color pixelColor = robot.getPixelColor(p.x, p.y); + System.out.println("pixelColor " + pixelColor); + if (!pixelColor.equals(Color.white)) { + throw new RuntimeException("Serializing DefaultTableCellRenderer changes colors"); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + } +} diff --git a/test/jdk/javax/swing/JFileChooser/6520101/bug6520101.java b/test/jdk/javax/swing/JFileChooser/6520101/bug6520101.java index f6671872ba8..131ccc0e348 100644 --- a/test/jdk/javax/swing/JFileChooser/6520101/bug6520101.java +++ b/test/jdk/javax/swing/JFileChooser/6520101/bug6520101.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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,7 +27,7 @@ * @bug 6520101 * @summary JFileChooser throws OOM in 1.4.2, 5.0u4 and 1.6.0 * @author Praveen Gupta - * @run main/othervm/timeout=600 -Xmx8m -verify bug6520101 + * @run main/othervm/timeout=600 -Xmx8m -Xverify:all bug6520101 */ import javax.swing.*; diff --git a/test/jdk/javax/swing/JInternalFrame/JIFMaximizedTrfAttribute.java b/test/jdk/javax/swing/JInternalFrame/JIFMaximizedTrfAttribute.java new file mode 100644 index 00000000000..f5030b934b6 --- /dev/null +++ b/test/jdk/javax/swing/JInternalFrame/JIFMaximizedTrfAttribute.java @@ -0,0 +1,100 @@ +/* + * 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 6681958 + * @summary Verifies Maximization state of JInternalFrames is + * not corrupted by WindowsDesktopManager + * @requires (os.family == "windows") + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual JIFMaximizedTrfAttribute + */ + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.BorderLayout; + +import javax.swing.JButton; +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.UIManager; + +import java.beans.PropertyVetoException; + +public class JIFMaximizedTrfAttribute { + + static final String INSTRUCTIONS = """ + A maximised JInternalFrame would be shown with a + button "open another internal frame". + Press the button on the internal frame. + A second internal frame is created and opened. + If second internal frame is maximized, + press Pass else press Fail."""; + + public static void main(String[] args) throws Exception { + // Set Windows L&F + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + PassFailJFrame.builder() + .title("Test Instructions") + .instructions(INSTRUCTIONS) + .columns(50) + .testUI(JIFMaximizedTrfAttribute::createUI) + .position(PassFailJFrame.Position.TOP_LEFT_CORNER) + .build() + .awaitAndCheck(); + } + + static JFrame createUI() { + + final JDesktopPane pane = new JDesktopPane(); + final JInternalFrame internal = new JInternalFrame("the first internal frame", true, true, true, true); + pane.add(internal); + internal.setBounds(0, 0, 200, 100); + try { + internal.setMaximum(true); + } catch (PropertyVetoException e) { } + internal.setVisible(true); + JButton button = new JButton("open another internal frame"); + button.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + final JInternalFrame internal2 = new JInternalFrame("another one", true, true, true, true); + pane.add(internal2); + internal2.setBounds(250, 150, 200, 100); + try { + internal2.setMaximum(true); + } catch (PropertyVetoException e) {} + internal2.setVisible(true); + } + }); + internal.add(button, BorderLayout.SOUTH); + + JFrame f = new JFrame("JIFMaximizedTrfAttribute"); + f.add(pane, BorderLayout.CENTER); + f.setSize(800, 600); + f.setLocationRelativeTo(null); + return f; + } +} diff --git a/test/jdk/javax/swing/JList/JListTest.java b/test/jdk/javax/swing/JList/JListTest.java new file mode 100644 index 00000000000..fbc9bda69e3 --- /dev/null +++ b/test/jdk/javax/swing/JList/JListTest.java @@ -0,0 +1,86 @@ +/* + * 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 8364146 + * @key headful + * @summary Verifies JList getScrollableUnitIncrement return non-negative number + * @run main JListTest + */ + +import java.awt.Dimension; +import java.awt.Rectangle; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JScrollPane; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; +public class JListTest { + + private static JFrame f; + + public static void main(String[] argv) throws Exception { + + SwingUtilities.invokeAndWait(() -> { + try { + f = new JFrame(); + String[] data = {"One", "Two", "Three", "Four", "Five", "Six ", + "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelv"}; + JList list = new JList<>(data); + list.setLayoutOrientation(JList.HORIZONTAL_WRAP); + + JScrollPane sp = new JScrollPane(list); + sp.setPreferredSize(new Dimension(200, 200)); + f.add(sp); + f.pack(); + f.setVisible(true); + + Rectangle cell = list.getCellBounds(1, data.length); + System.out.println(cell); + cell.y = list.getHeight() + 10; + int unit = list.getScrollableUnitIncrement( + cell, + SwingConstants.VERTICAL, + -1); + System.out.println("Scrollable unit increment: " + unit); + + if (unit < 0) { + throw new RuntimeException("JList scrollable unit increment should be greater than 0."); + } + unit = list.getScrollableUnitIncrement( + cell, + SwingConstants.VERTICAL, + 1); + System.out.println("Scrollable unit increment: " + unit); + if (unit < 0) { + throw new RuntimeException("JList scrollable unit increment should be greater than 0."); + } + } finally { + if (f != null) { + f.dispose(); + } + } + }); + } +} diff --git a/test/jdk/javax/swing/JMenu/TestPaintSpillOverBug.java b/test/jdk/javax/swing/JMenu/TestPaintSpillOverBug.java new file mode 100644 index 00000000000..8452b93cf45 --- /dev/null +++ b/test/jdk/javax/swing/JMenu/TestPaintSpillOverBug.java @@ -0,0 +1,82 @@ +/* + * 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 6223700 + * @requires (os.family == "windows") + * @summary Verifies no painting spillover in Win L&F + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TestPaintSpillOverBug + */ + +import javax.swing.JFrame; +import javax.swing.JMenuBar; +import javax.swing.JMenu; +import javax.swing.UIManager; + +public class TestPaintSpillOverBug { + + static final String INSTRUCTIONS = """ + A JMenu "click Me" will be shown. Click on it. + Position the mouse in the "Slowly Move Mouse Out of This" JMenu + so that the popup menu appears to the right. + Slowly move the mouse towards the edge of the item, + one pixel at a time + When the mouse hits the edge, + if the selection background spill over on to the popup + press Fail else press Pass."""; + + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + + PassFailJFrame.builder() + .title("TestPaintSpillOverBug Instructions") + .instructions(INSTRUCTIONS) + .columns(60) + .testUI(TestPaintSpillOverBug::createUI) + .position(PassFailJFrame.Position.TOP_LEFT_CORNER) + .build() + .awaitAndCheck(); + + } + + static JFrame createUI() { + JFrame f = new JFrame("TestPaintSpillOverBug"); + JMenuBar bar = new JMenuBar(); + JMenu clickMe = new JMenu("Click Me"); + JMenu culprit = new JMenu("Slowly Move Mouse Out of This"); + culprit.add("This item gets partially obscured"); + culprit.add(" "); + clickMe.add(" "); + clickMe.addSeparator(); + clickMe.add(culprit); + clickMe.addSeparator(); + clickMe.add(" "); + bar.add(clickMe); + f.setJMenuBar(bar); + f.setSize(600, 200); + return f; + } +} diff --git a/test/jdk/javax/swing/JMenuItem/MenuItemTest/bug6197830.java b/test/jdk/javax/swing/JMenuItem/MenuItemTest/bug6197830.java index afb1c7bb33f..5a30e202d9d 100644 --- a/test/jdk/javax/swing/JMenuItem/MenuItemTest/bug6197830.java +++ b/test/jdk/javax/swing/JMenuItem/MenuItemTest/bug6197830.java @@ -49,6 +49,7 @@ public class bug6197830 { .columns(35) .testUI(bug6197830::createTestUI) .positionTestUIBottomRowCentered() + .logArea() .build() .awaitAndCheck(); } diff --git a/test/jdk/javax/swing/JOptionPane/bug4174551.java b/test/jdk/javax/swing/JOptionPane/bug4174551.java index dbe6cdffe1a..ab96b28255f 100644 --- a/test/jdk/javax/swing/JOptionPane/bug4174551.java +++ b/test/jdk/javax/swing/JOptionPane/bug4174551.java @@ -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 diff --git a/test/jdk/javax/swing/JProgressBar/TestProgressBarBorder.java b/test/jdk/javax/swing/JProgressBar/TestProgressBarBorder.java deleted file mode 100644 index 06ccfc3b9bf..00000000000 --- a/test/jdk/javax/swing/JProgressBar/TestProgressBarBorder.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.awt.Graphics; -import java.awt.image.BufferedImage; -import javax.imageio.ImageIO; -import javax.swing.JComponent; -import javax.swing.JProgressBar; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.UnsupportedLookAndFeelException; - -import static java.awt.image.BufferedImage.TYPE_INT_RGB; - -/* - * @test - * @bug 8224261 - * @key headful - * @library ../regtesthelpers - * @build Util - * @summary Verifies JProgressBar border is not painted when border - * painting is set to false - * @run main TestProgressBarBorder - */ - -public class TestProgressBarBorder { - public static void main(String[] args) throws Exception { - for (UIManager.LookAndFeelInfo laf : - UIManager.getInstalledLookAndFeels()) { - if (!laf.getName().contains("Nimbus") && !laf.getName().contains("GTK")) { - continue; - } - System.out.println("Testing LAF: " + laf.getName()); - SwingUtilities.invokeAndWait(() -> test(laf)); - } - } - - private static void test(UIManager.LookAndFeelInfo laf) { - setLookAndFeel(laf); - JProgressBar progressBar = createProgressBar(); - progressBar.setBorderPainted(true); - BufferedImage withBorder = paintToImage(progressBar); - progressBar.setBorderPainted(false); - BufferedImage withoutBorder = paintToImage(progressBar); - - boolean equal = Util.compareBufferedImages(withBorder, withoutBorder); - if (equal) { - try { - ImageIO.write(withBorder, "png", new File("withBorder.png")); - ImageIO.write(withoutBorder, "png", new File("withoutBorder.png")); - } catch (IOException ignored) {} - - throw new RuntimeException("JProgressBar border is painted when border " + - "painting is set to false"); - } - } - - private static void setLookAndFeel(UIManager.LookAndFeelInfo laf) { - try { - UIManager.setLookAndFeel(laf.getClassName()); - } catch (UnsupportedLookAndFeelException ignored) { - System.out.println("Unsupported LAF: " + laf.getClassName()); - } catch (ClassNotFoundException | InstantiationException - | IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - private static JProgressBar createProgressBar() { - JProgressBar progressBar = new JProgressBar(); - progressBar.setSize(100, 50); - progressBar.setValue(0); - progressBar.setStringPainted(true); - return progressBar; - } - - private static BufferedImage paintToImage(JComponent content) { - BufferedImage im = new BufferedImage(content.getWidth(), content.getHeight(), - TYPE_INT_RGB); - Graphics g = im.getGraphics(); - content.paint(g); - g.dispose(); - return im; - } -} diff --git a/test/jdk/javax/swing/JSplitPane/TestSplitPaneCompResize.java b/test/jdk/javax/swing/JSplitPane/TestSplitPaneCompResize.java new file mode 100644 index 00000000000..07d9b77f90e --- /dev/null +++ b/test/jdk/javax/swing/JSplitPane/TestSplitPaneCompResize.java @@ -0,0 +1,173 @@ +/* + * 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 4765299 + * @key headful + * @summary Verifies componentResized() is called with nested JSplitPanes + * @run main TestSplitPaneCompResize + */ + +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.InputEvent; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JPanel; +import javax.swing.ListSelectionModel; +import javax.swing.plaf.basic.BasicSplitPaneDivider; +import javax.swing.plaf.basic.BasicSplitPaneUI; +import javax.swing.SwingUtilities; + +public class TestSplitPaneCompResize { + + private static JFrame frame; + private JSplitPane outer; + private static JButton leftOneTouchButton; + private static volatile Point leftBtnPos; + private static volatile boolean resized; + + public TestSplitPaneCompResize() { + + // set up a simple list embedded inside a scroll pane + String[] listItems = {"Item1", "Item2"}; + JList list = new JList<>(listItems); + list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + list.setSelectedIndex(0); + + JScrollPane comp = new JScrollPane(list); + JSplitPane inner = new JSplitPane(JSplitPane.VERTICAL_SPLIT, + comp, new JPanel()); + JPanel rightPanel = new JPanel(); + + outer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, + inner, rightPanel); + outer.setDividerLocation(150); + + //Provide minimum sizes for the two components in the split pane + Dimension minimumSize = new Dimension(100, 50); + comp.setMinimumSize(minimumSize); + inner.setMinimumSize(minimumSize); + rightPanel.setMinimumSize(minimumSize); + + //Provide a preferred size for the split pane + outer.setPreferredSize(new Dimension(400, 200)); + inner.addComponentListener(new ComponentAdapter() { + public void componentResized(ComponentEvent e) { + System.out.println("inner resized"); + } + }); + comp.addComponentListener(new ComponentAdapter() { + public void componentResized(ComponentEvent e) { + resized = true; + System.out.println("comp resized"); + } + }); + } + + public JSplitPane getSplitPane() { + return outer; + } + + + public static void main(String[] s) throws Exception { + Robot robot = new Robot(); + try { + SwingUtilities.invokeAndWait(() -> { + frame = new JFrame("SplitPaneDemo"); + + TestSplitPaneCompResize sp = new TestSplitPaneCompResize(); + JSplitPane jsp = sp.getSplitPane(); + frame.getContentPane().add(jsp); + jsp.setUI(new MySplitPaneUI()); + jsp.setOneTouchExpandable(true); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + }); + + robot.waitForIdle(); + robot.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + leftBtnPos = leftOneTouchButton.getLocationOnScreen(); + leftBtnPos.x += leftOneTouchButton.getWidth() / 2; + leftBtnPos.y += leftOneTouchButton.getHeight() / 2; + }); + + resized = false; + robot.mouseMove(leftBtnPos.x, leftBtnPos.y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.delay(1000); + + if (!resized) { + throw new RuntimeException("ComponentResized not called"); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + } + + + static class MySplitPaneUI extends BasicSplitPaneUI { + + public MySplitPaneUI() { + super(); + } + + public BasicSplitPaneDivider createDefaultDivider() { + return new MySplitPaneDivider(this); + } + } + + static class MySplitPaneDivider extends BasicSplitPaneDivider { + + public MySplitPaneDivider(BasicSplitPaneUI ui) { + super(ui); + } + + protected JButton createLeftOneTouchButton() { + leftOneTouchButton = super.createLeftOneTouchButton(); + return leftOneTouchButton; + } + + protected JButton createRightOneTouchButton() { + JButton rightOneTouchButton = super.createRightOneTouchButton(); + return rightOneTouchButton; + } + } +} diff --git a/test/jdk/javax/swing/JTabbedPane/TabbedPaneBugWithLNF.java b/test/jdk/javax/swing/JTabbedPane/TabbedPaneBugWithLNF.java new file mode 100644 index 00000000000..cf989280da2 --- /dev/null +++ b/test/jdk/javax/swing/JTabbedPane/TabbedPaneBugWithLNF.java @@ -0,0 +1,110 @@ +/* + * 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 4459231 + * @summary Verifies if JTabbedPane(with Scrollable tablayout) changes focus + * on change in LookAndFeel + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TabbedPaneBugWithLNF + */ + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +public class TabbedPaneBugWithLNF { + + private static String LNF = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; + private static JTabbedPane tabPane; + private static JButton testBtn; + + static final String INSTRUCTIONS = """ + A JTabbedPane with 10 tabs will be shown. + Scroll the tabs till the end, i.e., to "Testing Tab9". + Select that tab. + You will see the main tab JButton's text changed to 'Test Button9'. + Click on it, which will change the lookandfeel. + Verify if child tabs have scrolled back to starting child tab + i.e., 'Testing Tab0', where as the selected tab is still 'Testing Tab9'. + If it does, press Fail + else if focus of the child Tab is still at "Testing Tab9" press Pass."""; + + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); + PassFailJFrame.builder() + .title("TabbedPaneBugWithLNF Test Instructions") + .instructions(INSTRUCTIONS) + .columns(50) + .testUI(TabbedPaneBugWithLNF::createUI) + .position(PassFailJFrame.Position.TOP_LEFT_CORNER) + .build() + .awaitAndCheck(); + } + + static JFrame createUI() { + JFrame frame = new JFrame("TabbedPaneBugWithLNF"); + frame.setSize(640, 180); + + tabPane = new JTabbedPane(JTabbedPane.BOTTOM,JTabbedPane.SCROLL_TAB_LAYOUT); + + tabPane.addTab("Testing Tab0", testBtn = new JButton("Test Button0")); + + tabPane.addTab("Testing Tab1", testBtn = new JButton("Test Button1")); + + tabPane.addTab("Testing Tab2", testBtn = new JButton("Test Button2")); + + tabPane.addTab("Testing Tab3", testBtn = new JButton("Test Button3")); + + tabPane.addTab("Testing Tab4", testBtn = new JButton("Test Button4")); + + tabPane.addTab("Testing Tab5", testBtn = new JButton("Test Button5")); + + tabPane.addTab("Testing Tab6", testBtn = new JButton("Test Button6")); + + tabPane.addTab("Testing Tab7", testBtn = new JButton("Test Button7")); + tabPane.addTab("Testing Tab8", testBtn = new JButton("Test Button8")); + JButton myBtn = null; + tabPane.addTab("Testing Tab9", myBtn = new JButton("Test Button9")); + myBtn.addActionListener( new ActionListener() { + public void actionPerformed(ActionEvent ae) { + try { + UIManager.setLookAndFeel(LNF); + SwingUtilities.updateComponentTreeUI(frame); + System.out.println("tabPane.selectedIndex " + tabPane.getSelectedIndex()); + } catch (Exception exc) { + System.out.println("Error changing L&F : " + LNF); + } + } + }); + frame.add(tabPane); + return frame; + } +} + diff --git a/test/jdk/javax/swing/JTable/TestRowHeightWithColIdentifier.java b/test/jdk/javax/swing/JTable/TestRowHeightWithColIdentifier.java new file mode 100644 index 00000000000..ad2015e3b45 --- /dev/null +++ b/test/jdk/javax/swing/JTable/TestRowHeightWithColIdentifier.java @@ -0,0 +1,64 @@ +/* + * 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 6292135 + * @summary Verifies DefaultTableModel.setColumnIdentifiers() doesn't + * clear JTable Row Heights + * @run main TestRowHeightWithColIdentifier + */ + +import javax.swing.JTable; +import javax.swing.SwingUtilities; +import javax.swing.table.DefaultTableModel; + +public class TestRowHeightWithColIdentifier{ + + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + DefaultTableModel model = new DefaultTableModel(null, new Object[] {"FOO", "BAR"}); + JTable table = new JTable(model); + + model.addRow(new Object[] {"00", "01"}); + model.addRow(new Object[] {"10", "11"}); + model.addRow(new Object[] {"20", "21"}); + for (int row = 0; row < table.getRowCount(); row++) { + table.setRowHeight(row, 100); + } + for (int row = 0; row < table.getRowCount(); row++) { + System.out.println("Before table rowHeight " + table.getRowHeight(row)); + } + int oldRowHeight = table.getRowHeight(0); + model.setColumnIdentifiers(new Object[] {"Check", "it out!"}); + for (int row = 0; row < table.getRowCount(); row++) { + System.out.println("After table rowHeight " + table.getRowHeight(row)); + } + int curRowHeight = table.getRowHeight(0); + if (curRowHeight != oldRowHeight) { + throw new RuntimeException("DefaultTableModel.setColumnIdentifiers() Clears JTable Row Height"); + } + }); + } +} diff --git a/test/jdk/javax/swing/JTextArea/4697612/bug4697612.java b/test/jdk/javax/swing/JTextArea/4697612/bug4697612.java index ee01c38ed67..9ba788f09f2 100644 --- a/test/jdk/javax/swing/JTextArea/4697612/bug4697612.java +++ b/test/jdk/javax/swing/JTextArea/4697612/bug4697612.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 diff --git a/test/jdk/javax/swing/JTree/JTreeUpdateTest.java b/test/jdk/javax/swing/JTree/JTreeUpdateTest.java new file mode 100644 index 00000000000..6b0a4f03c29 --- /dev/null +++ b/test/jdk/javax/swing/JTree/JTreeUpdateTest.java @@ -0,0 +1,96 @@ +/* + * 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 8042054 + * @summary JTree.updateUI should use updated item size information + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual JTreeUpdateTest + */ + +import java.awt.BorderLayout; +import java.awt.Dimension; +import javax.swing.BorderFactory; +import javax.swing.JFrame; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.UIManager; + +public class JTreeUpdateTest { + + static final String INSTRUCTIONS = """ + A frame with two identical JTrees is shown. + If the left JTree's text is abbreviated and JTree items + are cramped with little space between rows then press Fail. + If the left JTree is identical with right JTree, press Pass. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("JTreeUpdateTest Test instructions") + .instructions(INSTRUCTIONS) + .columns(30) + .testUI(JTreeUpdateTest::createUI) + .build() + .awaitAndCheck(); + } + + private static JFrame createUI() { + setLaf("javax.swing.plaf.metal.MetalLookAndFeel"); + + final JFrame frame = new JFrame("JTreeUpdateTest"); + + final JTree tree = new JTree(); + tree.setPreferredSize(new Dimension(200, 200)); + tree.setCellRenderer(new DefaultTreeCellRenderer()); + tree.setBorder(BorderFactory.createTitledBorder("updateUI() called once")); + frame.add(tree); + + final JTree tree2 = new JTree(); + tree2.setPreferredSize(new Dimension(200, 200)); + tree2.setCellRenderer(new DefaultTreeCellRenderer()); + tree2.setBorder(BorderFactory.createTitledBorder("updateUI() called twice")); + frame.add(tree2, BorderLayout.EAST); + + frame.pack(); + frame.setLocationRelativeTo(null); + + SwingUtilities.invokeLater(() -> { + setLaf("javax.swing.plaf.nimbus.NimbusLookAndFeel"); + SwingUtilities.updateComponentTreeUI(frame); + SwingUtilities.updateComponentTreeUI(tree2); + }); + return frame; + } + + private static void setLaf(String className) { + try { + UIManager.setLookAndFeel(className); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} 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/javax/swing/SwingUtilities/UIMapTest.java b/test/jdk/javax/swing/SwingUtilities/UIMapTest.java new file mode 100644 index 00000000000..4a801580b35 --- /dev/null +++ b/test/jdk/javax/swing/SwingUtilities/UIMapTest.java @@ -0,0 +1,90 @@ +/* + * 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 6726690 + * @summary Verifies SwingUtilities.replaceUI*Map() methods remove + * previously installed maps + * @run main UIMapTest + */ + +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.ActionMap; +import javax.swing.ComponentInputMap; +import javax.swing.InputMap; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; + +public class UIMapTest { + + public static void main(String[] args) { + + StringBuilder str = new StringBuilder(); + + // Create the test button + JButton button = new JButton("Test"); + + // Create an input map that maps ENTER to the button + ComponentInputMap map = new ComponentInputMap(button); + map.put(KeyStroke.getKeyStroke("pressed ENTER"), "pressed"); + map.put(KeyStroke.getKeyStroke("released ENTER"), "released"); + + // Add the map + SwingUtilities.replaceUIInputMap(button, JComponent.WHEN_IN_FOCUSED_WINDOW, map); + + // Attempt to remove the map + SwingUtilities.replaceUIInputMap(button, JComponent.WHEN_IN_FOCUSED_WINDOW, null); + + if (button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + get(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)) != null) { + str.append("\nSwingUtilities.replaceUIInputMap " + + "didn't remove previously installed input map"); + } + + // Get the InputMap for the button when it has focus + InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); + + // Map the VK_ENTER key stroke to a specific action name + inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "doEnterAction"); + Action enterAction = new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { } + }; + button.getActionMap().put("doEnterAction", enterAction); + SwingUtilities.replaceUIActionMap(button, null); + if (button.getActionMap().size() != 0) { + str.append("\nSwingUtilities.replaceUIActionMap " + + "didn't remove previously installed action map"); + } + if (str.length() != 0) { + throw new RuntimeException(str.toString()); + } + } +} diff --git a/test/jdk/javax/swing/plaf/motif/TestIconRTL.java b/test/jdk/javax/swing/plaf/motif/TestIconRTL.java new file mode 100644 index 00000000000..e86e1ab38a6 --- /dev/null +++ b/test/jdk/javax/swing/plaf/motif/TestIconRTL.java @@ -0,0 +1,119 @@ +/* + * 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 5107379 + * @summary Component orientation in JOptionPane is not proper in Motif L&F. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TestIconRTL + */ + +import java.awt.ComponentOrientation; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +public class TestIconRTL { + + private static JFrame frame; + private static JOptionPane pane; + + static final String INSTRUCTIONS = """ + A JOptionPane is shown in Motif LookAndFeel with "Orientation" menu. + Click on "Orientation" menu and + test with "Left To Right" and "Right to Left" Orientation + If JOptionPane is drawn properly in different orientation, + then test passed, otherwise it failed."""; + + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); + PassFailJFrame.builder() + .title("TestIconRTL Instructions") + .instructions(INSTRUCTIONS) + .columns(60) + .testUI(TestIconRTL::createTestUI) + .build() + .awaitAndCheck(); + } + + static JFrame createTestUI() { + pane = new JOptionPane(new String("Testing CCC4265463"), + JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION); + pane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); + pane.setVisible(true); + + frame = new JFrame("TestIconRTL"); + + JMenuBar menuBar = new JMenuBar(); + menuBar.add(getOrientationJMenu()); + + frame.setJMenuBar(menuBar); + + frame.getContentPane().add(pane); + frame.pack(); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.setLocationRelativeTo(null); + return frame; + } + + public static void test() throws Exception { + AtomicBoolean leftToRightOrientationFlag = new AtomicBoolean(false); + SwingUtilities.invokeAndWait(() -> leftToRightOrientationFlag.set(pane.getComponentOrientation().isLeftToRight())); + if (leftToRightOrientationFlag.get()) { + System.out.println("LTR LOCATION ..."); + } else { + System.out.println("RTL LOCATION ..."); + } + } + + private static JMenu getOrientationJMenu() { + JMenu lafMenu = new JMenu("Orientation"); + JMenuItem leftToRight = new JMenuItem("Left to Right"); + leftToRight.addActionListener(e -> { + pane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); + pane.invalidate(); + SwingUtilities.updateComponentTreeUI(frame); + }); + + JMenuItem rightToLeft = new JMenuItem("Right to Left"); + rightToLeft.addActionListener(e -> { + pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); + pane.invalidate(); + SwingUtilities.updateComponentTreeUI(frame); + }); + + pane.invalidate(); + lafMenu.add(leftToRight); + lafMenu.add(rightToLeft); + return lafMenu; + } + + +} diff --git a/test/jdk/javax/swing/plaf/nimbus/TestNimbusProgressBarBorder.java b/test/jdk/javax/swing/plaf/nimbus/TestNimbusProgressBarBorder.java new file mode 100644 index 00000000000..f9aade1d24d --- /dev/null +++ b/test/jdk/javax/swing/plaf/nimbus/TestNimbusProgressBarBorder.java @@ -0,0 +1,123 @@ +/* + * 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 8192888 + * @key headful + * @summary Verifies ProgressBar in Synth L&F renders background + * when border is not painted + * @run main TestNimbusProgressBarBorder + */ + +import java.io.File; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.GridBagLayout; +import java.awt.image.BufferedImage; +import java.awt.Rectangle; +import java.awt.Robot; + +import javax.imageio.ImageIO; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.UIManager; +import javax.swing.SwingUtilities; + +public class TestNimbusProgressBarBorder { + + private static JFrame frame; + private static JProgressBar progressBar; + private static boolean failure = true; + private static volatile Rectangle rect; + + public static void main(String[] args) throws Exception { + int width = 200; + int height = 100; + try { + Robot robot = new Robot(); + SwingUtilities.invokeAndWait(() -> { + try { + // Set Nimbus L&F + UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); + } catch (Exception e) { + throw new RuntimeException(e); + } + frame = new JFrame("Nimbus JProgressBar Test"); + frame.setSize(width, height); + + // ProgressBar setup + progressBar = new JProgressBar(0, 100); + progressBar.setValue(0); + progressBar.setBorderPainted(false); + + JPanel center = new JPanel(new GridBagLayout()); + center.setBackground(Color.WHITE); + center.add(progressBar); + + frame.add(center, BorderLayout.CENTER); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + }); + robot.waitForIdle(); + robot.delay(1000); + SwingUtilities.invokeAndWait(() -> { + rect = progressBar.getBounds(); + }); + + BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + Graphics2D g2d = (Graphics2D) img.getGraphics(); + g2d.setColor(Color.WHITE); + g2d.fillRect(0, 0, rect.width, rect.height); + progressBar.paint(g2d); + g2d.dispose(); + + robot.waitForIdle(); + robot.delay(100); + + for (int x = 10; x < (10 + rect.width / 2); x++) { + for (int y = 10; y < (10 + rect.height / 2); y++) { + Color col = new Color(img.getRGB(x, y)); + if (!col.equals(Color.WHITE)) { + failure = false; + break; + } + } + } + if (failure) { + ImageIO.write(img, "png", new File("ProgressBarTest.png")); + throw new RuntimeException("ProgressBar background not drawn"); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + } +} diff --git a/test/jdk/javax/swing/text/html/parser/Parser/6990651/bug6990651.java b/test/jdk/javax/swing/text/html/parser/Parser/6990651/bug6990651.java index 9dada22ba60..0f8e3358eb6 100644 --- a/test/jdk/javax/swing/text/html/parser/Parser/6990651/bug6990651.java +++ b/test/jdk/javax/swing/text/html/parser/Parser/6990651/bug6990651.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 diff --git a/test/jdk/javax/swing/text/html/parser/Parser/8078268/bug8078268.java b/test/jdk/javax/swing/text/html/parser/Parser/8078268/bug8078268.java index 363cb94d924..609542d3be6 100644 --- a/test/jdk/javax/swing/text/html/parser/Parser/8078268/bug8078268.java +++ b/test/jdk/javax/swing/text/html/parser/Parser/8078268/bug8078268.java @@ -1,5 +1,5 @@ /* -* Copyright (c) 2016, 2023, 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 diff --git a/test/jdk/jdk/classfile/InstructionValidationTest.java b/test/jdk/jdk/classfile/InstructionValidationTest.java index f02c7a9c78c..190cbffca55 100644 --- a/test/jdk/jdk/classfile/InstructionValidationTest.java +++ b/test/jdk/jdk/classfile/InstructionValidationTest.java @@ -195,6 +195,7 @@ class InstructionValidationTest { ensureFailFast(i, cob -> cob.iinc(i, 1)); } check(fails, () -> IncrementInstruction.of(i, 1)); + check(fails, () -> IncrementInstruction.of(IINC_W, i, 1)); check(fails, () -> DiscontinuedInstruction.RetInstruction.of(i)); check(fails, () -> DiscontinuedInstruction.RetInstruction.of(RET_W, i)); check(fails, () -> LocalVariable.of(i, "test", CD_Object, dummyLabel, dummyLabel)); @@ -208,6 +209,7 @@ class InstructionValidationTest { check(fails, () -> LoadInstruction.of(u1Op, i)); for (var u1Op : List.of(ASTORE, ISTORE, LSTORE, FSTORE, DSTORE)) check(fails, () -> StoreInstruction.of(u1Op, i)); + check(fails, () -> IncrementInstruction.of(IINC, i, 1)); check(fails, () -> DiscontinuedInstruction.RetInstruction.of(RET, i)); } @@ -250,6 +252,13 @@ class InstructionValidationTest { IncrementInstruction.of(0, 2); IncrementInstruction.of(0, Short.MAX_VALUE); IncrementInstruction.of(0, Short.MIN_VALUE); + IncrementInstruction.of(IINC, 0, 2); + IncrementInstruction.of(IINC, 0, Byte.MIN_VALUE); + IncrementInstruction.of(IINC, 0, Byte.MAX_VALUE); + IncrementInstruction.of(IINC_W, 0, 2); + IncrementInstruction.of(IINC_W, 0, Short.MIN_VALUE); + IncrementInstruction.of(IINC_W, 0, Short.MAX_VALUE); + for (int i : new int[] {Short.MIN_VALUE - 1, Short.MAX_VALUE + 1}) { assertThrows(IllegalArgumentException.class, () -> IncrementInstruction.of(0, i)); TestUtil.runCodeHandler(cob -> { @@ -257,6 +266,12 @@ class InstructionValidationTest { cob.return_(); }); } + for (int i : new int[] {Byte.MIN_VALUE - 1, Byte.MAX_VALUE + 1}) { + assertThrows(IllegalArgumentException.class, () -> IncrementInstruction.of(IINC, 0, i)); + } + for (int i : new int[] {Short.MIN_VALUE - 1, Short.MAX_VALUE + 1}) { + assertThrows(IllegalArgumentException.class, () -> IncrementInstruction.of(IINC_W, 0, i)); + } } @Test diff --git a/test/jdk/jdk/incubator/vector/AbstractVectorTest.java b/test/jdk/jdk/incubator/vector/AbstractVectorTest.java index 71cabe75b76..99824d6e693 100644 --- a/test/jdk/jdk/incubator/vector/AbstractVectorTest.java +++ b/test/jdk/jdk/incubator/vector/AbstractVectorTest.java @@ -110,15 +110,12 @@ public class AbstractVectorTest { } static final List> BOOLEAN_MASK_GENERATORS = List.of( - withToString("mask[i % 2]", (int l) -> { - boolean[] a = new boolean[l]; - for (int i = 0; i < l; i++) { - a[i] = (i % 2 == 0); - } - return a; + withToString("mask[i % 2]", (int s) -> { + return fill_boolean(s, + i -> ((i % 2) == 0)); }), - withToString("mask[true]", (int l) -> { - boolean[] a = new boolean[l]; + withToString("mask[true]", (int s) -> { + boolean[] a = new boolean[s]; Arrays.fill(a, true); return a; }), @@ -131,6 +128,26 @@ public class AbstractVectorTest { flatMap(fa -> BOOLEAN_MASK_GENERATORS.stream().skip(1).map( fb -> List.of(fa, fb))).collect(Collectors.toList()); + static long[] pack_booleans_to_longs(boolean[] mask) { + int totalLongs = (mask.length + 63) / 64; // ceil division + long[] packed = new long[totalLongs]; + for (int i = 0; i < mask.length; i++) { + int longIndex = i / 64; + int bitIndex = i % 64; + if (mask[i]) { + packed[longIndex] |= 1L << bitIndex; + } + } + return packed; + } + + static final List> LONG_MASK_GENERATORS = BOOLEAN_MASK_GENERATORS.stream() + .map(f -> withToString( + f.toString().replace("mask", "long_mask"), + (IntFunction) (int l) -> pack_booleans_to_longs(f.apply(l)) + )) + .collect(Collectors.toList()); + static final List> INT_SHUFFLE_GENERATORS = List.of( withToStringBi("shuffle[random]", (Integer l, Integer m) -> RAND.ints(l, 0, m).toArray()) @@ -210,21 +227,6 @@ public class AbstractVectorTest { return a; } - interface FBooleanBinOp { - boolean apply(boolean a, boolean b); - } - - static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBooleanBinOp f) { - int i = 0; - try { - for (; i < a.length; i++) { - Assert.assertEquals(r[i], f.apply(a[i], b[i])); - } - } catch (AssertionError e) { - Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); - } - } - // Non-optimized test partial wrap derived from the Spec: // Validation function for lane indexes which may be out of the valid range of [0..VLENGTH-1]. // The index is forced into this range by adding or subtracting a suitable multiple of VLENGTH. diff --git a/test/jdk/jdk/incubator/vector/Byte128VectorTests.java b/test/jdk/jdk/incubator/vector/Byte128VectorTests.java index bea4d541987..fae7b678a09 100644 --- a/test/jdk/jdk/incubator/vector/Byte128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Byte128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Byte128VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final byte CONST_SHIFT = Byte.SIZE / 2; + // Identity values for reduction operations + private static final byte ADD_IDENTITY = (byte)0; + private static final byte AND_IDENTITY = (byte)-1; + private static final byte FIRST_NONZERO_IDENTITY = (byte)0; + private static final byte MAX_IDENTITY = Byte.MIN_VALUE; + private static final byte MIN_IDENTITY = Byte.MAX_VALUE; + private static final byte MUL_IDENTITY = (byte)1; + private static final byte OR_IDENTITY = (byte)0; + private static final byte SUADD_IDENTITY = (byte)0; + private static final byte UMAX_IDENTITY = (byte)0; // Minimum unsigned value + private static final byte UMIN_IDENTITY = (byte)-1; // Maximum unsigned value + private static final byte XOR_IDENTITY = (byte)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 128); static void assertArraysStrictlyEquals(byte[] r, byte[] a) { @@ -393,6 +405,36 @@ public class Byte128VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { byte apply(byte a, byte b); } @@ -1232,8 +1274,23 @@ public class Byte128VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3566,7 +3623,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte ANDReduce(byte[] a, int idx) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3575,7 +3632,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte ANDReduceAll(byte[] a) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3587,20 +3644,15 @@ public class Byte128VectorTests extends AbstractVectorTest { static void ANDReduceByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = -1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + byte v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3608,8 +3660,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::ANDReduce, Byte128VectorTests::ANDReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = AND_IDENTITY; + + Assert.assertEquals((byte) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id & x), x); + Assert.assertEquals((byte) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static byte ANDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3619,7 +3694,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte ANDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3633,20 +3708,15 @@ public class Byte128VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = -1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + byte v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3655,7 +3725,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte ORReduce(byte[] a, int idx) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3664,7 +3734,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte ORReduceAll(byte[] a) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3679,17 +3749,12 @@ public class Byte128VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + byte v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3697,8 +3762,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::ORReduce, Byte128VectorTests::ORReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = OR_IDENTITY; + + Assert.assertEquals((byte) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id | x), x); + Assert.assertEquals((byte) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static byte ORReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3708,7 +3796,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte ORReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3725,17 +3813,12 @@ public class Byte128VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + byte v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3744,7 +3827,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte XORReduce(byte[] a, int idx) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3753,7 +3836,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte XORReduceAll(byte[] a) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3768,17 +3851,12 @@ public class Byte128VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + byte v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3786,8 +3864,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::XORReduce, Byte128VectorTests::XORReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = XOR_IDENTITY; + + Assert.assertEquals((byte) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id ^ x), x); + Assert.assertEquals((byte) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static byte XORReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3797,7 +3898,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte XORReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3814,17 +3915,12 @@ public class Byte128VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + byte v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3833,7 +3929,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte ADDReduce(byte[] a, int idx) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3842,7 +3938,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte ADDReduceAll(byte[] a) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3857,17 +3953,12 @@ public class Byte128VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + byte v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3875,8 +3966,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::ADDReduce, Byte128VectorTests::ADDReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = ADD_IDENTITY; + + Assert.assertEquals((byte) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id + x), x); + Assert.assertEquals((byte) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static byte ADDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3886,7 +4000,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte ADDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3903,17 +4017,12 @@ public class Byte128VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + byte v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3922,7 +4031,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte MULReduce(byte[] a, int idx) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3931,7 +4040,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte MULReduceAll(byte[] a) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3943,20 +4052,15 @@ public class Byte128VectorTests extends AbstractVectorTest { static void MULReduceByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = 1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + byte v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -3964,8 +4068,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::MULReduce, Byte128VectorTests::MULReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MUL_IDENTITY; + + Assert.assertEquals((byte) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id * x), x); + Assert.assertEquals((byte) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static byte MULReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -3975,7 +4102,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte MULReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -3989,20 +4116,15 @@ public class Byte128VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = 1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + byte v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4011,7 +4133,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte MINReduce(byte[] a, int idx) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) Math.min(res, a[i]); } @@ -4020,7 +4142,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte MINReduceAll(byte[] a) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.min(res, MINReduce(a, i)); } @@ -4032,20 +4154,15 @@ public class Byte128VectorTests extends AbstractVectorTest { static void MINReduceByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + byte v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (byte) Math.min(ra, v); } } @@ -4053,8 +4170,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::MINReduce, Byte128VectorTests::MINReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MIN_IDENTITY; + + Assert.assertEquals((byte) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) Math.min(id, x), x); + Assert.assertEquals((byte) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static byte MINReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) Math.min(res, a[i]); @@ -4064,7 +4204,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte MINReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4078,20 +4218,15 @@ public class Byte128VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + byte v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (byte) Math.min(ra, v); } } @@ -4100,7 +4235,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte MAXReduce(byte[] a, int idx) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) Math.max(res, a[i]); } @@ -4109,7 +4244,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte MAXReduceAll(byte[] a) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.max(res, MAXReduce(a, i)); } @@ -4121,20 +4256,15 @@ public class Byte128VectorTests extends AbstractVectorTest { static void MAXReduceByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + byte v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (byte) Math.max(ra, v); } } @@ -4142,8 +4272,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::MAXReduce, Byte128VectorTests::MAXReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MAX_IDENTITY; + + Assert.assertEquals((byte) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) Math.max(id, x), x); + Assert.assertEquals((byte) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static byte MAXReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) Math.max(res, a[i]); @@ -4153,7 +4306,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte MAXReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4167,20 +4320,15 @@ public class Byte128VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + byte v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (byte) Math.max(ra, v); } } @@ -4189,7 +4337,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte UMINReduce(byte[] a, int idx) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.minUnsigned(res, a[i]); } @@ -4198,7 +4346,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte UMINReduceAll(byte[] a) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4210,20 +4358,15 @@ public class Byte128VectorTests extends AbstractVectorTest { static void UMINReduceByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + byte v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (byte) VectorMath.minUnsigned(ra, v); } } @@ -4231,8 +4374,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::UMINReduce, Byte128VectorTests::UMINReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = UMIN_IDENTITY; + + Assert.assertEquals((byte) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static byte UMINReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.minUnsigned(res, a[i]); @@ -4242,7 +4408,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte UMINReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4256,20 +4422,15 @@ public class Byte128VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + byte v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (byte) VectorMath.minUnsigned(ra, v); } } @@ -4278,7 +4439,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte UMAXReduce(byte[] a, int idx) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.maxUnsigned(res, a[i]); } @@ -4287,7 +4448,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte UMAXReduceAll(byte[] a) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4299,20 +4460,15 @@ public class Byte128VectorTests extends AbstractVectorTest { static void UMAXReduceByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + byte v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (byte) VectorMath.maxUnsigned(ra, v); } } @@ -4320,8 +4476,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::UMAXReduce, Byte128VectorTests::UMAXReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = UMAX_IDENTITY; + + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static byte UMAXReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.maxUnsigned(res, a[i]); @@ -4331,7 +4510,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte UMAXReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4345,20 +4524,15 @@ public class Byte128VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + byte v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (byte) VectorMath.maxUnsigned(ra, v); } } @@ -4367,7 +4541,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduce(byte[] a, int idx) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4376,7 +4550,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduceAll(byte[] a) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4388,20 +4562,15 @@ public class Byte128VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = (byte) 0; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (byte) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + byte v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4409,8 +4578,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::FIRST_NONZEROReduce, Byte128VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static byte FIRST_NONZEROReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4420,7 +4612,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduceAllMasked(byte[] a, boolean[] mask) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4434,20 +4626,15 @@ public class Byte128VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = (byte) 0; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (byte) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + byte v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4504,7 +4691,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte SUADDReduce(byte[] a, int idx) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4513,7 +4700,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte SUADDReduceAll(byte[] a) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4528,17 +4715,12 @@ public class Byte128VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + byte v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (byte) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4546,8 +4728,31 @@ public class Byte128VectorTests extends AbstractVectorTest { Byte128VectorTests::SUADDReduce, Byte128VectorTests::SUADDReduceAll); } + @Test(dataProvider = "byteSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = SUADD_IDENTITY; + + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static byte SUADDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4557,7 +4762,7 @@ public class Byte128VectorTests extends AbstractVectorTest { } static byte SUADDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4573,17 +4778,12 @@ public class Byte128VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + byte v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (byte) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6390,6 +6590,157 @@ public class Byte128VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Byte128VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandByte128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte128VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorByte128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte128VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorByte128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte128VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotByte128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte128VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqByte128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte128VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotByte128VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Byte128VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongByte128VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "byteCompareOpProvider") static void ltByte128VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { byte[] a = fa.apply(SPECIES.length()); @@ -6700,115 +7051,22 @@ public class Byte128VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsByte128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsByte128VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndByte128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte128VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrByte128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte128VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorByte128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte128VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotByte128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte128VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqByte128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte128VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeByte128VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6913,23 +7171,6 @@ public class Byte128VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongByte128VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Byte256VectorTests.java b/test/jdk/jdk/incubator/vector/Byte256VectorTests.java index be5b3cf6198..0e59db7d05d 100644 --- a/test/jdk/jdk/incubator/vector/Byte256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Byte256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Byte256VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final byte CONST_SHIFT = Byte.SIZE / 2; + // Identity values for reduction operations + private static final byte ADD_IDENTITY = (byte)0; + private static final byte AND_IDENTITY = (byte)-1; + private static final byte FIRST_NONZERO_IDENTITY = (byte)0; + private static final byte MAX_IDENTITY = Byte.MIN_VALUE; + private static final byte MIN_IDENTITY = Byte.MAX_VALUE; + private static final byte MUL_IDENTITY = (byte)1; + private static final byte OR_IDENTITY = (byte)0; + private static final byte SUADD_IDENTITY = (byte)0; + private static final byte UMAX_IDENTITY = (byte)0; // Minimum unsigned value + private static final byte UMIN_IDENTITY = (byte)-1; // Maximum unsigned value + private static final byte XOR_IDENTITY = (byte)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 256); static void assertArraysStrictlyEquals(byte[] r, byte[] a) { @@ -393,6 +405,36 @@ public class Byte256VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { byte apply(byte a, byte b); } @@ -1232,8 +1274,23 @@ public class Byte256VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3566,7 +3623,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte ANDReduce(byte[] a, int idx) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3575,7 +3632,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte ANDReduceAll(byte[] a) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3587,20 +3644,15 @@ public class Byte256VectorTests extends AbstractVectorTest { static void ANDReduceByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = -1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + byte v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3608,8 +3660,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::ANDReduce, Byte256VectorTests::ANDReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = AND_IDENTITY; + + Assert.assertEquals((byte) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id & x), x); + Assert.assertEquals((byte) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static byte ANDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3619,7 +3694,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte ANDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3633,20 +3708,15 @@ public class Byte256VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = -1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + byte v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3655,7 +3725,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte ORReduce(byte[] a, int idx) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3664,7 +3734,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte ORReduceAll(byte[] a) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3679,17 +3749,12 @@ public class Byte256VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + byte v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3697,8 +3762,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::ORReduce, Byte256VectorTests::ORReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = OR_IDENTITY; + + Assert.assertEquals((byte) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id | x), x); + Assert.assertEquals((byte) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static byte ORReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3708,7 +3796,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte ORReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3725,17 +3813,12 @@ public class Byte256VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + byte v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3744,7 +3827,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte XORReduce(byte[] a, int idx) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3753,7 +3836,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte XORReduceAll(byte[] a) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3768,17 +3851,12 @@ public class Byte256VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + byte v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3786,8 +3864,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::XORReduce, Byte256VectorTests::XORReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = XOR_IDENTITY; + + Assert.assertEquals((byte) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id ^ x), x); + Assert.assertEquals((byte) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static byte XORReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3797,7 +3898,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte XORReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3814,17 +3915,12 @@ public class Byte256VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + byte v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3833,7 +3929,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte ADDReduce(byte[] a, int idx) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3842,7 +3938,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte ADDReduceAll(byte[] a) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3857,17 +3953,12 @@ public class Byte256VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + byte v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3875,8 +3966,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::ADDReduce, Byte256VectorTests::ADDReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = ADD_IDENTITY; + + Assert.assertEquals((byte) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id + x), x); + Assert.assertEquals((byte) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static byte ADDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3886,7 +4000,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte ADDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3903,17 +4017,12 @@ public class Byte256VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + byte v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3922,7 +4031,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte MULReduce(byte[] a, int idx) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3931,7 +4040,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte MULReduceAll(byte[] a) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3943,20 +4052,15 @@ public class Byte256VectorTests extends AbstractVectorTest { static void MULReduceByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = 1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + byte v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -3964,8 +4068,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::MULReduce, Byte256VectorTests::MULReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MUL_IDENTITY; + + Assert.assertEquals((byte) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id * x), x); + Assert.assertEquals((byte) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static byte MULReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -3975,7 +4102,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte MULReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -3989,20 +4116,15 @@ public class Byte256VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = 1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + byte v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4011,7 +4133,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte MINReduce(byte[] a, int idx) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) Math.min(res, a[i]); } @@ -4020,7 +4142,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte MINReduceAll(byte[] a) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.min(res, MINReduce(a, i)); } @@ -4032,20 +4154,15 @@ public class Byte256VectorTests extends AbstractVectorTest { static void MINReduceByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + byte v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (byte) Math.min(ra, v); } } @@ -4053,8 +4170,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::MINReduce, Byte256VectorTests::MINReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MIN_IDENTITY; + + Assert.assertEquals((byte) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) Math.min(id, x), x); + Assert.assertEquals((byte) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static byte MINReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) Math.min(res, a[i]); @@ -4064,7 +4204,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte MINReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4078,20 +4218,15 @@ public class Byte256VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + byte v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (byte) Math.min(ra, v); } } @@ -4100,7 +4235,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte MAXReduce(byte[] a, int idx) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) Math.max(res, a[i]); } @@ -4109,7 +4244,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte MAXReduceAll(byte[] a) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.max(res, MAXReduce(a, i)); } @@ -4121,20 +4256,15 @@ public class Byte256VectorTests extends AbstractVectorTest { static void MAXReduceByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + byte v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (byte) Math.max(ra, v); } } @@ -4142,8 +4272,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::MAXReduce, Byte256VectorTests::MAXReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MAX_IDENTITY; + + Assert.assertEquals((byte) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) Math.max(id, x), x); + Assert.assertEquals((byte) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static byte MAXReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) Math.max(res, a[i]); @@ -4153,7 +4306,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte MAXReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4167,20 +4320,15 @@ public class Byte256VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + byte v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (byte) Math.max(ra, v); } } @@ -4189,7 +4337,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte UMINReduce(byte[] a, int idx) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.minUnsigned(res, a[i]); } @@ -4198,7 +4346,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte UMINReduceAll(byte[] a) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4210,20 +4358,15 @@ public class Byte256VectorTests extends AbstractVectorTest { static void UMINReduceByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + byte v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (byte) VectorMath.minUnsigned(ra, v); } } @@ -4231,8 +4374,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::UMINReduce, Byte256VectorTests::UMINReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = UMIN_IDENTITY; + + Assert.assertEquals((byte) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static byte UMINReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.minUnsigned(res, a[i]); @@ -4242,7 +4408,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte UMINReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4256,20 +4422,15 @@ public class Byte256VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + byte v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (byte) VectorMath.minUnsigned(ra, v); } } @@ -4278,7 +4439,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte UMAXReduce(byte[] a, int idx) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.maxUnsigned(res, a[i]); } @@ -4287,7 +4448,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte UMAXReduceAll(byte[] a) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4299,20 +4460,15 @@ public class Byte256VectorTests extends AbstractVectorTest { static void UMAXReduceByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + byte v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (byte) VectorMath.maxUnsigned(ra, v); } } @@ -4320,8 +4476,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::UMAXReduce, Byte256VectorTests::UMAXReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = UMAX_IDENTITY; + + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static byte UMAXReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.maxUnsigned(res, a[i]); @@ -4331,7 +4510,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte UMAXReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4345,20 +4524,15 @@ public class Byte256VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + byte v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (byte) VectorMath.maxUnsigned(ra, v); } } @@ -4367,7 +4541,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduce(byte[] a, int idx) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4376,7 +4550,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduceAll(byte[] a) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4388,20 +4562,15 @@ public class Byte256VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = (byte) 0; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (byte) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + byte v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4409,8 +4578,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::FIRST_NONZEROReduce, Byte256VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static byte FIRST_NONZEROReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4420,7 +4612,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduceAllMasked(byte[] a, boolean[] mask) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4434,20 +4626,15 @@ public class Byte256VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = (byte) 0; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (byte) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + byte v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4504,7 +4691,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte SUADDReduce(byte[] a, int idx) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4513,7 +4700,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte SUADDReduceAll(byte[] a) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4528,17 +4715,12 @@ public class Byte256VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + byte v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (byte) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4546,8 +4728,31 @@ public class Byte256VectorTests extends AbstractVectorTest { Byte256VectorTests::SUADDReduce, Byte256VectorTests::SUADDReduceAll); } + @Test(dataProvider = "byteSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = SUADD_IDENTITY; + + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static byte SUADDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4557,7 +4762,7 @@ public class Byte256VectorTests extends AbstractVectorTest { } static byte SUADDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4573,17 +4778,12 @@ public class Byte256VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + byte v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (byte) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6390,6 +6590,157 @@ public class Byte256VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Byte256VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandByte256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte256VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorByte256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte256VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorByte256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte256VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotByte256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte256VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqByte256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte256VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotByte256VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Byte256VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongByte256VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "byteCompareOpProvider") static void ltByte256VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { byte[] a = fa.apply(SPECIES.length()); @@ -6700,115 +7051,22 @@ public class Byte256VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsByte256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsByte256VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndByte256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte256VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrByte256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte256VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorByte256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte256VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotByte256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte256VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqByte256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte256VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeByte256VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6913,23 +7171,6 @@ public class Byte256VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongByte256VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Byte512VectorTests.java b/test/jdk/jdk/incubator/vector/Byte512VectorTests.java index 0fd68b6f712..5ad3bbdbc05 100644 --- a/test/jdk/jdk/incubator/vector/Byte512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Byte512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Byte512VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final byte CONST_SHIFT = Byte.SIZE / 2; + // Identity values for reduction operations + private static final byte ADD_IDENTITY = (byte)0; + private static final byte AND_IDENTITY = (byte)-1; + private static final byte FIRST_NONZERO_IDENTITY = (byte)0; + private static final byte MAX_IDENTITY = Byte.MIN_VALUE; + private static final byte MIN_IDENTITY = Byte.MAX_VALUE; + private static final byte MUL_IDENTITY = (byte)1; + private static final byte OR_IDENTITY = (byte)0; + private static final byte SUADD_IDENTITY = (byte)0; + private static final byte UMAX_IDENTITY = (byte)0; // Minimum unsigned value + private static final byte UMIN_IDENTITY = (byte)-1; // Maximum unsigned value + private static final byte XOR_IDENTITY = (byte)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 512); static void assertArraysStrictlyEquals(byte[] r, byte[] a) { @@ -393,6 +405,36 @@ public class Byte512VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { byte apply(byte a, byte b); } @@ -1232,8 +1274,23 @@ public class Byte512VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3566,7 +3623,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte ANDReduce(byte[] a, int idx) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3575,7 +3632,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte ANDReduceAll(byte[] a) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3587,20 +3644,15 @@ public class Byte512VectorTests extends AbstractVectorTest { static void ANDReduceByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = -1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + byte v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3608,8 +3660,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::ANDReduce, Byte512VectorTests::ANDReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = AND_IDENTITY; + + Assert.assertEquals((byte) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id & x), x); + Assert.assertEquals((byte) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static byte ANDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3619,7 +3694,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte ANDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3633,20 +3708,15 @@ public class Byte512VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = -1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + byte v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3655,7 +3725,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte ORReduce(byte[] a, int idx) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3664,7 +3734,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte ORReduceAll(byte[] a) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3679,17 +3749,12 @@ public class Byte512VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + byte v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3697,8 +3762,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::ORReduce, Byte512VectorTests::ORReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = OR_IDENTITY; + + Assert.assertEquals((byte) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id | x), x); + Assert.assertEquals((byte) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static byte ORReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3708,7 +3796,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte ORReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3725,17 +3813,12 @@ public class Byte512VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + byte v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3744,7 +3827,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte XORReduce(byte[] a, int idx) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3753,7 +3836,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte XORReduceAll(byte[] a) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3768,17 +3851,12 @@ public class Byte512VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + byte v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3786,8 +3864,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::XORReduce, Byte512VectorTests::XORReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = XOR_IDENTITY; + + Assert.assertEquals((byte) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id ^ x), x); + Assert.assertEquals((byte) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static byte XORReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3797,7 +3898,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte XORReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3814,17 +3915,12 @@ public class Byte512VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + byte v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3833,7 +3929,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte ADDReduce(byte[] a, int idx) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3842,7 +3938,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte ADDReduceAll(byte[] a) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3857,17 +3953,12 @@ public class Byte512VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + byte v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3875,8 +3966,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::ADDReduce, Byte512VectorTests::ADDReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = ADD_IDENTITY; + + Assert.assertEquals((byte) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id + x), x); + Assert.assertEquals((byte) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static byte ADDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3886,7 +4000,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte ADDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3903,17 +4017,12 @@ public class Byte512VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + byte v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3922,7 +4031,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte MULReduce(byte[] a, int idx) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3931,7 +4040,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte MULReduceAll(byte[] a) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3943,20 +4052,15 @@ public class Byte512VectorTests extends AbstractVectorTest { static void MULReduceByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = 1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + byte v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -3964,8 +4068,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::MULReduce, Byte512VectorTests::MULReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MUL_IDENTITY; + + Assert.assertEquals((byte) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id * x), x); + Assert.assertEquals((byte) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static byte MULReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -3975,7 +4102,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte MULReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -3989,20 +4116,15 @@ public class Byte512VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = 1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + byte v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4011,7 +4133,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte MINReduce(byte[] a, int idx) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) Math.min(res, a[i]); } @@ -4020,7 +4142,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte MINReduceAll(byte[] a) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.min(res, MINReduce(a, i)); } @@ -4032,20 +4154,15 @@ public class Byte512VectorTests extends AbstractVectorTest { static void MINReduceByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + byte v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (byte) Math.min(ra, v); } } @@ -4053,8 +4170,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::MINReduce, Byte512VectorTests::MINReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MIN_IDENTITY; + + Assert.assertEquals((byte) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) Math.min(id, x), x); + Assert.assertEquals((byte) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static byte MINReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) Math.min(res, a[i]); @@ -4064,7 +4204,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte MINReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4078,20 +4218,15 @@ public class Byte512VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + byte v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (byte) Math.min(ra, v); } } @@ -4100,7 +4235,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte MAXReduce(byte[] a, int idx) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) Math.max(res, a[i]); } @@ -4109,7 +4244,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte MAXReduceAll(byte[] a) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.max(res, MAXReduce(a, i)); } @@ -4121,20 +4256,15 @@ public class Byte512VectorTests extends AbstractVectorTest { static void MAXReduceByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + byte v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (byte) Math.max(ra, v); } } @@ -4142,8 +4272,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::MAXReduce, Byte512VectorTests::MAXReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MAX_IDENTITY; + + Assert.assertEquals((byte) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) Math.max(id, x), x); + Assert.assertEquals((byte) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static byte MAXReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) Math.max(res, a[i]); @@ -4153,7 +4306,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte MAXReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4167,20 +4320,15 @@ public class Byte512VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + byte v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (byte) Math.max(ra, v); } } @@ -4189,7 +4337,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte UMINReduce(byte[] a, int idx) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.minUnsigned(res, a[i]); } @@ -4198,7 +4346,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte UMINReduceAll(byte[] a) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4210,20 +4358,15 @@ public class Byte512VectorTests extends AbstractVectorTest { static void UMINReduceByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + byte v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (byte) VectorMath.minUnsigned(ra, v); } } @@ -4231,8 +4374,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::UMINReduce, Byte512VectorTests::UMINReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = UMIN_IDENTITY; + + Assert.assertEquals((byte) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static byte UMINReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.minUnsigned(res, a[i]); @@ -4242,7 +4408,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte UMINReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4256,20 +4422,15 @@ public class Byte512VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + byte v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (byte) VectorMath.minUnsigned(ra, v); } } @@ -4278,7 +4439,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte UMAXReduce(byte[] a, int idx) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.maxUnsigned(res, a[i]); } @@ -4287,7 +4448,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte UMAXReduceAll(byte[] a) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4299,20 +4460,15 @@ public class Byte512VectorTests extends AbstractVectorTest { static void UMAXReduceByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + byte v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (byte) VectorMath.maxUnsigned(ra, v); } } @@ -4320,8 +4476,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::UMAXReduce, Byte512VectorTests::UMAXReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = UMAX_IDENTITY; + + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static byte UMAXReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.maxUnsigned(res, a[i]); @@ -4331,7 +4510,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte UMAXReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4345,20 +4524,15 @@ public class Byte512VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + byte v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (byte) VectorMath.maxUnsigned(ra, v); } } @@ -4367,7 +4541,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduce(byte[] a, int idx) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4376,7 +4550,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduceAll(byte[] a) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4388,20 +4562,15 @@ public class Byte512VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = (byte) 0; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (byte) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + byte v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4409,8 +4578,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::FIRST_NONZEROReduce, Byte512VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static byte FIRST_NONZEROReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4420,7 +4612,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduceAllMasked(byte[] a, boolean[] mask) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4434,20 +4626,15 @@ public class Byte512VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = (byte) 0; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (byte) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + byte v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4504,7 +4691,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte SUADDReduce(byte[] a, int idx) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4513,7 +4700,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte SUADDReduceAll(byte[] a) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4528,17 +4715,12 @@ public class Byte512VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + byte v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (byte) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4546,8 +4728,31 @@ public class Byte512VectorTests extends AbstractVectorTest { Byte512VectorTests::SUADDReduce, Byte512VectorTests::SUADDReduceAll); } + @Test(dataProvider = "byteSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = SUADD_IDENTITY; + + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static byte SUADDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4557,7 +4762,7 @@ public class Byte512VectorTests extends AbstractVectorTest { } static byte SUADDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4573,17 +4778,12 @@ public class Byte512VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + byte v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (byte) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6390,6 +6590,157 @@ public class Byte512VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Byte512VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandByte512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte512VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorByte512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte512VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorByte512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte512VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotByte512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte512VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqByte512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte512VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotByte512VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Byte512VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongByte512VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "byteCompareOpProvider") static void ltByte512VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { byte[] a = fa.apply(SPECIES.length()); @@ -6700,115 +7051,22 @@ public class Byte512VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsByte512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsByte512VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndByte512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte512VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrByte512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte512VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorByte512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte512VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotByte512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte512VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqByte512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte512VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeByte512VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6913,23 +7171,6 @@ public class Byte512VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongByte512VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Byte64VectorTests.java b/test/jdk/jdk/incubator/vector/Byte64VectorTests.java index 112b2e56b6f..e28fb2b2001 100644 --- a/test/jdk/jdk/incubator/vector/Byte64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Byte64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Byte64VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final byte CONST_SHIFT = Byte.SIZE / 2; + // Identity values for reduction operations + private static final byte ADD_IDENTITY = (byte)0; + private static final byte AND_IDENTITY = (byte)-1; + private static final byte FIRST_NONZERO_IDENTITY = (byte)0; + private static final byte MAX_IDENTITY = Byte.MIN_VALUE; + private static final byte MIN_IDENTITY = Byte.MAX_VALUE; + private static final byte MUL_IDENTITY = (byte)1; + private static final byte OR_IDENTITY = (byte)0; + private static final byte SUADD_IDENTITY = (byte)0; + private static final byte UMAX_IDENTITY = (byte)0; // Minimum unsigned value + private static final byte UMIN_IDENTITY = (byte)-1; // Maximum unsigned value + private static final byte XOR_IDENTITY = (byte)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 64); static void assertArraysStrictlyEquals(byte[] r, byte[] a) { @@ -393,6 +405,36 @@ public class Byte64VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { byte apply(byte a, byte b); } @@ -1232,8 +1274,23 @@ public class Byte64VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3566,7 +3623,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte ANDReduce(byte[] a, int idx) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3575,7 +3632,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte ANDReduceAll(byte[] a) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3587,20 +3644,15 @@ public class Byte64VectorTests extends AbstractVectorTest { static void ANDReduceByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = -1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + byte v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3608,8 +3660,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::ANDReduce, Byte64VectorTests::ANDReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = AND_IDENTITY; + + Assert.assertEquals((byte) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id & x), x); + Assert.assertEquals((byte) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static byte ANDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3619,7 +3694,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte ANDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3633,20 +3708,15 @@ public class Byte64VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = -1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + byte v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3655,7 +3725,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte ORReduce(byte[] a, int idx) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3664,7 +3734,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte ORReduceAll(byte[] a) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3679,17 +3749,12 @@ public class Byte64VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + byte v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3697,8 +3762,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::ORReduce, Byte64VectorTests::ORReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = OR_IDENTITY; + + Assert.assertEquals((byte) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id | x), x); + Assert.assertEquals((byte) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static byte ORReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3708,7 +3796,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte ORReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3725,17 +3813,12 @@ public class Byte64VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + byte v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3744,7 +3827,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte XORReduce(byte[] a, int idx) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3753,7 +3836,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte XORReduceAll(byte[] a) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3768,17 +3851,12 @@ public class Byte64VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + byte v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3786,8 +3864,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::XORReduce, Byte64VectorTests::XORReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = XOR_IDENTITY; + + Assert.assertEquals((byte) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id ^ x), x); + Assert.assertEquals((byte) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static byte XORReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3797,7 +3898,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte XORReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3814,17 +3915,12 @@ public class Byte64VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + byte v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3833,7 +3929,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte ADDReduce(byte[] a, int idx) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3842,7 +3938,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte ADDReduceAll(byte[] a) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3857,17 +3953,12 @@ public class Byte64VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + byte v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3875,8 +3966,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::ADDReduce, Byte64VectorTests::ADDReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = ADD_IDENTITY; + + Assert.assertEquals((byte) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id + x), x); + Assert.assertEquals((byte) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static byte ADDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3886,7 +4000,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte ADDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3903,17 +4017,12 @@ public class Byte64VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + byte v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3922,7 +4031,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte MULReduce(byte[] a, int idx) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3931,7 +4040,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte MULReduceAll(byte[] a) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3943,20 +4052,15 @@ public class Byte64VectorTests extends AbstractVectorTest { static void MULReduceByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = 1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + byte v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -3964,8 +4068,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::MULReduce, Byte64VectorTests::MULReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MUL_IDENTITY; + + Assert.assertEquals((byte) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id * x), x); + Assert.assertEquals((byte) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static byte MULReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -3975,7 +4102,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte MULReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -3989,20 +4116,15 @@ public class Byte64VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = 1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + byte v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4011,7 +4133,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte MINReduce(byte[] a, int idx) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) Math.min(res, a[i]); } @@ -4020,7 +4142,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte MINReduceAll(byte[] a) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.min(res, MINReduce(a, i)); } @@ -4032,20 +4154,15 @@ public class Byte64VectorTests extends AbstractVectorTest { static void MINReduceByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + byte v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (byte) Math.min(ra, v); } } @@ -4053,8 +4170,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::MINReduce, Byte64VectorTests::MINReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MIN_IDENTITY; + + Assert.assertEquals((byte) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) Math.min(id, x), x); + Assert.assertEquals((byte) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static byte MINReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) Math.min(res, a[i]); @@ -4064,7 +4204,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte MINReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4078,20 +4218,15 @@ public class Byte64VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + byte v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (byte) Math.min(ra, v); } } @@ -4100,7 +4235,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte MAXReduce(byte[] a, int idx) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) Math.max(res, a[i]); } @@ -4109,7 +4244,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte MAXReduceAll(byte[] a) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.max(res, MAXReduce(a, i)); } @@ -4121,20 +4256,15 @@ public class Byte64VectorTests extends AbstractVectorTest { static void MAXReduceByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + byte v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (byte) Math.max(ra, v); } } @@ -4142,8 +4272,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::MAXReduce, Byte64VectorTests::MAXReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MAX_IDENTITY; + + Assert.assertEquals((byte) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) Math.max(id, x), x); + Assert.assertEquals((byte) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static byte MAXReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) Math.max(res, a[i]); @@ -4153,7 +4306,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte MAXReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4167,20 +4320,15 @@ public class Byte64VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + byte v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (byte) Math.max(ra, v); } } @@ -4189,7 +4337,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte UMINReduce(byte[] a, int idx) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.minUnsigned(res, a[i]); } @@ -4198,7 +4346,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte UMINReduceAll(byte[] a) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4210,20 +4358,15 @@ public class Byte64VectorTests extends AbstractVectorTest { static void UMINReduceByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + byte v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (byte) VectorMath.minUnsigned(ra, v); } } @@ -4231,8 +4374,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::UMINReduce, Byte64VectorTests::UMINReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = UMIN_IDENTITY; + + Assert.assertEquals((byte) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static byte UMINReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.minUnsigned(res, a[i]); @@ -4242,7 +4408,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte UMINReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4256,20 +4422,15 @@ public class Byte64VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + byte v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (byte) VectorMath.minUnsigned(ra, v); } } @@ -4278,7 +4439,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte UMAXReduce(byte[] a, int idx) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.maxUnsigned(res, a[i]); } @@ -4287,7 +4448,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte UMAXReduceAll(byte[] a) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4299,20 +4460,15 @@ public class Byte64VectorTests extends AbstractVectorTest { static void UMAXReduceByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + byte v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (byte) VectorMath.maxUnsigned(ra, v); } } @@ -4320,8 +4476,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::UMAXReduce, Byte64VectorTests::UMAXReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = UMAX_IDENTITY; + + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static byte UMAXReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.maxUnsigned(res, a[i]); @@ -4331,7 +4510,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte UMAXReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4345,20 +4524,15 @@ public class Byte64VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + byte v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (byte) VectorMath.maxUnsigned(ra, v); } } @@ -4367,7 +4541,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduce(byte[] a, int idx) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4376,7 +4550,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduceAll(byte[] a) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4388,20 +4562,15 @@ public class Byte64VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = (byte) 0; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (byte) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + byte v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4409,8 +4578,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::FIRST_NONZEROReduce, Byte64VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static byte FIRST_NONZEROReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4420,7 +4612,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduceAllMasked(byte[] a, boolean[] mask) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4434,20 +4626,15 @@ public class Byte64VectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = (byte) 0; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (byte) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + byte v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4504,7 +4691,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte SUADDReduce(byte[] a, int idx) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4513,7 +4700,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte SUADDReduceAll(byte[] a) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4528,17 +4715,12 @@ public class Byte64VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + byte v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (byte) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4546,8 +4728,31 @@ public class Byte64VectorTests extends AbstractVectorTest { Byte64VectorTests::SUADDReduce, Byte64VectorTests::SUADDReduceAll); } + @Test(dataProvider = "byteSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = SUADD_IDENTITY; + + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static byte SUADDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4557,7 +4762,7 @@ public class Byte64VectorTests extends AbstractVectorTest { } static byte SUADDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4573,17 +4778,12 @@ public class Byte64VectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + byte v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (byte) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6390,6 +6590,157 @@ public class Byte64VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Byte64VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandByte64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte64VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorByte64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte64VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorByte64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte64VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotByte64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte64VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqByte64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Byte64VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotByte64VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Byte64VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongByte64VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "byteCompareOpProvider") static void ltByte64VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { byte[] a = fa.apply(SPECIES.length()); @@ -6700,115 +7051,22 @@ public class Byte64VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsByte64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsByte64VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndByte64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte64VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrByte64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte64VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorByte64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte64VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotByte64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte64VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqByte64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Byte64VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeByte64VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6913,23 +7171,6 @@ public class Byte64VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongByte64VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java b/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java index 435cacc013e..b6932785b55 100644 --- a/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -71,6 +71,19 @@ public class ByteMaxVectorTests extends AbstractVectorTest { private static final byte CONST_SHIFT = Byte.SIZE / 2; + // Identity values for reduction operations + private static final byte ADD_IDENTITY = (byte)0; + private static final byte AND_IDENTITY = (byte)-1; + private static final byte FIRST_NONZERO_IDENTITY = (byte)0; + private static final byte MAX_IDENTITY = Byte.MIN_VALUE; + private static final byte MIN_IDENTITY = Byte.MAX_VALUE; + private static final byte MUL_IDENTITY = (byte)1; + private static final byte OR_IDENTITY = (byte)0; + private static final byte SUADD_IDENTITY = (byte)0; + private static final byte UMAX_IDENTITY = (byte)0; // Minimum unsigned value + private static final byte UMIN_IDENTITY = (byte)-1; // Maximum unsigned value + private static final byte XOR_IDENTITY = (byte)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / Max); static void assertArraysStrictlyEquals(byte[] r, byte[] a) { @@ -398,6 +411,36 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { byte apply(byte a, byte b); } @@ -1237,8 +1280,23 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3571,7 +3629,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte ANDReduce(byte[] a, int idx) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3580,7 +3638,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte ANDReduceAll(byte[] a) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3592,20 +3650,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { static void ANDReduceByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = -1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + byte v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3613,8 +3666,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::ANDReduce, ByteMaxVectorTests::ANDReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = AND_IDENTITY; + + Assert.assertEquals((byte) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id & x), x); + Assert.assertEquals((byte) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static byte ANDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3624,7 +3700,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte ANDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = -1; + byte res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3638,20 +3714,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = -1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + byte v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3660,7 +3731,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte ORReduce(byte[] a, int idx) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3669,7 +3740,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte ORReduceAll(byte[] a) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3684,17 +3755,12 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + byte v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3702,8 +3768,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::ORReduce, ByteMaxVectorTests::ORReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = OR_IDENTITY; + + Assert.assertEquals((byte) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id | x), x); + Assert.assertEquals((byte) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static byte ORReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3713,7 +3802,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte ORReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3730,17 +3819,12 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + byte v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3749,7 +3833,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte XORReduce(byte[] a, int idx) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3758,7 +3842,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte XORReduceAll(byte[] a) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3773,17 +3857,12 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + byte v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3791,8 +3870,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::XORReduce, ByteMaxVectorTests::XORReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = XOR_IDENTITY; + + Assert.assertEquals((byte) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id ^ x), x); + Assert.assertEquals((byte) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static byte XORReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3802,7 +3904,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte XORReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3819,17 +3921,12 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + byte v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3838,7 +3935,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte ADDReduce(byte[] a, int idx) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3847,7 +3944,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte ADDReduceAll(byte[] a) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3862,17 +3959,12 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + byte v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3880,8 +3972,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::ADDReduce, ByteMaxVectorTests::ADDReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = ADD_IDENTITY; + + Assert.assertEquals((byte) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id + x), x); + Assert.assertEquals((byte) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static byte ADDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3891,7 +4006,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte ADDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3908,17 +4023,12 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + byte v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3927,7 +4037,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte MULReduce(byte[] a, int idx) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3936,7 +4046,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte MULReduceAll(byte[] a) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3948,20 +4058,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { static void MULReduceByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = 1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + byte v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -3969,8 +4074,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::MULReduce, ByteMaxVectorTests::MULReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MUL_IDENTITY; + + Assert.assertEquals((byte) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) (id * x), x); + Assert.assertEquals((byte) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static byte MULReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -3980,7 +4108,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte MULReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 1; + byte res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -3994,20 +4122,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = 1; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + byte v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4016,7 +4139,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte MINReduce(byte[] a, int idx) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) Math.min(res, a[i]); } @@ -4025,7 +4148,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte MINReduceAll(byte[] a) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.min(res, MINReduce(a, i)); } @@ -4037,20 +4160,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { static void MINReduceByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + byte v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (byte) Math.min(ra, v); } } @@ -4058,8 +4176,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::MINReduce, ByteMaxVectorTests::MINReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MIN_IDENTITY; + + Assert.assertEquals((byte) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) Math.min(id, x), x); + Assert.assertEquals((byte) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static byte MINReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) Math.min(res, a[i]); @@ -4069,7 +4210,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte MINReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4083,20 +4224,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + byte v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (byte) Math.min(ra, v); } } @@ -4105,7 +4241,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte MAXReduce(byte[] a, int idx) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) Math.max(res, a[i]); } @@ -4114,7 +4250,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte MAXReduceAll(byte[] a) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.max(res, MAXReduce(a, i)); } @@ -4126,20 +4262,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { static void MAXReduceByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + byte v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (byte) Math.max(ra, v); } } @@ -4147,8 +4278,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::MAXReduce, ByteMaxVectorTests::MAXReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = MAX_IDENTITY; + + Assert.assertEquals((byte) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) Math.max(id, x), x); + Assert.assertEquals((byte) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static byte MAXReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) Math.max(res, a[i]); @@ -4158,7 +4312,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte MAXReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4172,20 +4326,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + byte v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (byte) Math.max(ra, v); } } @@ -4194,7 +4343,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte UMINReduce(byte[] a, int idx) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.minUnsigned(res, a[i]); } @@ -4203,7 +4352,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte UMINReduceAll(byte[] a) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4215,20 +4364,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { static void UMINReduceByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + byte v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (byte) VectorMath.minUnsigned(ra, v); } } @@ -4236,8 +4380,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::UMINReduce, ByteMaxVectorTests::UMINReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = UMIN_IDENTITY; + + Assert.assertEquals((byte) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static byte UMINReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.minUnsigned(res, a[i]); @@ -4247,7 +4414,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte UMINReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MAX_VALUE; + byte res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4261,20 +4428,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MAX_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + byte v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (byte) VectorMath.minUnsigned(ra, v); } } @@ -4283,7 +4445,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte UMAXReduce(byte[] a, int idx) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.maxUnsigned(res, a[i]); } @@ -4292,7 +4454,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte UMAXReduceAll(byte[] a) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4304,20 +4466,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { static void UMAXReduceByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + byte v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (byte) VectorMath.maxUnsigned(ra, v); } } @@ -4325,8 +4482,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::UMAXReduce, ByteMaxVectorTests::UMAXReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = UMAX_IDENTITY; + + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static byte UMAXReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.maxUnsigned(res, a[i]); @@ -4336,7 +4516,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte UMAXReduceAllMasked(byte[] a, boolean[] mask) { - byte res = Byte.MIN_VALUE; + byte res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4350,20 +4530,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = Byte.MIN_VALUE; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Byte.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + byte v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (byte) VectorMath.maxUnsigned(ra, v); } } @@ -4372,7 +4547,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduce(byte[] a, int idx) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4381,7 +4556,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduceAll(byte[] a) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4393,20 +4568,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = fr.apply(SPECIES.length()); - byte ra = (byte) 0; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (byte) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + byte v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4414,8 +4584,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::FIRST_NONZEROReduce, ByteMaxVectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "byteUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static byte FIRST_NONZEROReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4425,7 +4618,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte FIRST_NONZEROReduceAllMasked(byte[] a, boolean[] mask) { - byte res = (byte) 0; + byte res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4439,20 +4632,15 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - byte ra = (byte) 0; + byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (byte) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + byte v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4509,7 +4697,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte SUADDReduce(byte[] a, int idx) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (byte) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4518,7 +4706,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte SUADDReduceAll(byte[] a) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4533,17 +4721,12 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + byte v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (byte) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4551,8 +4734,31 @@ public class ByteMaxVectorTests extends AbstractVectorTest { ByteMaxVectorTests::SUADDReduce, ByteMaxVectorTests::SUADDReduceAll); } + @Test(dataProvider = "byteSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + byte[] a = fa.apply(SPECIES.length()); + byte id = SUADD_IDENTITY; + + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + byte x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((byte) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static byte SUADDReduceMasked(byte[] a, int idx, boolean[] mask) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (byte) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4562,7 +4768,7 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } static byte SUADDReduceAllMasked(byte[] a, boolean[] mask) { - byte res = 0; + byte res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (byte) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4578,17 +4784,12 @@ public class ByteMaxVectorTests extends AbstractVectorTest { byte ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ByteVector av = ByteVector.fromArray(SPECIES, a, i); - ra = (byte) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + byte v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (byte) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6395,6 +6596,157 @@ public class ByteMaxVectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, ByteMaxVectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandByteMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, ByteMaxVectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorByteMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, ByteMaxVectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorByteMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, ByteMaxVectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotByteMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, ByteMaxVectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqByteMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, ByteMaxVectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotByteMaxVectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, ByteMaxVectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongByteMaxVectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "byteCompareOpProvider") static void ltByteMaxVectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { byte[] a = fa.apply(SPECIES.length()); @@ -6705,115 +7057,22 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsByteMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsByteMaxVectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndByteMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, ByteMaxVectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrByteMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, ByteMaxVectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorByteMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, ByteMaxVectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotByteMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, ByteMaxVectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqByteMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, ByteMaxVectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeByteMaxVectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6918,7 +7177,6 @@ public class ByteMaxVectorTests extends AbstractVectorTest { } } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Double128VectorTests.java b/test/jdk/jdk/incubator/vector/Double128VectorTests.java index f15ce88ddb8..1d4cadd2158 100644 --- a/test/jdk/jdk/incubator/vector/Double128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Double128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -62,6 +62,12 @@ public class Double128VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); + // Identity values for reduction operations + private static final double ADD_IDENTITY = (double)0; + private static final double FIRST_NONZERO_IDENTITY = (double)0; + private static final double MAX_IDENTITY = Double.NEGATIVE_INFINITY; + private static final double MIN_IDENTITY = Double.POSITIVE_INFINITY; + private static final double MUL_IDENTITY = (double)1; // for floating point addition reduction ops that may introduce rounding errors private static final double RELATIVE_ROUNDING_ERROR_FACTOR_ADD = (double)10.0; @@ -411,6 +417,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { double apply(double a, double b); } @@ -1291,8 +1327,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -2339,7 +2390,7 @@ relativeError)); } static double ADDReduce(double[] a, int idx) { - double res = 0; + double res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -2348,7 +2399,7 @@ relativeError)); } static double ADDReduceAll(double[] a) { - double res = 0; + double res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -2363,17 +2414,12 @@ relativeError)); double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + double v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -2381,8 +2427,31 @@ relativeError)); Double128VectorTests::ADDReduce, Double128VectorTests::ADDReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_ADD); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = ADD_IDENTITY; + + Assert.assertEquals((double) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) (id + x), x); + Assert.assertEquals((double) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static double ADDReduceMasked(double[] a, int idx, boolean[] mask) { - double res = 0; + double res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -2392,7 +2461,7 @@ relativeError)); } static double ADDReduceAllMasked(double[] a, boolean[] mask) { - double res = 0; + double res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -2409,17 +2478,12 @@ relativeError)); double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + double v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -2428,7 +2492,7 @@ relativeError)); } static double MULReduce(double[] a, int idx) { - double res = 1; + double res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -2437,7 +2501,7 @@ relativeError)); } static double MULReduceAll(double[] a) { - double res = 1; + double res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -2449,20 +2513,15 @@ relativeError)); static void MULReduceDouble128VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = 1; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + double v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -2470,8 +2529,31 @@ relativeError)); Double128VectorTests::MULReduce, Double128VectorTests::MULReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_MUL); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MUL_IDENTITY; + + Assert.assertEquals((double) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) (id * x), x); + Assert.assertEquals((double) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static double MULReduceMasked(double[] a, int idx, boolean[] mask) { - double res = 1; + double res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -2481,7 +2563,7 @@ relativeError)); } static double MULReduceAllMasked(double[] a, boolean[] mask) { - double res = 1; + double res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -2495,20 +2577,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = 1; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + double v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -2517,7 +2594,7 @@ relativeError)); } static double MINReduce(double[] a, int idx) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (double) Math.min(res, a[i]); } @@ -2526,7 +2603,7 @@ relativeError)); } static double MINReduceAll(double[] a) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.min(res, MINReduce(a, i)); } @@ -2538,20 +2615,15 @@ relativeError)); static void MINReduceDouble128VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = Double.POSITIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + double v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (double) Math.min(ra, v); } } @@ -2559,8 +2631,31 @@ relativeError)); Double128VectorTests::MINReduce, Double128VectorTests::MINReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MIN_IDENTITY; + + Assert.assertEquals((double) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) Math.min(id, x), x); + Assert.assertEquals((double) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static double MINReduceMasked(double[] a, int idx, boolean[] mask) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (double) Math.min(res, a[i]); @@ -2570,7 +2665,7 @@ relativeError)); } static double MINReduceAllMasked(double[] a, boolean[] mask) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -2584,20 +2679,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = Double.POSITIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + double v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (double) Math.min(ra, v); } } @@ -2606,7 +2696,7 @@ relativeError)); } static double MAXReduce(double[] a, int idx) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (double) Math.max(res, a[i]); } @@ -2615,7 +2705,7 @@ relativeError)); } static double MAXReduceAll(double[] a) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.max(res, MAXReduce(a, i)); } @@ -2627,20 +2717,15 @@ relativeError)); static void MAXReduceDouble128VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = Double.NEGATIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + double v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (double) Math.max(ra, v); } } @@ -2648,8 +2733,31 @@ relativeError)); Double128VectorTests::MAXReduce, Double128VectorTests::MAXReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MAX_IDENTITY; + + Assert.assertEquals((double) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) Math.max(id, x), x); + Assert.assertEquals((double) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static double MAXReduceMasked(double[] a, int idx, boolean[] mask) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (double) Math.max(res, a[i]); @@ -2659,7 +2767,7 @@ relativeError)); } static double MAXReduceAllMasked(double[] a, boolean[] mask) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -2673,20 +2781,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = Double.NEGATIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + double v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (double) Math.max(ra, v); } } @@ -2695,7 +2798,7 @@ relativeError)); } static double FIRST_NONZEROReduce(double[] a, int idx) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -2704,7 +2807,7 @@ relativeError)); } static double FIRST_NONZEROReduceAll(double[] a) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -2716,20 +2819,15 @@ relativeError)); static void FIRST_NONZEROReduceDouble128VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = (double) 0; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (double) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + double v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -2737,8 +2835,31 @@ relativeError)); Double128VectorTests::FIRST_NONZEROReduce, Double128VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static double FIRST_NONZEROReduceMasked(double[] a, int idx, boolean[] mask) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -2748,7 +2869,7 @@ relativeError)); } static double FIRST_NONZEROReduceAllMasked(double[] a, boolean[] mask) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -2762,20 +2883,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = (double) 0; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (double) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + double v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4806,6 +4922,157 @@ relativeError)); assertArraysEquals(r, a, mask, Double128VectorTests::SQRT); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandDouble128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double128VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorDouble128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double128VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorDouble128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double128VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotDouble128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double128VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqDouble128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double128VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotDouble128VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Double128VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongDouble128VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "doubleCompareOpProvider") static void ltDouble128VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { double[] a = fa.apply(SPECIES.length()); @@ -5095,115 +5362,22 @@ relativeError)); } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsDouble128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsDouble128VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndDouble128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double128VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrDouble128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double128VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorDouble128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double128VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotDouble128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double128VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqDouble128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double128VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeDouble128VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -5308,23 +5482,6 @@ relativeError)); } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongDouble128VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Double256VectorTests.java b/test/jdk/jdk/incubator/vector/Double256VectorTests.java index e6c3662e0ad..b5acfe0ef34 100644 --- a/test/jdk/jdk/incubator/vector/Double256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Double256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -62,6 +62,12 @@ public class Double256VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); + // Identity values for reduction operations + private static final double ADD_IDENTITY = (double)0; + private static final double FIRST_NONZERO_IDENTITY = (double)0; + private static final double MAX_IDENTITY = Double.NEGATIVE_INFINITY; + private static final double MIN_IDENTITY = Double.POSITIVE_INFINITY; + private static final double MUL_IDENTITY = (double)1; // for floating point addition reduction ops that may introduce rounding errors private static final double RELATIVE_ROUNDING_ERROR_FACTOR_ADD = (double)10.0; @@ -411,6 +417,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { double apply(double a, double b); } @@ -1291,8 +1327,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -2339,7 +2390,7 @@ relativeError)); } static double ADDReduce(double[] a, int idx) { - double res = 0; + double res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -2348,7 +2399,7 @@ relativeError)); } static double ADDReduceAll(double[] a) { - double res = 0; + double res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -2363,17 +2414,12 @@ relativeError)); double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + double v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -2381,8 +2427,31 @@ relativeError)); Double256VectorTests::ADDReduce, Double256VectorTests::ADDReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_ADD); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = ADD_IDENTITY; + + Assert.assertEquals((double) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) (id + x), x); + Assert.assertEquals((double) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static double ADDReduceMasked(double[] a, int idx, boolean[] mask) { - double res = 0; + double res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -2392,7 +2461,7 @@ relativeError)); } static double ADDReduceAllMasked(double[] a, boolean[] mask) { - double res = 0; + double res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -2409,17 +2478,12 @@ relativeError)); double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + double v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -2428,7 +2492,7 @@ relativeError)); } static double MULReduce(double[] a, int idx) { - double res = 1; + double res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -2437,7 +2501,7 @@ relativeError)); } static double MULReduceAll(double[] a) { - double res = 1; + double res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -2449,20 +2513,15 @@ relativeError)); static void MULReduceDouble256VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = 1; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + double v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -2470,8 +2529,31 @@ relativeError)); Double256VectorTests::MULReduce, Double256VectorTests::MULReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_MUL); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MUL_IDENTITY; + + Assert.assertEquals((double) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) (id * x), x); + Assert.assertEquals((double) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static double MULReduceMasked(double[] a, int idx, boolean[] mask) { - double res = 1; + double res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -2481,7 +2563,7 @@ relativeError)); } static double MULReduceAllMasked(double[] a, boolean[] mask) { - double res = 1; + double res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -2495,20 +2577,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = 1; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + double v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -2517,7 +2594,7 @@ relativeError)); } static double MINReduce(double[] a, int idx) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (double) Math.min(res, a[i]); } @@ -2526,7 +2603,7 @@ relativeError)); } static double MINReduceAll(double[] a) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.min(res, MINReduce(a, i)); } @@ -2538,20 +2615,15 @@ relativeError)); static void MINReduceDouble256VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = Double.POSITIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + double v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (double) Math.min(ra, v); } } @@ -2559,8 +2631,31 @@ relativeError)); Double256VectorTests::MINReduce, Double256VectorTests::MINReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MIN_IDENTITY; + + Assert.assertEquals((double) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) Math.min(id, x), x); + Assert.assertEquals((double) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static double MINReduceMasked(double[] a, int idx, boolean[] mask) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (double) Math.min(res, a[i]); @@ -2570,7 +2665,7 @@ relativeError)); } static double MINReduceAllMasked(double[] a, boolean[] mask) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -2584,20 +2679,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = Double.POSITIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + double v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (double) Math.min(ra, v); } } @@ -2606,7 +2696,7 @@ relativeError)); } static double MAXReduce(double[] a, int idx) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (double) Math.max(res, a[i]); } @@ -2615,7 +2705,7 @@ relativeError)); } static double MAXReduceAll(double[] a) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.max(res, MAXReduce(a, i)); } @@ -2627,20 +2717,15 @@ relativeError)); static void MAXReduceDouble256VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = Double.NEGATIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + double v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (double) Math.max(ra, v); } } @@ -2648,8 +2733,31 @@ relativeError)); Double256VectorTests::MAXReduce, Double256VectorTests::MAXReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MAX_IDENTITY; + + Assert.assertEquals((double) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) Math.max(id, x), x); + Assert.assertEquals((double) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static double MAXReduceMasked(double[] a, int idx, boolean[] mask) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (double) Math.max(res, a[i]); @@ -2659,7 +2767,7 @@ relativeError)); } static double MAXReduceAllMasked(double[] a, boolean[] mask) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -2673,20 +2781,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = Double.NEGATIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + double v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (double) Math.max(ra, v); } } @@ -2695,7 +2798,7 @@ relativeError)); } static double FIRST_NONZEROReduce(double[] a, int idx) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -2704,7 +2807,7 @@ relativeError)); } static double FIRST_NONZEROReduceAll(double[] a) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -2716,20 +2819,15 @@ relativeError)); static void FIRST_NONZEROReduceDouble256VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = (double) 0; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (double) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + double v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -2737,8 +2835,31 @@ relativeError)); Double256VectorTests::FIRST_NONZEROReduce, Double256VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static double FIRST_NONZEROReduceMasked(double[] a, int idx, boolean[] mask) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -2748,7 +2869,7 @@ relativeError)); } static double FIRST_NONZEROReduceAllMasked(double[] a, boolean[] mask) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -2762,20 +2883,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = (double) 0; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (double) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + double v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4806,6 +4922,157 @@ relativeError)); assertArraysEquals(r, a, mask, Double256VectorTests::SQRT); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandDouble256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double256VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorDouble256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double256VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorDouble256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double256VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotDouble256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double256VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqDouble256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double256VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotDouble256VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Double256VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongDouble256VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "doubleCompareOpProvider") static void ltDouble256VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { double[] a = fa.apply(SPECIES.length()); @@ -5095,115 +5362,22 @@ relativeError)); } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsDouble256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsDouble256VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndDouble256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double256VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrDouble256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double256VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorDouble256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double256VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotDouble256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double256VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqDouble256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double256VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeDouble256VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -5308,23 +5482,6 @@ relativeError)); } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongDouble256VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Double512VectorTests.java b/test/jdk/jdk/incubator/vector/Double512VectorTests.java index 7c37c9878e8..3f85d0e52a6 100644 --- a/test/jdk/jdk/incubator/vector/Double512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Double512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -62,6 +62,12 @@ public class Double512VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); + // Identity values for reduction operations + private static final double ADD_IDENTITY = (double)0; + private static final double FIRST_NONZERO_IDENTITY = (double)0; + private static final double MAX_IDENTITY = Double.NEGATIVE_INFINITY; + private static final double MIN_IDENTITY = Double.POSITIVE_INFINITY; + private static final double MUL_IDENTITY = (double)1; // for floating point addition reduction ops that may introduce rounding errors private static final double RELATIVE_ROUNDING_ERROR_FACTOR_ADD = (double)10.0; @@ -411,6 +417,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { double apply(double a, double b); } @@ -1291,8 +1327,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -2339,7 +2390,7 @@ relativeError)); } static double ADDReduce(double[] a, int idx) { - double res = 0; + double res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -2348,7 +2399,7 @@ relativeError)); } static double ADDReduceAll(double[] a) { - double res = 0; + double res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -2363,17 +2414,12 @@ relativeError)); double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + double v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -2381,8 +2427,31 @@ relativeError)); Double512VectorTests::ADDReduce, Double512VectorTests::ADDReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_ADD); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = ADD_IDENTITY; + + Assert.assertEquals((double) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) (id + x), x); + Assert.assertEquals((double) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static double ADDReduceMasked(double[] a, int idx, boolean[] mask) { - double res = 0; + double res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -2392,7 +2461,7 @@ relativeError)); } static double ADDReduceAllMasked(double[] a, boolean[] mask) { - double res = 0; + double res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -2409,17 +2478,12 @@ relativeError)); double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + double v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -2428,7 +2492,7 @@ relativeError)); } static double MULReduce(double[] a, int idx) { - double res = 1; + double res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -2437,7 +2501,7 @@ relativeError)); } static double MULReduceAll(double[] a) { - double res = 1; + double res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -2449,20 +2513,15 @@ relativeError)); static void MULReduceDouble512VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = 1; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + double v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -2470,8 +2529,31 @@ relativeError)); Double512VectorTests::MULReduce, Double512VectorTests::MULReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_MUL); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MUL_IDENTITY; + + Assert.assertEquals((double) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) (id * x), x); + Assert.assertEquals((double) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static double MULReduceMasked(double[] a, int idx, boolean[] mask) { - double res = 1; + double res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -2481,7 +2563,7 @@ relativeError)); } static double MULReduceAllMasked(double[] a, boolean[] mask) { - double res = 1; + double res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -2495,20 +2577,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = 1; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + double v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -2517,7 +2594,7 @@ relativeError)); } static double MINReduce(double[] a, int idx) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (double) Math.min(res, a[i]); } @@ -2526,7 +2603,7 @@ relativeError)); } static double MINReduceAll(double[] a) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.min(res, MINReduce(a, i)); } @@ -2538,20 +2615,15 @@ relativeError)); static void MINReduceDouble512VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = Double.POSITIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + double v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (double) Math.min(ra, v); } } @@ -2559,8 +2631,31 @@ relativeError)); Double512VectorTests::MINReduce, Double512VectorTests::MINReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MIN_IDENTITY; + + Assert.assertEquals((double) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) Math.min(id, x), x); + Assert.assertEquals((double) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static double MINReduceMasked(double[] a, int idx, boolean[] mask) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (double) Math.min(res, a[i]); @@ -2570,7 +2665,7 @@ relativeError)); } static double MINReduceAllMasked(double[] a, boolean[] mask) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -2584,20 +2679,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = Double.POSITIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + double v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (double) Math.min(ra, v); } } @@ -2606,7 +2696,7 @@ relativeError)); } static double MAXReduce(double[] a, int idx) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (double) Math.max(res, a[i]); } @@ -2615,7 +2705,7 @@ relativeError)); } static double MAXReduceAll(double[] a) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.max(res, MAXReduce(a, i)); } @@ -2627,20 +2717,15 @@ relativeError)); static void MAXReduceDouble512VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = Double.NEGATIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + double v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (double) Math.max(ra, v); } } @@ -2648,8 +2733,31 @@ relativeError)); Double512VectorTests::MAXReduce, Double512VectorTests::MAXReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MAX_IDENTITY; + + Assert.assertEquals((double) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) Math.max(id, x), x); + Assert.assertEquals((double) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static double MAXReduceMasked(double[] a, int idx, boolean[] mask) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (double) Math.max(res, a[i]); @@ -2659,7 +2767,7 @@ relativeError)); } static double MAXReduceAllMasked(double[] a, boolean[] mask) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -2673,20 +2781,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = Double.NEGATIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + double v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (double) Math.max(ra, v); } } @@ -2695,7 +2798,7 @@ relativeError)); } static double FIRST_NONZEROReduce(double[] a, int idx) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -2704,7 +2807,7 @@ relativeError)); } static double FIRST_NONZEROReduceAll(double[] a) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -2716,20 +2819,15 @@ relativeError)); static void FIRST_NONZEROReduceDouble512VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = (double) 0; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (double) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + double v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -2737,8 +2835,31 @@ relativeError)); Double512VectorTests::FIRST_NONZEROReduce, Double512VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static double FIRST_NONZEROReduceMasked(double[] a, int idx, boolean[] mask) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -2748,7 +2869,7 @@ relativeError)); } static double FIRST_NONZEROReduceAllMasked(double[] a, boolean[] mask) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -2762,20 +2883,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = (double) 0; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (double) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + double v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4806,6 +4922,157 @@ relativeError)); assertArraysEquals(r, a, mask, Double512VectorTests::SQRT); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandDouble512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double512VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorDouble512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double512VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorDouble512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double512VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotDouble512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double512VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqDouble512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double512VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotDouble512VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Double512VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongDouble512VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "doubleCompareOpProvider") static void ltDouble512VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { double[] a = fa.apply(SPECIES.length()); @@ -5095,115 +5362,22 @@ relativeError)); } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsDouble512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsDouble512VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndDouble512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double512VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrDouble512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double512VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorDouble512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double512VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotDouble512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double512VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqDouble512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double512VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeDouble512VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -5308,23 +5482,6 @@ relativeError)); } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongDouble512VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Double64VectorTests.java b/test/jdk/jdk/incubator/vector/Double64VectorTests.java index 85b96288b37..ab3586fb424 100644 --- a/test/jdk/jdk/incubator/vector/Double64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Double64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -62,6 +62,12 @@ public class Double64VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); + // Identity values for reduction operations + private static final double ADD_IDENTITY = (double)0; + private static final double FIRST_NONZERO_IDENTITY = (double)0; + private static final double MAX_IDENTITY = Double.NEGATIVE_INFINITY; + private static final double MIN_IDENTITY = Double.POSITIVE_INFINITY; + private static final double MUL_IDENTITY = (double)1; // for floating point addition reduction ops that may introduce rounding errors private static final double RELATIVE_ROUNDING_ERROR_FACTOR_ADD = (double)10.0; @@ -411,6 +417,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { double apply(double a, double b); } @@ -1291,8 +1327,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -2339,7 +2390,7 @@ relativeError)); } static double ADDReduce(double[] a, int idx) { - double res = 0; + double res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -2348,7 +2399,7 @@ relativeError)); } static double ADDReduceAll(double[] a) { - double res = 0; + double res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -2363,17 +2414,12 @@ relativeError)); double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + double v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -2381,8 +2427,31 @@ relativeError)); Double64VectorTests::ADDReduce, Double64VectorTests::ADDReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_ADD); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = ADD_IDENTITY; + + Assert.assertEquals((double) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) (id + x), x); + Assert.assertEquals((double) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static double ADDReduceMasked(double[] a, int idx, boolean[] mask) { - double res = 0; + double res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -2392,7 +2461,7 @@ relativeError)); } static double ADDReduceAllMasked(double[] a, boolean[] mask) { - double res = 0; + double res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -2409,17 +2478,12 @@ relativeError)); double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + double v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -2428,7 +2492,7 @@ relativeError)); } static double MULReduce(double[] a, int idx) { - double res = 1; + double res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -2437,7 +2501,7 @@ relativeError)); } static double MULReduceAll(double[] a) { - double res = 1; + double res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -2449,20 +2513,15 @@ relativeError)); static void MULReduceDouble64VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = 1; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + double v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -2470,8 +2529,31 @@ relativeError)); Double64VectorTests::MULReduce, Double64VectorTests::MULReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_MUL); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MUL_IDENTITY; + + Assert.assertEquals((double) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) (id * x), x); + Assert.assertEquals((double) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static double MULReduceMasked(double[] a, int idx, boolean[] mask) { - double res = 1; + double res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -2481,7 +2563,7 @@ relativeError)); } static double MULReduceAllMasked(double[] a, boolean[] mask) { - double res = 1; + double res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -2495,20 +2577,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = 1; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + double v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -2517,7 +2594,7 @@ relativeError)); } static double MINReduce(double[] a, int idx) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (double) Math.min(res, a[i]); } @@ -2526,7 +2603,7 @@ relativeError)); } static double MINReduceAll(double[] a) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.min(res, MINReduce(a, i)); } @@ -2538,20 +2615,15 @@ relativeError)); static void MINReduceDouble64VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = Double.POSITIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + double v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (double) Math.min(ra, v); } } @@ -2559,8 +2631,31 @@ relativeError)); Double64VectorTests::MINReduce, Double64VectorTests::MINReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MIN_IDENTITY; + + Assert.assertEquals((double) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) Math.min(id, x), x); + Assert.assertEquals((double) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static double MINReduceMasked(double[] a, int idx, boolean[] mask) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (double) Math.min(res, a[i]); @@ -2570,7 +2665,7 @@ relativeError)); } static double MINReduceAllMasked(double[] a, boolean[] mask) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -2584,20 +2679,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = Double.POSITIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + double v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (double) Math.min(ra, v); } } @@ -2606,7 +2696,7 @@ relativeError)); } static double MAXReduce(double[] a, int idx) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (double) Math.max(res, a[i]); } @@ -2615,7 +2705,7 @@ relativeError)); } static double MAXReduceAll(double[] a) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.max(res, MAXReduce(a, i)); } @@ -2627,20 +2717,15 @@ relativeError)); static void MAXReduceDouble64VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = Double.NEGATIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + double v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (double) Math.max(ra, v); } } @@ -2648,8 +2733,31 @@ relativeError)); Double64VectorTests::MAXReduce, Double64VectorTests::MAXReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MAX_IDENTITY; + + Assert.assertEquals((double) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) Math.max(id, x), x); + Assert.assertEquals((double) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static double MAXReduceMasked(double[] a, int idx, boolean[] mask) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (double) Math.max(res, a[i]); @@ -2659,7 +2767,7 @@ relativeError)); } static double MAXReduceAllMasked(double[] a, boolean[] mask) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -2673,20 +2781,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = Double.NEGATIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + double v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (double) Math.max(ra, v); } } @@ -2695,7 +2798,7 @@ relativeError)); } static double FIRST_NONZEROReduce(double[] a, int idx) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -2704,7 +2807,7 @@ relativeError)); } static double FIRST_NONZEROReduceAll(double[] a) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -2716,20 +2819,15 @@ relativeError)); static void FIRST_NONZEROReduceDouble64VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = (double) 0; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (double) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + double v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -2737,8 +2835,31 @@ relativeError)); Double64VectorTests::FIRST_NONZEROReduce, Double64VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static double FIRST_NONZEROReduceMasked(double[] a, int idx, boolean[] mask) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -2748,7 +2869,7 @@ relativeError)); } static double FIRST_NONZEROReduceAllMasked(double[] a, boolean[] mask) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -2762,20 +2883,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = (double) 0; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (double) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + double v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4806,6 +4922,157 @@ relativeError)); assertArraysEquals(r, a, mask, Double64VectorTests::SQRT); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandDouble64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double64VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorDouble64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double64VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorDouble64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double64VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotDouble64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double64VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqDouble64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Double64VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotDouble64VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Double64VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongDouble64VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "doubleCompareOpProvider") static void ltDouble64VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { double[] a = fa.apply(SPECIES.length()); @@ -5095,115 +5362,22 @@ relativeError)); } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsDouble64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsDouble64VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndDouble64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double64VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrDouble64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double64VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorDouble64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double64VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotDouble64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double64VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqDouble64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Double64VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeDouble64VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -5308,23 +5482,6 @@ relativeError)); } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongDouble64VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java b/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java index 7245990d66c..8f135cd221a 100644 --- a/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -68,6 +68,13 @@ public class DoubleMaxVectorTests extends AbstractVectorTest { private static final int Max = 256; // juts so we can do N/Max + // Identity values for reduction operations + private static final double ADD_IDENTITY = (double)0; + private static final double FIRST_NONZERO_IDENTITY = (double)0; + private static final double MAX_IDENTITY = Double.NEGATIVE_INFINITY; + private static final double MIN_IDENTITY = Double.POSITIVE_INFINITY; + private static final double MUL_IDENTITY = (double)1; + // for floating point addition reduction ops that may introduce rounding errors private static final double RELATIVE_ROUNDING_ERROR_FACTOR_ADD = (double)10.0; @@ -416,6 +423,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { double apply(double a, double b); } @@ -1296,8 +1333,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -2344,7 +2396,7 @@ relativeError)); } static double ADDReduce(double[] a, int idx) { - double res = 0; + double res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -2353,7 +2405,7 @@ relativeError)); } static double ADDReduceAll(double[] a) { - double res = 0; + double res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -2368,17 +2420,12 @@ relativeError)); double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + double v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -2386,8 +2433,31 @@ relativeError)); DoubleMaxVectorTests::ADDReduce, DoubleMaxVectorTests::ADDReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_ADD); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = ADD_IDENTITY; + + Assert.assertEquals((double) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) (id + x), x); + Assert.assertEquals((double) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static double ADDReduceMasked(double[] a, int idx, boolean[] mask) { - double res = 0; + double res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -2397,7 +2467,7 @@ relativeError)); } static double ADDReduceAllMasked(double[] a, boolean[] mask) { - double res = 0; + double res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -2414,17 +2484,12 @@ relativeError)); double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + double v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -2433,7 +2498,7 @@ relativeError)); } static double MULReduce(double[] a, int idx) { - double res = 1; + double res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -2442,7 +2507,7 @@ relativeError)); } static double MULReduceAll(double[] a) { - double res = 1; + double res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -2454,20 +2519,15 @@ relativeError)); static void MULReduceDoubleMaxVectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = 1; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + double v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -2475,8 +2535,31 @@ relativeError)); DoubleMaxVectorTests::MULReduce, DoubleMaxVectorTests::MULReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_MUL); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MUL_IDENTITY; + + Assert.assertEquals((double) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) (id * x), x); + Assert.assertEquals((double) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static double MULReduceMasked(double[] a, int idx, boolean[] mask) { - double res = 1; + double res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -2486,7 +2569,7 @@ relativeError)); } static double MULReduceAllMasked(double[] a, boolean[] mask) { - double res = 1; + double res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -2500,20 +2583,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = 1; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + double v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -2522,7 +2600,7 @@ relativeError)); } static double MINReduce(double[] a, int idx) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (double) Math.min(res, a[i]); } @@ -2531,7 +2609,7 @@ relativeError)); } static double MINReduceAll(double[] a) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.min(res, MINReduce(a, i)); } @@ -2543,20 +2621,15 @@ relativeError)); static void MINReduceDoubleMaxVectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = Double.POSITIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + double v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (double) Math.min(ra, v); } } @@ -2564,8 +2637,31 @@ relativeError)); DoubleMaxVectorTests::MINReduce, DoubleMaxVectorTests::MINReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MIN_IDENTITY; + + Assert.assertEquals((double) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) Math.min(id, x), x); + Assert.assertEquals((double) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static double MINReduceMasked(double[] a, int idx, boolean[] mask) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (double) Math.min(res, a[i]); @@ -2575,7 +2671,7 @@ relativeError)); } static double MINReduceAllMasked(double[] a, boolean[] mask) { - double res = Double.POSITIVE_INFINITY; + double res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -2589,20 +2685,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = Double.POSITIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + double v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (double) Math.min(ra, v); } } @@ -2611,7 +2702,7 @@ relativeError)); } static double MAXReduce(double[] a, int idx) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (double) Math.max(res, a[i]); } @@ -2620,7 +2711,7 @@ relativeError)); } static double MAXReduceAll(double[] a) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.max(res, MAXReduce(a, i)); } @@ -2632,20 +2723,15 @@ relativeError)); static void MAXReduceDoubleMaxVectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = Double.NEGATIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + double v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (double) Math.max(ra, v); } } @@ -2653,8 +2739,31 @@ relativeError)); DoubleMaxVectorTests::MAXReduce, DoubleMaxVectorTests::MAXReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = MAX_IDENTITY; + + Assert.assertEquals((double) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((double) Math.max(id, x), x); + Assert.assertEquals((double) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((double) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((double) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static double MAXReduceMasked(double[] a, int idx, boolean[] mask) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (double) Math.max(res, a[i]); @@ -2664,7 +2773,7 @@ relativeError)); } static double MAXReduceAllMasked(double[] a, boolean[] mask) { - double res = Double.NEGATIVE_INFINITY; + double res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (double) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -2678,20 +2787,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = Double.NEGATIVE_INFINITY; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Double.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = (double) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + double v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (double) Math.max(ra, v); } } @@ -2700,7 +2804,7 @@ relativeError)); } static double FIRST_NONZEROReduce(double[] a, int idx) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -2709,7 +2813,7 @@ relativeError)); } static double FIRST_NONZEROReduceAll(double[] a) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -2721,20 +2825,15 @@ relativeError)); static void FIRST_NONZEROReduceDoubleMaxVectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = fr.apply(SPECIES.length()); - double ra = (double) 0; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (double) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + double v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -2742,8 +2841,31 @@ relativeError)); DoubleMaxVectorTests::FIRST_NONZEROReduce, DoubleMaxVectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "doubleUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + double[] a = fa.apply(SPECIES.length()); + double id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + double x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static double FIRST_NONZEROReduceMasked(double[] a, int idx, boolean[] mask) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -2753,7 +2875,7 @@ relativeError)); } static double FIRST_NONZEROReduceAllMasked(double[] a, boolean[] mask) { - double res = (double) 0; + double res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -2767,20 +2889,15 @@ relativeError)); double[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - double ra = (double) 0; + double ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (double) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + double v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4811,6 +4928,157 @@ relativeError)); assertArraysEquals(r, a, mask, DoubleMaxVectorTests::SQRT); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandDoubleMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, DoubleMaxVectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorDoubleMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, DoubleMaxVectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorDoubleMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, DoubleMaxVectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotDoubleMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, DoubleMaxVectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqDoubleMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, DoubleMaxVectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotDoubleMaxVectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, DoubleMaxVectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongDoubleMaxVectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "doubleCompareOpProvider") static void ltDoubleMaxVectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { double[] a = fa.apply(SPECIES.length()); @@ -5100,115 +5368,22 @@ relativeError)); } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsDoubleMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsDoubleMaxVectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndDoubleMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, DoubleMaxVectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrDoubleMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, DoubleMaxVectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorDoubleMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, DoubleMaxVectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotDoubleMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, DoubleMaxVectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqDoubleMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, DoubleMaxVectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeDoubleMaxVectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -5313,7 +5488,6 @@ relativeError)); } } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Float128VectorTests.java b/test/jdk/jdk/incubator/vector/Float128VectorTests.java index c4f4ed1b966..f97c5b0064c 100644 --- a/test/jdk/jdk/incubator/vector/Float128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Float128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -62,6 +62,12 @@ public class Float128VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); + // Identity values for reduction operations + private static final float ADD_IDENTITY = (float)0; + private static final float FIRST_NONZERO_IDENTITY = (float)0; + private static final float MAX_IDENTITY = Float.NEGATIVE_INFINITY; + private static final float MIN_IDENTITY = Float.POSITIVE_INFINITY; + private static final float MUL_IDENTITY = (float)1; // for floating point addition reduction ops that may introduce rounding errors private static final float RELATIVE_ROUNDING_ERROR_FACTOR_ADD = (float)10.0; @@ -411,6 +417,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { float apply(float a, float b); } @@ -1302,8 +1338,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -2350,7 +2401,7 @@ relativeError)); } static float ADDReduce(float[] a, int idx) { - float res = 0; + float res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -2359,7 +2410,7 @@ relativeError)); } static float ADDReduceAll(float[] a) { - float res = 0; + float res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -2374,17 +2425,12 @@ relativeError)); float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + float v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -2392,8 +2438,31 @@ relativeError)); Float128VectorTests::ADDReduce, Float128VectorTests::ADDReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_ADD); } + @Test(dataProvider = "floatUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = ADD_IDENTITY; + + Assert.assertEquals((float) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) (id + x), x); + Assert.assertEquals((float) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static float ADDReduceMasked(float[] a, int idx, boolean[] mask) { - float res = 0; + float res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -2403,7 +2472,7 @@ relativeError)); } static float ADDReduceAllMasked(float[] a, boolean[] mask) { - float res = 0; + float res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -2420,17 +2489,12 @@ relativeError)); float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + float v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -2439,7 +2503,7 @@ relativeError)); } static float MULReduce(float[] a, int idx) { - float res = 1; + float res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -2448,7 +2512,7 @@ relativeError)); } static float MULReduceAll(float[] a) { - float res = 1; + float res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -2460,20 +2524,15 @@ relativeError)); static void MULReduceFloat128VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = 1; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + float v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -2481,8 +2540,31 @@ relativeError)); Float128VectorTests::MULReduce, Float128VectorTests::MULReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_MUL); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MUL_IDENTITY; + + Assert.assertEquals((float) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) (id * x), x); + Assert.assertEquals((float) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static float MULReduceMasked(float[] a, int idx, boolean[] mask) { - float res = 1; + float res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -2492,7 +2574,7 @@ relativeError)); } static float MULReduceAllMasked(float[] a, boolean[] mask) { - float res = 1; + float res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -2506,20 +2588,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = 1; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + float v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -2528,7 +2605,7 @@ relativeError)); } static float MINReduce(float[] a, int idx) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (float) Math.min(res, a[i]); } @@ -2537,7 +2614,7 @@ relativeError)); } static float MINReduceAll(float[] a) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.min(res, MINReduce(a, i)); } @@ -2549,20 +2626,15 @@ relativeError)); static void MINReduceFloat128VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = Float.POSITIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + float v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (float) Math.min(ra, v); } } @@ -2570,8 +2642,31 @@ relativeError)); Float128VectorTests::MINReduce, Float128VectorTests::MINReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MIN_IDENTITY; + + Assert.assertEquals((float) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) Math.min(id, x), x); + Assert.assertEquals((float) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static float MINReduceMasked(float[] a, int idx, boolean[] mask) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (float) Math.min(res, a[i]); @@ -2581,7 +2676,7 @@ relativeError)); } static float MINReduceAllMasked(float[] a, boolean[] mask) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -2595,20 +2690,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = Float.POSITIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + float v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (float) Math.min(ra, v); } } @@ -2617,7 +2707,7 @@ relativeError)); } static float MAXReduce(float[] a, int idx) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (float) Math.max(res, a[i]); } @@ -2626,7 +2716,7 @@ relativeError)); } static float MAXReduceAll(float[] a) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.max(res, MAXReduce(a, i)); } @@ -2638,20 +2728,15 @@ relativeError)); static void MAXReduceFloat128VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = Float.NEGATIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + float v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (float) Math.max(ra, v); } } @@ -2659,8 +2744,31 @@ relativeError)); Float128VectorTests::MAXReduce, Float128VectorTests::MAXReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MAX_IDENTITY; + + Assert.assertEquals((float) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) Math.max(id, x), x); + Assert.assertEquals((float) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static float MAXReduceMasked(float[] a, int idx, boolean[] mask) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (float) Math.max(res, a[i]); @@ -2670,7 +2778,7 @@ relativeError)); } static float MAXReduceAllMasked(float[] a, boolean[] mask) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -2684,20 +2792,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = Float.NEGATIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + float v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (float) Math.max(ra, v); } } @@ -2706,7 +2809,7 @@ relativeError)); } static float FIRST_NONZEROReduce(float[] a, int idx) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -2715,7 +2818,7 @@ relativeError)); } static float FIRST_NONZEROReduceAll(float[] a) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -2727,20 +2830,15 @@ relativeError)); static void FIRST_NONZEROReduceFloat128VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = (float) 0; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (float) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + float v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -2748,8 +2846,31 @@ relativeError)); Float128VectorTests::FIRST_NONZEROReduce, Float128VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static float FIRST_NONZEROReduceMasked(float[] a, int idx, boolean[] mask) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -2759,7 +2880,7 @@ relativeError)); } static float FIRST_NONZEROReduceAllMasked(float[] a, boolean[] mask) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -2773,20 +2894,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = (float) 0; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (float) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + float v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4775,6 +4891,157 @@ relativeError)); assertArraysEquals(r, a, mask, Float128VectorTests::SQRT); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandFloat128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float128VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorFloat128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float128VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorFloat128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float128VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotFloat128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float128VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqFloat128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float128VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotFloat128VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Float128VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongFloat128VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "floatCompareOpProvider") static void ltFloat128VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { float[] a = fa.apply(SPECIES.length()); @@ -5074,115 +5341,22 @@ relativeError)); } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsFloat128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsFloat128VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndFloat128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float128VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrFloat128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float128VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorFloat128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float128VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotFloat128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float128VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqFloat128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float128VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeFloat128VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -5287,23 +5461,6 @@ relativeError)); } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongFloat128VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Float256VectorTests.java b/test/jdk/jdk/incubator/vector/Float256VectorTests.java index 87cbc165d59..d9746d3291c 100644 --- a/test/jdk/jdk/incubator/vector/Float256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Float256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -62,6 +62,12 @@ public class Float256VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); + // Identity values for reduction operations + private static final float ADD_IDENTITY = (float)0; + private static final float FIRST_NONZERO_IDENTITY = (float)0; + private static final float MAX_IDENTITY = Float.NEGATIVE_INFINITY; + private static final float MIN_IDENTITY = Float.POSITIVE_INFINITY; + private static final float MUL_IDENTITY = (float)1; // for floating point addition reduction ops that may introduce rounding errors private static final float RELATIVE_ROUNDING_ERROR_FACTOR_ADD = (float)10.0; @@ -411,6 +417,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { float apply(float a, float b); } @@ -1302,8 +1338,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -2350,7 +2401,7 @@ relativeError)); } static float ADDReduce(float[] a, int idx) { - float res = 0; + float res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -2359,7 +2410,7 @@ relativeError)); } static float ADDReduceAll(float[] a) { - float res = 0; + float res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -2374,17 +2425,12 @@ relativeError)); float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + float v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -2392,8 +2438,31 @@ relativeError)); Float256VectorTests::ADDReduce, Float256VectorTests::ADDReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_ADD); } + @Test(dataProvider = "floatUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = ADD_IDENTITY; + + Assert.assertEquals((float) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) (id + x), x); + Assert.assertEquals((float) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static float ADDReduceMasked(float[] a, int idx, boolean[] mask) { - float res = 0; + float res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -2403,7 +2472,7 @@ relativeError)); } static float ADDReduceAllMasked(float[] a, boolean[] mask) { - float res = 0; + float res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -2420,17 +2489,12 @@ relativeError)); float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + float v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -2439,7 +2503,7 @@ relativeError)); } static float MULReduce(float[] a, int idx) { - float res = 1; + float res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -2448,7 +2512,7 @@ relativeError)); } static float MULReduceAll(float[] a) { - float res = 1; + float res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -2460,20 +2524,15 @@ relativeError)); static void MULReduceFloat256VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = 1; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + float v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -2481,8 +2540,31 @@ relativeError)); Float256VectorTests::MULReduce, Float256VectorTests::MULReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_MUL); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MUL_IDENTITY; + + Assert.assertEquals((float) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) (id * x), x); + Assert.assertEquals((float) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static float MULReduceMasked(float[] a, int idx, boolean[] mask) { - float res = 1; + float res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -2492,7 +2574,7 @@ relativeError)); } static float MULReduceAllMasked(float[] a, boolean[] mask) { - float res = 1; + float res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -2506,20 +2588,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = 1; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + float v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -2528,7 +2605,7 @@ relativeError)); } static float MINReduce(float[] a, int idx) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (float) Math.min(res, a[i]); } @@ -2537,7 +2614,7 @@ relativeError)); } static float MINReduceAll(float[] a) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.min(res, MINReduce(a, i)); } @@ -2549,20 +2626,15 @@ relativeError)); static void MINReduceFloat256VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = Float.POSITIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + float v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (float) Math.min(ra, v); } } @@ -2570,8 +2642,31 @@ relativeError)); Float256VectorTests::MINReduce, Float256VectorTests::MINReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MIN_IDENTITY; + + Assert.assertEquals((float) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) Math.min(id, x), x); + Assert.assertEquals((float) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static float MINReduceMasked(float[] a, int idx, boolean[] mask) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (float) Math.min(res, a[i]); @@ -2581,7 +2676,7 @@ relativeError)); } static float MINReduceAllMasked(float[] a, boolean[] mask) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -2595,20 +2690,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = Float.POSITIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + float v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (float) Math.min(ra, v); } } @@ -2617,7 +2707,7 @@ relativeError)); } static float MAXReduce(float[] a, int idx) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (float) Math.max(res, a[i]); } @@ -2626,7 +2716,7 @@ relativeError)); } static float MAXReduceAll(float[] a) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.max(res, MAXReduce(a, i)); } @@ -2638,20 +2728,15 @@ relativeError)); static void MAXReduceFloat256VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = Float.NEGATIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + float v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (float) Math.max(ra, v); } } @@ -2659,8 +2744,31 @@ relativeError)); Float256VectorTests::MAXReduce, Float256VectorTests::MAXReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MAX_IDENTITY; + + Assert.assertEquals((float) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) Math.max(id, x), x); + Assert.assertEquals((float) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static float MAXReduceMasked(float[] a, int idx, boolean[] mask) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (float) Math.max(res, a[i]); @@ -2670,7 +2778,7 @@ relativeError)); } static float MAXReduceAllMasked(float[] a, boolean[] mask) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -2684,20 +2792,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = Float.NEGATIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + float v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (float) Math.max(ra, v); } } @@ -2706,7 +2809,7 @@ relativeError)); } static float FIRST_NONZEROReduce(float[] a, int idx) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -2715,7 +2818,7 @@ relativeError)); } static float FIRST_NONZEROReduceAll(float[] a) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -2727,20 +2830,15 @@ relativeError)); static void FIRST_NONZEROReduceFloat256VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = (float) 0; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (float) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + float v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -2748,8 +2846,31 @@ relativeError)); Float256VectorTests::FIRST_NONZEROReduce, Float256VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static float FIRST_NONZEROReduceMasked(float[] a, int idx, boolean[] mask) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -2759,7 +2880,7 @@ relativeError)); } static float FIRST_NONZEROReduceAllMasked(float[] a, boolean[] mask) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -2773,20 +2894,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = (float) 0; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (float) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + float v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4775,6 +4891,157 @@ relativeError)); assertArraysEquals(r, a, mask, Float256VectorTests::SQRT); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandFloat256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float256VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorFloat256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float256VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorFloat256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float256VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotFloat256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float256VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqFloat256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float256VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotFloat256VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Float256VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongFloat256VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "floatCompareOpProvider") static void ltFloat256VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { float[] a = fa.apply(SPECIES.length()); @@ -5074,115 +5341,22 @@ relativeError)); } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsFloat256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsFloat256VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndFloat256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float256VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrFloat256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float256VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorFloat256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float256VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotFloat256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float256VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqFloat256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float256VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeFloat256VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -5287,23 +5461,6 @@ relativeError)); } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongFloat256VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Float512VectorTests.java b/test/jdk/jdk/incubator/vector/Float512VectorTests.java index beb9561d882..ca395221c6b 100644 --- a/test/jdk/jdk/incubator/vector/Float512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Float512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -62,6 +62,12 @@ public class Float512VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); + // Identity values for reduction operations + private static final float ADD_IDENTITY = (float)0; + private static final float FIRST_NONZERO_IDENTITY = (float)0; + private static final float MAX_IDENTITY = Float.NEGATIVE_INFINITY; + private static final float MIN_IDENTITY = Float.POSITIVE_INFINITY; + private static final float MUL_IDENTITY = (float)1; // for floating point addition reduction ops that may introduce rounding errors private static final float RELATIVE_ROUNDING_ERROR_FACTOR_ADD = (float)10.0; @@ -411,6 +417,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { float apply(float a, float b); } @@ -1302,8 +1338,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -2350,7 +2401,7 @@ relativeError)); } static float ADDReduce(float[] a, int idx) { - float res = 0; + float res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -2359,7 +2410,7 @@ relativeError)); } static float ADDReduceAll(float[] a) { - float res = 0; + float res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -2374,17 +2425,12 @@ relativeError)); float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + float v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -2392,8 +2438,31 @@ relativeError)); Float512VectorTests::ADDReduce, Float512VectorTests::ADDReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_ADD); } + @Test(dataProvider = "floatUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = ADD_IDENTITY; + + Assert.assertEquals((float) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) (id + x), x); + Assert.assertEquals((float) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static float ADDReduceMasked(float[] a, int idx, boolean[] mask) { - float res = 0; + float res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -2403,7 +2472,7 @@ relativeError)); } static float ADDReduceAllMasked(float[] a, boolean[] mask) { - float res = 0; + float res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -2420,17 +2489,12 @@ relativeError)); float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + float v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -2439,7 +2503,7 @@ relativeError)); } static float MULReduce(float[] a, int idx) { - float res = 1; + float res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -2448,7 +2512,7 @@ relativeError)); } static float MULReduceAll(float[] a) { - float res = 1; + float res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -2460,20 +2524,15 @@ relativeError)); static void MULReduceFloat512VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = 1; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + float v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -2481,8 +2540,31 @@ relativeError)); Float512VectorTests::MULReduce, Float512VectorTests::MULReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_MUL); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MUL_IDENTITY; + + Assert.assertEquals((float) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) (id * x), x); + Assert.assertEquals((float) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static float MULReduceMasked(float[] a, int idx, boolean[] mask) { - float res = 1; + float res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -2492,7 +2574,7 @@ relativeError)); } static float MULReduceAllMasked(float[] a, boolean[] mask) { - float res = 1; + float res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -2506,20 +2588,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = 1; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + float v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -2528,7 +2605,7 @@ relativeError)); } static float MINReduce(float[] a, int idx) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (float) Math.min(res, a[i]); } @@ -2537,7 +2614,7 @@ relativeError)); } static float MINReduceAll(float[] a) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.min(res, MINReduce(a, i)); } @@ -2549,20 +2626,15 @@ relativeError)); static void MINReduceFloat512VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = Float.POSITIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + float v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (float) Math.min(ra, v); } } @@ -2570,8 +2642,31 @@ relativeError)); Float512VectorTests::MINReduce, Float512VectorTests::MINReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MIN_IDENTITY; + + Assert.assertEquals((float) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) Math.min(id, x), x); + Assert.assertEquals((float) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static float MINReduceMasked(float[] a, int idx, boolean[] mask) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (float) Math.min(res, a[i]); @@ -2581,7 +2676,7 @@ relativeError)); } static float MINReduceAllMasked(float[] a, boolean[] mask) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -2595,20 +2690,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = Float.POSITIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + float v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (float) Math.min(ra, v); } } @@ -2617,7 +2707,7 @@ relativeError)); } static float MAXReduce(float[] a, int idx) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (float) Math.max(res, a[i]); } @@ -2626,7 +2716,7 @@ relativeError)); } static float MAXReduceAll(float[] a) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.max(res, MAXReduce(a, i)); } @@ -2638,20 +2728,15 @@ relativeError)); static void MAXReduceFloat512VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = Float.NEGATIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + float v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (float) Math.max(ra, v); } } @@ -2659,8 +2744,31 @@ relativeError)); Float512VectorTests::MAXReduce, Float512VectorTests::MAXReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MAX_IDENTITY; + + Assert.assertEquals((float) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) Math.max(id, x), x); + Assert.assertEquals((float) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static float MAXReduceMasked(float[] a, int idx, boolean[] mask) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (float) Math.max(res, a[i]); @@ -2670,7 +2778,7 @@ relativeError)); } static float MAXReduceAllMasked(float[] a, boolean[] mask) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -2684,20 +2792,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = Float.NEGATIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + float v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (float) Math.max(ra, v); } } @@ -2706,7 +2809,7 @@ relativeError)); } static float FIRST_NONZEROReduce(float[] a, int idx) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -2715,7 +2818,7 @@ relativeError)); } static float FIRST_NONZEROReduceAll(float[] a) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -2727,20 +2830,15 @@ relativeError)); static void FIRST_NONZEROReduceFloat512VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = (float) 0; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (float) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + float v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -2748,8 +2846,31 @@ relativeError)); Float512VectorTests::FIRST_NONZEROReduce, Float512VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static float FIRST_NONZEROReduceMasked(float[] a, int idx, boolean[] mask) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -2759,7 +2880,7 @@ relativeError)); } static float FIRST_NONZEROReduceAllMasked(float[] a, boolean[] mask) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -2773,20 +2894,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = (float) 0; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (float) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + float v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4775,6 +4891,157 @@ relativeError)); assertArraysEquals(r, a, mask, Float512VectorTests::SQRT); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandFloat512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float512VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorFloat512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float512VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorFloat512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float512VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotFloat512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float512VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqFloat512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float512VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotFloat512VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Float512VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongFloat512VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "floatCompareOpProvider") static void ltFloat512VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { float[] a = fa.apply(SPECIES.length()); @@ -5074,115 +5341,22 @@ relativeError)); } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsFloat512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsFloat512VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndFloat512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float512VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrFloat512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float512VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorFloat512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float512VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotFloat512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float512VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqFloat512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float512VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeFloat512VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -5287,23 +5461,6 @@ relativeError)); } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongFloat512VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Float64VectorTests.java b/test/jdk/jdk/incubator/vector/Float64VectorTests.java index ee630abd8e0..1b14cdb7791 100644 --- a/test/jdk/jdk/incubator/vector/Float64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Float64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -62,6 +62,12 @@ public class Float64VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); + // Identity values for reduction operations + private static final float ADD_IDENTITY = (float)0; + private static final float FIRST_NONZERO_IDENTITY = (float)0; + private static final float MAX_IDENTITY = Float.NEGATIVE_INFINITY; + private static final float MIN_IDENTITY = Float.POSITIVE_INFINITY; + private static final float MUL_IDENTITY = (float)1; // for floating point addition reduction ops that may introduce rounding errors private static final float RELATIVE_ROUNDING_ERROR_FACTOR_ADD = (float)10.0; @@ -411,6 +417,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { float apply(float a, float b); } @@ -1302,8 +1338,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -2350,7 +2401,7 @@ relativeError)); } static float ADDReduce(float[] a, int idx) { - float res = 0; + float res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -2359,7 +2410,7 @@ relativeError)); } static float ADDReduceAll(float[] a) { - float res = 0; + float res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -2374,17 +2425,12 @@ relativeError)); float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + float v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -2392,8 +2438,31 @@ relativeError)); Float64VectorTests::ADDReduce, Float64VectorTests::ADDReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_ADD); } + @Test(dataProvider = "floatUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = ADD_IDENTITY; + + Assert.assertEquals((float) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) (id + x), x); + Assert.assertEquals((float) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static float ADDReduceMasked(float[] a, int idx, boolean[] mask) { - float res = 0; + float res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -2403,7 +2472,7 @@ relativeError)); } static float ADDReduceAllMasked(float[] a, boolean[] mask) { - float res = 0; + float res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -2420,17 +2489,12 @@ relativeError)); float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + float v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -2439,7 +2503,7 @@ relativeError)); } static float MULReduce(float[] a, int idx) { - float res = 1; + float res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -2448,7 +2512,7 @@ relativeError)); } static float MULReduceAll(float[] a) { - float res = 1; + float res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -2460,20 +2524,15 @@ relativeError)); static void MULReduceFloat64VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = 1; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + float v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -2481,8 +2540,31 @@ relativeError)); Float64VectorTests::MULReduce, Float64VectorTests::MULReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_MUL); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MUL_IDENTITY; + + Assert.assertEquals((float) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) (id * x), x); + Assert.assertEquals((float) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static float MULReduceMasked(float[] a, int idx, boolean[] mask) { - float res = 1; + float res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -2492,7 +2574,7 @@ relativeError)); } static float MULReduceAllMasked(float[] a, boolean[] mask) { - float res = 1; + float res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -2506,20 +2588,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = 1; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + float v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -2528,7 +2605,7 @@ relativeError)); } static float MINReduce(float[] a, int idx) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (float) Math.min(res, a[i]); } @@ -2537,7 +2614,7 @@ relativeError)); } static float MINReduceAll(float[] a) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.min(res, MINReduce(a, i)); } @@ -2549,20 +2626,15 @@ relativeError)); static void MINReduceFloat64VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = Float.POSITIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + float v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (float) Math.min(ra, v); } } @@ -2570,8 +2642,31 @@ relativeError)); Float64VectorTests::MINReduce, Float64VectorTests::MINReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MIN_IDENTITY; + + Assert.assertEquals((float) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) Math.min(id, x), x); + Assert.assertEquals((float) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static float MINReduceMasked(float[] a, int idx, boolean[] mask) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (float) Math.min(res, a[i]); @@ -2581,7 +2676,7 @@ relativeError)); } static float MINReduceAllMasked(float[] a, boolean[] mask) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -2595,20 +2690,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = Float.POSITIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + float v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (float) Math.min(ra, v); } } @@ -2617,7 +2707,7 @@ relativeError)); } static float MAXReduce(float[] a, int idx) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (float) Math.max(res, a[i]); } @@ -2626,7 +2716,7 @@ relativeError)); } static float MAXReduceAll(float[] a) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.max(res, MAXReduce(a, i)); } @@ -2638,20 +2728,15 @@ relativeError)); static void MAXReduceFloat64VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = Float.NEGATIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + float v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (float) Math.max(ra, v); } } @@ -2659,8 +2744,31 @@ relativeError)); Float64VectorTests::MAXReduce, Float64VectorTests::MAXReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MAX_IDENTITY; + + Assert.assertEquals((float) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) Math.max(id, x), x); + Assert.assertEquals((float) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static float MAXReduceMasked(float[] a, int idx, boolean[] mask) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (float) Math.max(res, a[i]); @@ -2670,7 +2778,7 @@ relativeError)); } static float MAXReduceAllMasked(float[] a, boolean[] mask) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -2684,20 +2792,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = Float.NEGATIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + float v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (float) Math.max(ra, v); } } @@ -2706,7 +2809,7 @@ relativeError)); } static float FIRST_NONZEROReduce(float[] a, int idx) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -2715,7 +2818,7 @@ relativeError)); } static float FIRST_NONZEROReduceAll(float[] a) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -2727,20 +2830,15 @@ relativeError)); static void FIRST_NONZEROReduceFloat64VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = (float) 0; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (float) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + float v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -2748,8 +2846,31 @@ relativeError)); Float64VectorTests::FIRST_NONZEROReduce, Float64VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static float FIRST_NONZEROReduceMasked(float[] a, int idx, boolean[] mask) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -2759,7 +2880,7 @@ relativeError)); } static float FIRST_NONZEROReduceAllMasked(float[] a, boolean[] mask) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -2773,20 +2894,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = (float) 0; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (float) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + float v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4775,6 +4891,157 @@ relativeError)); assertArraysEquals(r, a, mask, Float64VectorTests::SQRT); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandFloat64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float64VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorFloat64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float64VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorFloat64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float64VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotFloat64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float64VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqFloat64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Float64VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotFloat64VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Float64VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongFloat64VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "floatCompareOpProvider") static void ltFloat64VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { float[] a = fa.apply(SPECIES.length()); @@ -5074,115 +5341,22 @@ relativeError)); } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsFloat64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsFloat64VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndFloat64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float64VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrFloat64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float64VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorFloat64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float64VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotFloat64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float64VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqFloat64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Float64VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeFloat64VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -5287,23 +5461,6 @@ relativeError)); } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongFloat64VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java b/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java index 41e4d6e4a5d..53edb408035 100644 --- a/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -68,6 +68,13 @@ public class FloatMaxVectorTests extends AbstractVectorTest { private static final int Max = 256; // juts so we can do N/Max + // Identity values for reduction operations + private static final float ADD_IDENTITY = (float)0; + private static final float FIRST_NONZERO_IDENTITY = (float)0; + private static final float MAX_IDENTITY = Float.NEGATIVE_INFINITY; + private static final float MIN_IDENTITY = Float.POSITIVE_INFINITY; + private static final float MUL_IDENTITY = (float)1; + // for floating point addition reduction ops that may introduce rounding errors private static final float RELATIVE_ROUNDING_ERROR_FACTOR_ADD = (float)10.0; @@ -416,6 +423,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { float apply(float a, float b); } @@ -1307,8 +1344,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -2355,7 +2407,7 @@ relativeError)); } static float ADDReduce(float[] a, int idx) { - float res = 0; + float res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -2364,7 +2416,7 @@ relativeError)); } static float ADDReduceAll(float[] a) { - float res = 0; + float res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -2379,17 +2431,12 @@ relativeError)); float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + float v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -2397,8 +2444,31 @@ relativeError)); FloatMaxVectorTests::ADDReduce, FloatMaxVectorTests::ADDReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_ADD); } + @Test(dataProvider = "floatUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = ADD_IDENTITY; + + Assert.assertEquals((float) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) (id + x), x); + Assert.assertEquals((float) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static float ADDReduceMasked(float[] a, int idx, boolean[] mask) { - float res = 0; + float res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -2408,7 +2478,7 @@ relativeError)); } static float ADDReduceAllMasked(float[] a, boolean[] mask) { - float res = 0; + float res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -2425,17 +2495,12 @@ relativeError)); float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + float v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -2444,7 +2509,7 @@ relativeError)); } static float MULReduce(float[] a, int idx) { - float res = 1; + float res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -2453,7 +2518,7 @@ relativeError)); } static float MULReduceAll(float[] a) { - float res = 1; + float res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -2465,20 +2530,15 @@ relativeError)); static void MULReduceFloatMaxVectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = 1; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + float v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -2486,8 +2546,31 @@ relativeError)); FloatMaxVectorTests::MULReduce, FloatMaxVectorTests::MULReduceAll, RELATIVE_ROUNDING_ERROR_FACTOR_MUL); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MUL_IDENTITY; + + Assert.assertEquals((float) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) (id * x), x); + Assert.assertEquals((float) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static float MULReduceMasked(float[] a, int idx, boolean[] mask) { - float res = 1; + float res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -2497,7 +2580,7 @@ relativeError)); } static float MULReduceAllMasked(float[] a, boolean[] mask) { - float res = 1; + float res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -2511,20 +2594,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = 1; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + float v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -2533,7 +2611,7 @@ relativeError)); } static float MINReduce(float[] a, int idx) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (float) Math.min(res, a[i]); } @@ -2542,7 +2620,7 @@ relativeError)); } static float MINReduceAll(float[] a) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.min(res, MINReduce(a, i)); } @@ -2554,20 +2632,15 @@ relativeError)); static void MINReduceFloatMaxVectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = Float.POSITIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + float v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (float) Math.min(ra, v); } } @@ -2575,8 +2648,31 @@ relativeError)); FloatMaxVectorTests::MINReduce, FloatMaxVectorTests::MINReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MIN_IDENTITY; + + Assert.assertEquals((float) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) Math.min(id, x), x); + Assert.assertEquals((float) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static float MINReduceMasked(float[] a, int idx, boolean[] mask) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (float) Math.min(res, a[i]); @@ -2586,7 +2682,7 @@ relativeError)); } static float MINReduceAllMasked(float[] a, boolean[] mask) { - float res = Float.POSITIVE_INFINITY; + float res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -2600,20 +2696,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = Float.POSITIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.POSITIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + float v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (float) Math.min(ra, v); } } @@ -2622,7 +2713,7 @@ relativeError)); } static float MAXReduce(float[] a, int idx) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (float) Math.max(res, a[i]); } @@ -2631,7 +2722,7 @@ relativeError)); } static float MAXReduceAll(float[] a) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.max(res, MAXReduce(a, i)); } @@ -2643,20 +2734,15 @@ relativeError)); static void MAXReduceFloatMaxVectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = Float.NEGATIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + float v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (float) Math.max(ra, v); } } @@ -2664,8 +2750,31 @@ relativeError)); FloatMaxVectorTests::MAXReduce, FloatMaxVectorTests::MAXReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = MAX_IDENTITY; + + Assert.assertEquals((float) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((float) Math.max(id, x), x); + Assert.assertEquals((float) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((float) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((float) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static float MAXReduceMasked(float[] a, int idx, boolean[] mask) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (float) Math.max(res, a[i]); @@ -2675,7 +2784,7 @@ relativeError)); } static float MAXReduceAllMasked(float[] a, boolean[] mask) { - float res = Float.NEGATIVE_INFINITY; + float res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (float) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -2689,20 +2798,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = Float.NEGATIVE_INFINITY; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Float.NEGATIVE_INFINITY; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = (float) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + float v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (float) Math.max(ra, v); } } @@ -2711,7 +2815,7 @@ relativeError)); } static float FIRST_NONZEROReduce(float[] a, int idx) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -2720,7 +2824,7 @@ relativeError)); } static float FIRST_NONZEROReduceAll(float[] a) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -2732,20 +2836,15 @@ relativeError)); static void FIRST_NONZEROReduceFloatMaxVectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = fr.apply(SPECIES.length()); - float ra = (float) 0; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (float) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + float v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -2753,8 +2852,31 @@ relativeError)); FloatMaxVectorTests::FIRST_NONZEROReduce, FloatMaxVectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "floatUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + float[] a = fa.apply(SPECIES.length()); + float id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + float x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static float FIRST_NONZEROReduceMasked(float[] a, int idx, boolean[] mask) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -2764,7 +2886,7 @@ relativeError)); } static float FIRST_NONZEROReduceAllMasked(float[] a, boolean[] mask) { - float res = (float) 0; + float res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -2778,20 +2900,15 @@ relativeError)); float[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - float ra = (float) 0; + float ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (float) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - FloatVector av = FloatVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + float v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4780,6 +4897,157 @@ relativeError)); assertArraysEquals(r, a, mask, FloatMaxVectorTests::SQRT); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandFloatMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, FloatMaxVectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorFloatMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, FloatMaxVectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorFloatMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, FloatMaxVectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotFloatMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, FloatMaxVectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqFloatMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, FloatMaxVectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotFloatMaxVectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, FloatMaxVectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongFloatMaxVectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "floatCompareOpProvider") static void ltFloatMaxVectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { float[] a = fa.apply(SPECIES.length()); @@ -5079,115 +5347,22 @@ relativeError)); } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsFloatMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsFloatMaxVectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndFloatMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, FloatMaxVectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrFloatMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, FloatMaxVectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorFloatMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, FloatMaxVectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotFloatMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, FloatMaxVectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqFloatMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, FloatMaxVectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeFloatMaxVectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -5292,7 +5467,6 @@ relativeError)); } } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Int128VectorTests.java b/test/jdk/jdk/incubator/vector/Int128VectorTests.java index d6bca96ea6e..69bb0c84588 100644 --- a/test/jdk/jdk/incubator/vector/Int128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Int128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Int128VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final int CONST_SHIFT = Integer.SIZE / 2; + // Identity values for reduction operations + private static final int ADD_IDENTITY = (int)0; + private static final int AND_IDENTITY = (int)-1; + private static final int FIRST_NONZERO_IDENTITY = (int)0; + private static final int MAX_IDENTITY = Integer.MIN_VALUE; + private static final int MIN_IDENTITY = Integer.MAX_VALUE; + private static final int MUL_IDENTITY = (int)1; + private static final int OR_IDENTITY = (int)0; + private static final int SUADD_IDENTITY = (int)0; + private static final int UMAX_IDENTITY = (int)0; // Minimum unsigned value + private static final int UMIN_IDENTITY = (int)-1; // Maximum unsigned value + private static final int XOR_IDENTITY = (int)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 128); static void assertArraysStrictlyEquals(int[] r, int[] a) { @@ -393,6 +405,36 @@ public class Int128VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { int apply(int a, int b); } @@ -1222,8 +1264,23 @@ public class Int128VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3610,7 +3667,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int ANDReduce(int[] a, int idx) { - int res = -1; + int res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3619,7 +3676,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int ANDReduceAll(int[] a) { - int res = -1; + int res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3631,20 +3688,15 @@ public class Int128VectorTests extends AbstractVectorTest { static void ANDReduceInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = -1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + int v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3652,8 +3704,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::ANDReduce, Int128VectorTests::ANDReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = AND_IDENTITY; + + Assert.assertEquals((int) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id & x), x); + Assert.assertEquals((int) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static int ANDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = -1; + int res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3663,7 +3738,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int ANDReduceAllMasked(int[] a, boolean[] mask) { - int res = -1; + int res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3677,20 +3752,15 @@ public class Int128VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = -1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + int v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3699,7 +3769,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int ORReduce(int[] a, int idx) { - int res = 0; + int res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3708,7 +3778,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int ORReduceAll(int[] a) { - int res = 0; + int res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3723,17 +3793,12 @@ public class Int128VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + int v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3741,8 +3806,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::ORReduce, Int128VectorTests::ORReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = OR_IDENTITY; + + Assert.assertEquals((int) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id | x), x); + Assert.assertEquals((int) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static int ORReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3752,7 +3840,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int ORReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3769,17 +3857,12 @@ public class Int128VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + int v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3788,7 +3871,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int XORReduce(int[] a, int idx) { - int res = 0; + int res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3797,7 +3880,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int XORReduceAll(int[] a) { - int res = 0; + int res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3812,17 +3895,12 @@ public class Int128VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + int v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3830,8 +3908,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::XORReduce, Int128VectorTests::XORReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = XOR_IDENTITY; + + Assert.assertEquals((int) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id ^ x), x); + Assert.assertEquals((int) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static int XORReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3841,7 +3942,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int XORReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3858,17 +3959,12 @@ public class Int128VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + int v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3877,7 +3973,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int ADDReduce(int[] a, int idx) { - int res = 0; + int res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3886,7 +3982,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int ADDReduceAll(int[] a) { - int res = 0; + int res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3901,17 +3997,12 @@ public class Int128VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + int v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3919,8 +4010,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::ADDReduce, Int128VectorTests::ADDReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = ADD_IDENTITY; + + Assert.assertEquals((int) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id + x), x); + Assert.assertEquals((int) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static int ADDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3930,7 +4044,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int ADDReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3947,17 +4061,12 @@ public class Int128VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + int v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3966,7 +4075,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int MULReduce(int[] a, int idx) { - int res = 1; + int res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3975,7 +4084,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int MULReduceAll(int[] a) { - int res = 1; + int res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3987,20 +4096,15 @@ public class Int128VectorTests extends AbstractVectorTest { static void MULReduceInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = 1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + int v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -4008,8 +4112,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::MULReduce, Int128VectorTests::MULReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MUL_IDENTITY; + + Assert.assertEquals((int) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id * x), x); + Assert.assertEquals((int) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static int MULReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 1; + int res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -4019,7 +4146,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int MULReduceAllMasked(int[] a, boolean[] mask) { - int res = 1; + int res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -4033,20 +4160,15 @@ public class Int128VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = 1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + int v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4055,7 +4177,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int MINReduce(int[] a, int idx) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) Math.min(res, a[i]); } @@ -4064,7 +4186,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int MINReduceAll(int[] a) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.min(res, MINReduce(a, i)); } @@ -4076,20 +4198,15 @@ public class Int128VectorTests extends AbstractVectorTest { static void MINReduceInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + int v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (int) Math.min(ra, v); } } @@ -4097,8 +4214,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::MINReduce, Int128VectorTests::MINReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MIN_IDENTITY; + + Assert.assertEquals((int) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) Math.min(id, x), x); + Assert.assertEquals((int) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static int MINReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) Math.min(res, a[i]); @@ -4108,7 +4248,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int MINReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4122,20 +4262,15 @@ public class Int128VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + int v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (int) Math.min(ra, v); } } @@ -4144,7 +4279,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int MAXReduce(int[] a, int idx) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) Math.max(res, a[i]); } @@ -4153,7 +4288,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int MAXReduceAll(int[] a) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.max(res, MAXReduce(a, i)); } @@ -4165,20 +4300,15 @@ public class Int128VectorTests extends AbstractVectorTest { static void MAXReduceInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + int v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (int) Math.max(ra, v); } } @@ -4186,8 +4316,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::MAXReduce, Int128VectorTests::MAXReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MAX_IDENTITY; + + Assert.assertEquals((int) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) Math.max(id, x), x); + Assert.assertEquals((int) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static int MAXReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) Math.max(res, a[i]); @@ -4197,7 +4350,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int MAXReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4211,20 +4364,15 @@ public class Int128VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + int v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (int) Math.max(ra, v); } } @@ -4233,7 +4381,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int UMINReduce(int[] a, int idx) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.minUnsigned(res, a[i]); } @@ -4242,7 +4390,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int UMINReduceAll(int[] a) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4254,20 +4402,15 @@ public class Int128VectorTests extends AbstractVectorTest { static void UMINReduceInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + int v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (int) VectorMath.minUnsigned(ra, v); } } @@ -4275,8 +4418,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::UMINReduce, Int128VectorTests::UMINReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = UMIN_IDENTITY; + + Assert.assertEquals((int) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static int UMINReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.minUnsigned(res, a[i]); @@ -4286,7 +4452,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int UMINReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4300,20 +4466,15 @@ public class Int128VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + int v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (int) VectorMath.minUnsigned(ra, v); } } @@ -4322,7 +4483,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int UMAXReduce(int[] a, int idx) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.maxUnsigned(res, a[i]); } @@ -4331,7 +4492,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int UMAXReduceAll(int[] a) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4343,20 +4504,15 @@ public class Int128VectorTests extends AbstractVectorTest { static void UMAXReduceInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + int v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (int) VectorMath.maxUnsigned(ra, v); } } @@ -4364,8 +4520,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::UMAXReduce, Int128VectorTests::UMAXReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = UMAX_IDENTITY; + + Assert.assertEquals((int) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static int UMAXReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.maxUnsigned(res, a[i]); @@ -4375,7 +4554,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int UMAXReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4389,20 +4568,15 @@ public class Int128VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + int v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (int) VectorMath.maxUnsigned(ra, v); } } @@ -4411,7 +4585,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduce(int[] a, int idx) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4420,7 +4594,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduceAll(int[] a) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4432,20 +4606,15 @@ public class Int128VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = (int) 0; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (int) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + int v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4453,8 +4622,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::FIRST_NONZEROReduce, Int128VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static int FIRST_NONZEROReduceMasked(int[] a, int idx, boolean[] mask) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4464,7 +4656,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduceAllMasked(int[] a, boolean[] mask) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4478,20 +4670,15 @@ public class Int128VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = (int) 0; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (int) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + int v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4548,7 +4735,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int SUADDReduce(int[] a, int idx) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4557,7 +4744,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int SUADDReduceAll(int[] a) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4572,17 +4759,12 @@ public class Int128VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + int v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (int) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4590,8 +4772,31 @@ public class Int128VectorTests extends AbstractVectorTest { Int128VectorTests::SUADDReduce, Int128VectorTests::SUADDReduceAll); } + @Test(dataProvider = "intSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = SUADD_IDENTITY; + + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static int SUADDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4601,7 +4806,7 @@ public class Int128VectorTests extends AbstractVectorTest { } static int SUADDReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4617,17 +4822,12 @@ public class Int128VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + int v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (int) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6434,6 +6634,157 @@ public class Int128VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Int128VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandInt128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int128VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorInt128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int128VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorInt128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int128VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotInt128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int128VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqInt128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int128VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotInt128VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Int128VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongInt128VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "intCompareOpProvider") static void ltInt128VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { int[] a = fa.apply(SPECIES.length()); @@ -6733,115 +7084,22 @@ public class Int128VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsInt128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsInt128VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndInt128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int128VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrInt128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int128VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorInt128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int128VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotInt128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int128VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqInt128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int128VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeInt128VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6946,23 +7204,6 @@ public class Int128VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongInt128VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Int256VectorTests.java b/test/jdk/jdk/incubator/vector/Int256VectorTests.java index ac98217b714..4e63de95b7b 100644 --- a/test/jdk/jdk/incubator/vector/Int256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Int256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Int256VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final int CONST_SHIFT = Integer.SIZE / 2; + // Identity values for reduction operations + private static final int ADD_IDENTITY = (int)0; + private static final int AND_IDENTITY = (int)-1; + private static final int FIRST_NONZERO_IDENTITY = (int)0; + private static final int MAX_IDENTITY = Integer.MIN_VALUE; + private static final int MIN_IDENTITY = Integer.MAX_VALUE; + private static final int MUL_IDENTITY = (int)1; + private static final int OR_IDENTITY = (int)0; + private static final int SUADD_IDENTITY = (int)0; + private static final int UMAX_IDENTITY = (int)0; // Minimum unsigned value + private static final int UMIN_IDENTITY = (int)-1; // Maximum unsigned value + private static final int XOR_IDENTITY = (int)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 256); static void assertArraysStrictlyEquals(int[] r, int[] a) { @@ -393,6 +405,36 @@ public class Int256VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { int apply(int a, int b); } @@ -1222,8 +1264,23 @@ public class Int256VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3610,7 +3667,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int ANDReduce(int[] a, int idx) { - int res = -1; + int res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3619,7 +3676,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int ANDReduceAll(int[] a) { - int res = -1; + int res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3631,20 +3688,15 @@ public class Int256VectorTests extends AbstractVectorTest { static void ANDReduceInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = -1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + int v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3652,8 +3704,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::ANDReduce, Int256VectorTests::ANDReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = AND_IDENTITY; + + Assert.assertEquals((int) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id & x), x); + Assert.assertEquals((int) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static int ANDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = -1; + int res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3663,7 +3738,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int ANDReduceAllMasked(int[] a, boolean[] mask) { - int res = -1; + int res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3677,20 +3752,15 @@ public class Int256VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = -1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + int v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3699,7 +3769,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int ORReduce(int[] a, int idx) { - int res = 0; + int res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3708,7 +3778,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int ORReduceAll(int[] a) { - int res = 0; + int res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3723,17 +3793,12 @@ public class Int256VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + int v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3741,8 +3806,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::ORReduce, Int256VectorTests::ORReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = OR_IDENTITY; + + Assert.assertEquals((int) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id | x), x); + Assert.assertEquals((int) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static int ORReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3752,7 +3840,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int ORReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3769,17 +3857,12 @@ public class Int256VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + int v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3788,7 +3871,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int XORReduce(int[] a, int idx) { - int res = 0; + int res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3797,7 +3880,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int XORReduceAll(int[] a) { - int res = 0; + int res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3812,17 +3895,12 @@ public class Int256VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + int v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3830,8 +3908,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::XORReduce, Int256VectorTests::XORReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = XOR_IDENTITY; + + Assert.assertEquals((int) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id ^ x), x); + Assert.assertEquals((int) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static int XORReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3841,7 +3942,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int XORReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3858,17 +3959,12 @@ public class Int256VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + int v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3877,7 +3973,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int ADDReduce(int[] a, int idx) { - int res = 0; + int res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3886,7 +3982,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int ADDReduceAll(int[] a) { - int res = 0; + int res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3901,17 +3997,12 @@ public class Int256VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + int v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3919,8 +4010,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::ADDReduce, Int256VectorTests::ADDReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = ADD_IDENTITY; + + Assert.assertEquals((int) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id + x), x); + Assert.assertEquals((int) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static int ADDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3930,7 +4044,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int ADDReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3947,17 +4061,12 @@ public class Int256VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + int v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3966,7 +4075,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int MULReduce(int[] a, int idx) { - int res = 1; + int res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3975,7 +4084,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int MULReduceAll(int[] a) { - int res = 1; + int res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3987,20 +4096,15 @@ public class Int256VectorTests extends AbstractVectorTest { static void MULReduceInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = 1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + int v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -4008,8 +4112,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::MULReduce, Int256VectorTests::MULReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MUL_IDENTITY; + + Assert.assertEquals((int) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id * x), x); + Assert.assertEquals((int) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static int MULReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 1; + int res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -4019,7 +4146,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int MULReduceAllMasked(int[] a, boolean[] mask) { - int res = 1; + int res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -4033,20 +4160,15 @@ public class Int256VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = 1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + int v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4055,7 +4177,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int MINReduce(int[] a, int idx) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) Math.min(res, a[i]); } @@ -4064,7 +4186,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int MINReduceAll(int[] a) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.min(res, MINReduce(a, i)); } @@ -4076,20 +4198,15 @@ public class Int256VectorTests extends AbstractVectorTest { static void MINReduceInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + int v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (int) Math.min(ra, v); } } @@ -4097,8 +4214,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::MINReduce, Int256VectorTests::MINReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MIN_IDENTITY; + + Assert.assertEquals((int) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) Math.min(id, x), x); + Assert.assertEquals((int) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static int MINReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) Math.min(res, a[i]); @@ -4108,7 +4248,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int MINReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4122,20 +4262,15 @@ public class Int256VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + int v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (int) Math.min(ra, v); } } @@ -4144,7 +4279,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int MAXReduce(int[] a, int idx) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) Math.max(res, a[i]); } @@ -4153,7 +4288,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int MAXReduceAll(int[] a) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.max(res, MAXReduce(a, i)); } @@ -4165,20 +4300,15 @@ public class Int256VectorTests extends AbstractVectorTest { static void MAXReduceInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + int v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (int) Math.max(ra, v); } } @@ -4186,8 +4316,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::MAXReduce, Int256VectorTests::MAXReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MAX_IDENTITY; + + Assert.assertEquals((int) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) Math.max(id, x), x); + Assert.assertEquals((int) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static int MAXReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) Math.max(res, a[i]); @@ -4197,7 +4350,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int MAXReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4211,20 +4364,15 @@ public class Int256VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + int v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (int) Math.max(ra, v); } } @@ -4233,7 +4381,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int UMINReduce(int[] a, int idx) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.minUnsigned(res, a[i]); } @@ -4242,7 +4390,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int UMINReduceAll(int[] a) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4254,20 +4402,15 @@ public class Int256VectorTests extends AbstractVectorTest { static void UMINReduceInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + int v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (int) VectorMath.minUnsigned(ra, v); } } @@ -4275,8 +4418,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::UMINReduce, Int256VectorTests::UMINReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = UMIN_IDENTITY; + + Assert.assertEquals((int) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static int UMINReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.minUnsigned(res, a[i]); @@ -4286,7 +4452,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int UMINReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4300,20 +4466,15 @@ public class Int256VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + int v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (int) VectorMath.minUnsigned(ra, v); } } @@ -4322,7 +4483,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int UMAXReduce(int[] a, int idx) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.maxUnsigned(res, a[i]); } @@ -4331,7 +4492,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int UMAXReduceAll(int[] a) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4343,20 +4504,15 @@ public class Int256VectorTests extends AbstractVectorTest { static void UMAXReduceInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + int v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (int) VectorMath.maxUnsigned(ra, v); } } @@ -4364,8 +4520,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::UMAXReduce, Int256VectorTests::UMAXReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = UMAX_IDENTITY; + + Assert.assertEquals((int) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static int UMAXReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.maxUnsigned(res, a[i]); @@ -4375,7 +4554,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int UMAXReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4389,20 +4568,15 @@ public class Int256VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + int v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (int) VectorMath.maxUnsigned(ra, v); } } @@ -4411,7 +4585,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduce(int[] a, int idx) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4420,7 +4594,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduceAll(int[] a) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4432,20 +4606,15 @@ public class Int256VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = (int) 0; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (int) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + int v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4453,8 +4622,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::FIRST_NONZEROReduce, Int256VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static int FIRST_NONZEROReduceMasked(int[] a, int idx, boolean[] mask) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4464,7 +4656,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduceAllMasked(int[] a, boolean[] mask) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4478,20 +4670,15 @@ public class Int256VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = (int) 0; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (int) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + int v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4548,7 +4735,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int SUADDReduce(int[] a, int idx) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4557,7 +4744,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int SUADDReduceAll(int[] a) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4572,17 +4759,12 @@ public class Int256VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + int v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (int) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4590,8 +4772,31 @@ public class Int256VectorTests extends AbstractVectorTest { Int256VectorTests::SUADDReduce, Int256VectorTests::SUADDReduceAll); } + @Test(dataProvider = "intSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = SUADD_IDENTITY; + + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static int SUADDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4601,7 +4806,7 @@ public class Int256VectorTests extends AbstractVectorTest { } static int SUADDReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4617,17 +4822,12 @@ public class Int256VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + int v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (int) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6434,6 +6634,157 @@ public class Int256VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Int256VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandInt256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int256VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorInt256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int256VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorInt256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int256VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotInt256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int256VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqInt256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int256VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotInt256VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Int256VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongInt256VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "intCompareOpProvider") static void ltInt256VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { int[] a = fa.apply(SPECIES.length()); @@ -6733,115 +7084,22 @@ public class Int256VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsInt256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsInt256VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndInt256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int256VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrInt256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int256VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorInt256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int256VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotInt256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int256VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqInt256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int256VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeInt256VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6946,23 +7204,6 @@ public class Int256VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongInt256VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Int512VectorTests.java b/test/jdk/jdk/incubator/vector/Int512VectorTests.java index b56236db322..e2de7905a83 100644 --- a/test/jdk/jdk/incubator/vector/Int512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Int512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Int512VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final int CONST_SHIFT = Integer.SIZE / 2; + // Identity values for reduction operations + private static final int ADD_IDENTITY = (int)0; + private static final int AND_IDENTITY = (int)-1; + private static final int FIRST_NONZERO_IDENTITY = (int)0; + private static final int MAX_IDENTITY = Integer.MIN_VALUE; + private static final int MIN_IDENTITY = Integer.MAX_VALUE; + private static final int MUL_IDENTITY = (int)1; + private static final int OR_IDENTITY = (int)0; + private static final int SUADD_IDENTITY = (int)0; + private static final int UMAX_IDENTITY = (int)0; // Minimum unsigned value + private static final int UMIN_IDENTITY = (int)-1; // Maximum unsigned value + private static final int XOR_IDENTITY = (int)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 512); static void assertArraysStrictlyEquals(int[] r, int[] a) { @@ -393,6 +405,36 @@ public class Int512VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { int apply(int a, int b); } @@ -1222,8 +1264,23 @@ public class Int512VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3610,7 +3667,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int ANDReduce(int[] a, int idx) { - int res = -1; + int res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3619,7 +3676,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int ANDReduceAll(int[] a) { - int res = -1; + int res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3631,20 +3688,15 @@ public class Int512VectorTests extends AbstractVectorTest { static void ANDReduceInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = -1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + int v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3652,8 +3704,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::ANDReduce, Int512VectorTests::ANDReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = AND_IDENTITY; + + Assert.assertEquals((int) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id & x), x); + Assert.assertEquals((int) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static int ANDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = -1; + int res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3663,7 +3738,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int ANDReduceAllMasked(int[] a, boolean[] mask) { - int res = -1; + int res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3677,20 +3752,15 @@ public class Int512VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = -1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + int v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3699,7 +3769,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int ORReduce(int[] a, int idx) { - int res = 0; + int res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3708,7 +3778,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int ORReduceAll(int[] a) { - int res = 0; + int res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3723,17 +3793,12 @@ public class Int512VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + int v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3741,8 +3806,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::ORReduce, Int512VectorTests::ORReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = OR_IDENTITY; + + Assert.assertEquals((int) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id | x), x); + Assert.assertEquals((int) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static int ORReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3752,7 +3840,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int ORReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3769,17 +3857,12 @@ public class Int512VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + int v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3788,7 +3871,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int XORReduce(int[] a, int idx) { - int res = 0; + int res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3797,7 +3880,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int XORReduceAll(int[] a) { - int res = 0; + int res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3812,17 +3895,12 @@ public class Int512VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + int v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3830,8 +3908,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::XORReduce, Int512VectorTests::XORReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = XOR_IDENTITY; + + Assert.assertEquals((int) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id ^ x), x); + Assert.assertEquals((int) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static int XORReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3841,7 +3942,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int XORReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3858,17 +3959,12 @@ public class Int512VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + int v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3877,7 +3973,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int ADDReduce(int[] a, int idx) { - int res = 0; + int res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3886,7 +3982,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int ADDReduceAll(int[] a) { - int res = 0; + int res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3901,17 +3997,12 @@ public class Int512VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + int v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3919,8 +4010,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::ADDReduce, Int512VectorTests::ADDReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = ADD_IDENTITY; + + Assert.assertEquals((int) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id + x), x); + Assert.assertEquals((int) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static int ADDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3930,7 +4044,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int ADDReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3947,17 +4061,12 @@ public class Int512VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + int v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3966,7 +4075,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int MULReduce(int[] a, int idx) { - int res = 1; + int res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3975,7 +4084,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int MULReduceAll(int[] a) { - int res = 1; + int res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3987,20 +4096,15 @@ public class Int512VectorTests extends AbstractVectorTest { static void MULReduceInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = 1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + int v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -4008,8 +4112,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::MULReduce, Int512VectorTests::MULReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MUL_IDENTITY; + + Assert.assertEquals((int) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id * x), x); + Assert.assertEquals((int) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static int MULReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 1; + int res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -4019,7 +4146,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int MULReduceAllMasked(int[] a, boolean[] mask) { - int res = 1; + int res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -4033,20 +4160,15 @@ public class Int512VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = 1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + int v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4055,7 +4177,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int MINReduce(int[] a, int idx) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) Math.min(res, a[i]); } @@ -4064,7 +4186,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int MINReduceAll(int[] a) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.min(res, MINReduce(a, i)); } @@ -4076,20 +4198,15 @@ public class Int512VectorTests extends AbstractVectorTest { static void MINReduceInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + int v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (int) Math.min(ra, v); } } @@ -4097,8 +4214,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::MINReduce, Int512VectorTests::MINReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MIN_IDENTITY; + + Assert.assertEquals((int) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) Math.min(id, x), x); + Assert.assertEquals((int) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static int MINReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) Math.min(res, a[i]); @@ -4108,7 +4248,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int MINReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4122,20 +4262,15 @@ public class Int512VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + int v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (int) Math.min(ra, v); } } @@ -4144,7 +4279,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int MAXReduce(int[] a, int idx) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) Math.max(res, a[i]); } @@ -4153,7 +4288,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int MAXReduceAll(int[] a) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.max(res, MAXReduce(a, i)); } @@ -4165,20 +4300,15 @@ public class Int512VectorTests extends AbstractVectorTest { static void MAXReduceInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + int v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (int) Math.max(ra, v); } } @@ -4186,8 +4316,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::MAXReduce, Int512VectorTests::MAXReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MAX_IDENTITY; + + Assert.assertEquals((int) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) Math.max(id, x), x); + Assert.assertEquals((int) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static int MAXReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) Math.max(res, a[i]); @@ -4197,7 +4350,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int MAXReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4211,20 +4364,15 @@ public class Int512VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + int v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (int) Math.max(ra, v); } } @@ -4233,7 +4381,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int UMINReduce(int[] a, int idx) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.minUnsigned(res, a[i]); } @@ -4242,7 +4390,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int UMINReduceAll(int[] a) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4254,20 +4402,15 @@ public class Int512VectorTests extends AbstractVectorTest { static void UMINReduceInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + int v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (int) VectorMath.minUnsigned(ra, v); } } @@ -4275,8 +4418,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::UMINReduce, Int512VectorTests::UMINReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = UMIN_IDENTITY; + + Assert.assertEquals((int) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static int UMINReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.minUnsigned(res, a[i]); @@ -4286,7 +4452,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int UMINReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4300,20 +4466,15 @@ public class Int512VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + int v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (int) VectorMath.minUnsigned(ra, v); } } @@ -4322,7 +4483,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int UMAXReduce(int[] a, int idx) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.maxUnsigned(res, a[i]); } @@ -4331,7 +4492,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int UMAXReduceAll(int[] a) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4343,20 +4504,15 @@ public class Int512VectorTests extends AbstractVectorTest { static void UMAXReduceInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + int v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (int) VectorMath.maxUnsigned(ra, v); } } @@ -4364,8 +4520,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::UMAXReduce, Int512VectorTests::UMAXReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = UMAX_IDENTITY; + + Assert.assertEquals((int) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static int UMAXReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.maxUnsigned(res, a[i]); @@ -4375,7 +4554,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int UMAXReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4389,20 +4568,15 @@ public class Int512VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + int v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (int) VectorMath.maxUnsigned(ra, v); } } @@ -4411,7 +4585,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduce(int[] a, int idx) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4420,7 +4594,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduceAll(int[] a) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4432,20 +4606,15 @@ public class Int512VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = (int) 0; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (int) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + int v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4453,8 +4622,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::FIRST_NONZEROReduce, Int512VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static int FIRST_NONZEROReduceMasked(int[] a, int idx, boolean[] mask) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4464,7 +4656,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduceAllMasked(int[] a, boolean[] mask) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4478,20 +4670,15 @@ public class Int512VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = (int) 0; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (int) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + int v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4548,7 +4735,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int SUADDReduce(int[] a, int idx) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4557,7 +4744,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int SUADDReduceAll(int[] a) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4572,17 +4759,12 @@ public class Int512VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + int v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (int) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4590,8 +4772,31 @@ public class Int512VectorTests extends AbstractVectorTest { Int512VectorTests::SUADDReduce, Int512VectorTests::SUADDReduceAll); } + @Test(dataProvider = "intSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = SUADD_IDENTITY; + + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static int SUADDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4601,7 +4806,7 @@ public class Int512VectorTests extends AbstractVectorTest { } static int SUADDReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4617,17 +4822,12 @@ public class Int512VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + int v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (int) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6434,6 +6634,157 @@ public class Int512VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Int512VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandInt512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int512VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorInt512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int512VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorInt512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int512VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotInt512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int512VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqInt512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int512VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotInt512VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Int512VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongInt512VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "intCompareOpProvider") static void ltInt512VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { int[] a = fa.apply(SPECIES.length()); @@ -6733,115 +7084,22 @@ public class Int512VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsInt512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsInt512VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndInt512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int512VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrInt512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int512VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorInt512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int512VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotInt512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int512VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqInt512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int512VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeInt512VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6946,23 +7204,6 @@ public class Int512VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongInt512VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Int64VectorTests.java b/test/jdk/jdk/incubator/vector/Int64VectorTests.java index f87a0eb458c..d64db80b94d 100644 --- a/test/jdk/jdk/incubator/vector/Int64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Int64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Int64VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final int CONST_SHIFT = Integer.SIZE / 2; + // Identity values for reduction operations + private static final int ADD_IDENTITY = (int)0; + private static final int AND_IDENTITY = (int)-1; + private static final int FIRST_NONZERO_IDENTITY = (int)0; + private static final int MAX_IDENTITY = Integer.MIN_VALUE; + private static final int MIN_IDENTITY = Integer.MAX_VALUE; + private static final int MUL_IDENTITY = (int)1; + private static final int OR_IDENTITY = (int)0; + private static final int SUADD_IDENTITY = (int)0; + private static final int UMAX_IDENTITY = (int)0; // Minimum unsigned value + private static final int UMIN_IDENTITY = (int)-1; // Maximum unsigned value + private static final int XOR_IDENTITY = (int)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 64); static void assertArraysStrictlyEquals(int[] r, int[] a) { @@ -393,6 +405,36 @@ public class Int64VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { int apply(int a, int b); } @@ -1222,8 +1264,23 @@ public class Int64VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3610,7 +3667,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int ANDReduce(int[] a, int idx) { - int res = -1; + int res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3619,7 +3676,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int ANDReduceAll(int[] a) { - int res = -1; + int res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3631,20 +3688,15 @@ public class Int64VectorTests extends AbstractVectorTest { static void ANDReduceInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = -1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + int v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3652,8 +3704,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::ANDReduce, Int64VectorTests::ANDReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = AND_IDENTITY; + + Assert.assertEquals((int) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id & x), x); + Assert.assertEquals((int) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static int ANDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = -1; + int res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3663,7 +3738,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int ANDReduceAllMasked(int[] a, boolean[] mask) { - int res = -1; + int res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3677,20 +3752,15 @@ public class Int64VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = -1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + int v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3699,7 +3769,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int ORReduce(int[] a, int idx) { - int res = 0; + int res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3708,7 +3778,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int ORReduceAll(int[] a) { - int res = 0; + int res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3723,17 +3793,12 @@ public class Int64VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + int v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3741,8 +3806,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::ORReduce, Int64VectorTests::ORReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = OR_IDENTITY; + + Assert.assertEquals((int) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id | x), x); + Assert.assertEquals((int) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static int ORReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3752,7 +3840,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int ORReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3769,17 +3857,12 @@ public class Int64VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + int v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3788,7 +3871,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int XORReduce(int[] a, int idx) { - int res = 0; + int res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3797,7 +3880,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int XORReduceAll(int[] a) { - int res = 0; + int res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3812,17 +3895,12 @@ public class Int64VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + int v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3830,8 +3908,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::XORReduce, Int64VectorTests::XORReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = XOR_IDENTITY; + + Assert.assertEquals((int) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id ^ x), x); + Assert.assertEquals((int) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static int XORReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3841,7 +3942,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int XORReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3858,17 +3959,12 @@ public class Int64VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + int v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3877,7 +3973,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int ADDReduce(int[] a, int idx) { - int res = 0; + int res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3886,7 +3982,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int ADDReduceAll(int[] a) { - int res = 0; + int res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3901,17 +3997,12 @@ public class Int64VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + int v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3919,8 +4010,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::ADDReduce, Int64VectorTests::ADDReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = ADD_IDENTITY; + + Assert.assertEquals((int) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id + x), x); + Assert.assertEquals((int) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static int ADDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3930,7 +4044,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int ADDReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3947,17 +4061,12 @@ public class Int64VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + int v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3966,7 +4075,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int MULReduce(int[] a, int idx) { - int res = 1; + int res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3975,7 +4084,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int MULReduceAll(int[] a) { - int res = 1; + int res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3987,20 +4096,15 @@ public class Int64VectorTests extends AbstractVectorTest { static void MULReduceInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = 1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + int v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -4008,8 +4112,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::MULReduce, Int64VectorTests::MULReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MUL_IDENTITY; + + Assert.assertEquals((int) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id * x), x); + Assert.assertEquals((int) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static int MULReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 1; + int res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -4019,7 +4146,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int MULReduceAllMasked(int[] a, boolean[] mask) { - int res = 1; + int res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -4033,20 +4160,15 @@ public class Int64VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = 1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + int v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4055,7 +4177,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int MINReduce(int[] a, int idx) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) Math.min(res, a[i]); } @@ -4064,7 +4186,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int MINReduceAll(int[] a) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.min(res, MINReduce(a, i)); } @@ -4076,20 +4198,15 @@ public class Int64VectorTests extends AbstractVectorTest { static void MINReduceInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + int v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (int) Math.min(ra, v); } } @@ -4097,8 +4214,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::MINReduce, Int64VectorTests::MINReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MIN_IDENTITY; + + Assert.assertEquals((int) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) Math.min(id, x), x); + Assert.assertEquals((int) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static int MINReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) Math.min(res, a[i]); @@ -4108,7 +4248,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int MINReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4122,20 +4262,15 @@ public class Int64VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + int v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (int) Math.min(ra, v); } } @@ -4144,7 +4279,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int MAXReduce(int[] a, int idx) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) Math.max(res, a[i]); } @@ -4153,7 +4288,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int MAXReduceAll(int[] a) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.max(res, MAXReduce(a, i)); } @@ -4165,20 +4300,15 @@ public class Int64VectorTests extends AbstractVectorTest { static void MAXReduceInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + int v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (int) Math.max(ra, v); } } @@ -4186,8 +4316,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::MAXReduce, Int64VectorTests::MAXReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MAX_IDENTITY; + + Assert.assertEquals((int) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) Math.max(id, x), x); + Assert.assertEquals((int) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static int MAXReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) Math.max(res, a[i]); @@ -4197,7 +4350,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int MAXReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4211,20 +4364,15 @@ public class Int64VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + int v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (int) Math.max(ra, v); } } @@ -4233,7 +4381,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int UMINReduce(int[] a, int idx) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.minUnsigned(res, a[i]); } @@ -4242,7 +4390,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int UMINReduceAll(int[] a) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4254,20 +4402,15 @@ public class Int64VectorTests extends AbstractVectorTest { static void UMINReduceInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + int v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (int) VectorMath.minUnsigned(ra, v); } } @@ -4275,8 +4418,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::UMINReduce, Int64VectorTests::UMINReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = UMIN_IDENTITY; + + Assert.assertEquals((int) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static int UMINReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.minUnsigned(res, a[i]); @@ -4286,7 +4452,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int UMINReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4300,20 +4466,15 @@ public class Int64VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + int v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (int) VectorMath.minUnsigned(ra, v); } } @@ -4322,7 +4483,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int UMAXReduce(int[] a, int idx) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.maxUnsigned(res, a[i]); } @@ -4331,7 +4492,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int UMAXReduceAll(int[] a) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4343,20 +4504,15 @@ public class Int64VectorTests extends AbstractVectorTest { static void UMAXReduceInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + int v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (int) VectorMath.maxUnsigned(ra, v); } } @@ -4364,8 +4520,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::UMAXReduce, Int64VectorTests::UMAXReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = UMAX_IDENTITY; + + Assert.assertEquals((int) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static int UMAXReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.maxUnsigned(res, a[i]); @@ -4375,7 +4554,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int UMAXReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4389,20 +4568,15 @@ public class Int64VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + int v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (int) VectorMath.maxUnsigned(ra, v); } } @@ -4411,7 +4585,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduce(int[] a, int idx) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4420,7 +4594,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduceAll(int[] a) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4432,20 +4606,15 @@ public class Int64VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = (int) 0; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (int) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + int v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4453,8 +4622,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::FIRST_NONZEROReduce, Int64VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static int FIRST_NONZEROReduceMasked(int[] a, int idx, boolean[] mask) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4464,7 +4656,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduceAllMasked(int[] a, boolean[] mask) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4478,20 +4670,15 @@ public class Int64VectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = (int) 0; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (int) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + int v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4548,7 +4735,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int SUADDReduce(int[] a, int idx) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4557,7 +4744,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int SUADDReduceAll(int[] a) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4572,17 +4759,12 @@ public class Int64VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + int v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (int) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4590,8 +4772,31 @@ public class Int64VectorTests extends AbstractVectorTest { Int64VectorTests::SUADDReduce, Int64VectorTests::SUADDReduceAll); } + @Test(dataProvider = "intSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = SUADD_IDENTITY; + + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static int SUADDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4601,7 +4806,7 @@ public class Int64VectorTests extends AbstractVectorTest { } static int SUADDReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4617,17 +4822,12 @@ public class Int64VectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + int v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (int) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6434,6 +6634,157 @@ public class Int64VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Int64VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandInt64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int64VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorInt64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int64VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorInt64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int64VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotInt64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int64VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqInt64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Int64VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotInt64VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Int64VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongInt64VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "intCompareOpProvider") static void ltInt64VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { int[] a = fa.apply(SPECIES.length()); @@ -6733,115 +7084,22 @@ public class Int64VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsInt64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsInt64VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndInt64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int64VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrInt64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int64VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorInt64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int64VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotInt64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int64VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqInt64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Int64VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeInt64VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6946,23 +7204,6 @@ public class Int64VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongInt64VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java b/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java index c61aab0013e..7bf4dc48171 100644 --- a/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -71,6 +71,19 @@ public class IntMaxVectorTests extends AbstractVectorTest { private static final int CONST_SHIFT = Integer.SIZE / 2; + // Identity values for reduction operations + private static final int ADD_IDENTITY = (int)0; + private static final int AND_IDENTITY = (int)-1; + private static final int FIRST_NONZERO_IDENTITY = (int)0; + private static final int MAX_IDENTITY = Integer.MIN_VALUE; + private static final int MIN_IDENTITY = Integer.MAX_VALUE; + private static final int MUL_IDENTITY = (int)1; + private static final int OR_IDENTITY = (int)0; + private static final int SUADD_IDENTITY = (int)0; + private static final int UMAX_IDENTITY = (int)0; // Minimum unsigned value + private static final int UMIN_IDENTITY = (int)-1; // Maximum unsigned value + private static final int XOR_IDENTITY = (int)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / Max); static void assertArraysStrictlyEquals(int[] r, int[] a) { @@ -398,6 +411,36 @@ public class IntMaxVectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { int apply(int a, int b); } @@ -1227,8 +1270,23 @@ public class IntMaxVectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3615,7 +3673,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int ANDReduce(int[] a, int idx) { - int res = -1; + int res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3624,7 +3682,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int ANDReduceAll(int[] a) { - int res = -1; + int res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3636,20 +3694,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { static void ANDReduceIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = -1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + int v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3657,8 +3710,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::ANDReduce, IntMaxVectorTests::ANDReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = AND_IDENTITY; + + Assert.assertEquals((int) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id & x), x); + Assert.assertEquals((int) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static int ANDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = -1; + int res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3668,7 +3744,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int ANDReduceAllMasked(int[] a, boolean[] mask) { - int res = -1; + int res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3682,20 +3758,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = -1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + int v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3704,7 +3775,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int ORReduce(int[] a, int idx) { - int res = 0; + int res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3713,7 +3784,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int ORReduceAll(int[] a) { - int res = 0; + int res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3728,17 +3799,12 @@ public class IntMaxVectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + int v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3746,8 +3812,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::ORReduce, IntMaxVectorTests::ORReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = OR_IDENTITY; + + Assert.assertEquals((int) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id | x), x); + Assert.assertEquals((int) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static int ORReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3757,7 +3846,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int ORReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3774,17 +3863,12 @@ public class IntMaxVectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + int v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3793,7 +3877,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int XORReduce(int[] a, int idx) { - int res = 0; + int res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3802,7 +3886,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int XORReduceAll(int[] a) { - int res = 0; + int res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3817,17 +3901,12 @@ public class IntMaxVectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + int v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3835,8 +3914,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::XORReduce, IntMaxVectorTests::XORReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = XOR_IDENTITY; + + Assert.assertEquals((int) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id ^ x), x); + Assert.assertEquals((int) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static int XORReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3846,7 +3948,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int XORReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3863,17 +3965,12 @@ public class IntMaxVectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + int v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3882,7 +3979,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int ADDReduce(int[] a, int idx) { - int res = 0; + int res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3891,7 +3988,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int ADDReduceAll(int[] a) { - int res = 0; + int res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3906,17 +4003,12 @@ public class IntMaxVectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + int v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3924,8 +4016,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::ADDReduce, IntMaxVectorTests::ADDReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = ADD_IDENTITY; + + Assert.assertEquals((int) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id + x), x); + Assert.assertEquals((int) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static int ADDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3935,7 +4050,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int ADDReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3952,17 +4067,12 @@ public class IntMaxVectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + int v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3971,7 +4081,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int MULReduce(int[] a, int idx) { - int res = 1; + int res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3980,7 +4090,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int MULReduceAll(int[] a) { - int res = 1; + int res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3992,20 +4102,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { static void MULReduceIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = 1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + int v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -4013,8 +4118,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::MULReduce, IntMaxVectorTests::MULReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MUL_IDENTITY; + + Assert.assertEquals((int) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) (id * x), x); + Assert.assertEquals((int) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static int MULReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 1; + int res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -4024,7 +4152,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int MULReduceAllMasked(int[] a, boolean[] mask) { - int res = 1; + int res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -4038,20 +4166,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = 1; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + int v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4060,7 +4183,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int MINReduce(int[] a, int idx) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) Math.min(res, a[i]); } @@ -4069,7 +4192,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int MINReduceAll(int[] a) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.min(res, MINReduce(a, i)); } @@ -4081,20 +4204,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { static void MINReduceIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + int v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (int) Math.min(ra, v); } } @@ -4102,8 +4220,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::MINReduce, IntMaxVectorTests::MINReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MIN_IDENTITY; + + Assert.assertEquals((int) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) Math.min(id, x), x); + Assert.assertEquals((int) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static int MINReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) Math.min(res, a[i]); @@ -4113,7 +4254,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int MINReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4127,20 +4268,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + int v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (int) Math.min(ra, v); } } @@ -4149,7 +4285,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int MAXReduce(int[] a, int idx) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) Math.max(res, a[i]); } @@ -4158,7 +4294,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int MAXReduceAll(int[] a) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.max(res, MAXReduce(a, i)); } @@ -4170,20 +4306,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { static void MAXReduceIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + int v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (int) Math.max(ra, v); } } @@ -4191,8 +4322,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::MAXReduce, IntMaxVectorTests::MAXReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = MAX_IDENTITY; + + Assert.assertEquals((int) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) Math.max(id, x), x); + Assert.assertEquals((int) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static int MAXReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) Math.max(res, a[i]); @@ -4202,7 +4356,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int MAXReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4216,20 +4370,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + int v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (int) Math.max(ra, v); } } @@ -4238,7 +4387,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int UMINReduce(int[] a, int idx) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.minUnsigned(res, a[i]); } @@ -4247,7 +4396,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int UMINReduceAll(int[] a) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4259,20 +4408,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { static void UMINReduceIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + int v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (int) VectorMath.minUnsigned(ra, v); } } @@ -4280,8 +4424,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::UMINReduce, IntMaxVectorTests::UMINReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = UMIN_IDENTITY; + + Assert.assertEquals((int) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static int UMINReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.minUnsigned(res, a[i]); @@ -4291,7 +4458,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int UMINReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MAX_VALUE; + int res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4305,20 +4472,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MAX_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + int v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (int) VectorMath.minUnsigned(ra, v); } } @@ -4327,7 +4489,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int UMAXReduce(int[] a, int idx) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.maxUnsigned(res, a[i]); } @@ -4336,7 +4498,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int UMAXReduceAll(int[] a) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4348,20 +4510,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { static void UMAXReduceIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + int v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (int) VectorMath.maxUnsigned(ra, v); } } @@ -4369,8 +4526,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::UMAXReduce, IntMaxVectorTests::UMAXReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = UMAX_IDENTITY; + + Assert.assertEquals((int) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static int UMAXReduceMasked(int[] a, int idx, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.maxUnsigned(res, a[i]); @@ -4380,7 +4560,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int UMAXReduceAllMasked(int[] a, boolean[] mask) { - int res = Integer.MIN_VALUE; + int res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4394,20 +4574,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = Integer.MIN_VALUE; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Integer.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + int v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (int) VectorMath.maxUnsigned(ra, v); } } @@ -4416,7 +4591,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduce(int[] a, int idx) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4425,7 +4600,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduceAll(int[] a) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4437,20 +4612,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = fr.apply(SPECIES.length()); - int ra = (int) 0; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (int) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + int v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4458,8 +4628,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::FIRST_NONZEROReduce, IntMaxVectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "intUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static int FIRST_NONZEROReduceMasked(int[] a, int idx, boolean[] mask) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4469,7 +4662,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int FIRST_NONZEROReduceAllMasked(int[] a, boolean[] mask) { - int res = (int) 0; + int res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4483,20 +4676,15 @@ public class IntMaxVectorTests extends AbstractVectorTest { int[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - int ra = (int) 0; + int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (int) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + int v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4553,7 +4741,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int SUADDReduce(int[] a, int idx) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (int) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4562,7 +4750,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int SUADDReduceAll(int[] a) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4577,17 +4765,12 @@ public class IntMaxVectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + int v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (int) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4595,8 +4778,31 @@ public class IntMaxVectorTests extends AbstractVectorTest { IntMaxVectorTests::SUADDReduce, IntMaxVectorTests::SUADDReduceAll); } + @Test(dataProvider = "intSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + int[] a = fa.apply(SPECIES.length()); + int id = SUADD_IDENTITY; + + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + int x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((int) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static int SUADDReduceMasked(int[] a, int idx, boolean[] mask) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (int) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4606,7 +4812,7 @@ public class IntMaxVectorTests extends AbstractVectorTest { } static int SUADDReduceAllMasked(int[] a, boolean[] mask) { - int res = 0; + int res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (int) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4622,17 +4828,12 @@ public class IntMaxVectorTests extends AbstractVectorTest { int ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - IntVector av = IntVector.fromArray(SPECIES, a, i); - ra = (int) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + int v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (int) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6439,6 +6640,157 @@ public class IntMaxVectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, IntMaxVectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandIntMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, IntMaxVectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorIntMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, IntMaxVectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorIntMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, IntMaxVectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotIntMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, IntMaxVectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqIntMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, IntMaxVectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotIntMaxVectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, IntMaxVectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongIntMaxVectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "intCompareOpProvider") static void ltIntMaxVectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { int[] a = fa.apply(SPECIES.length()); @@ -6738,115 +7090,22 @@ public class IntMaxVectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsIntMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsIntMaxVectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndIntMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, IntMaxVectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrIntMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, IntMaxVectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorIntMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, IntMaxVectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotIntMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, IntMaxVectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqIntMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, IntMaxVectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeIntMaxVectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6951,7 +7210,6 @@ public class IntMaxVectorTests extends AbstractVectorTest { } } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Long128VectorTests.java b/test/jdk/jdk/incubator/vector/Long128VectorTests.java index a8cf38c003a..227f196ffdf 100644 --- a/test/jdk/jdk/incubator/vector/Long128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Long128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Long128VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final long CONST_SHIFT = Long.SIZE / 2; + // Identity values for reduction operations + private static final long ADD_IDENTITY = (long)0; + private static final long AND_IDENTITY = (long)-1; + private static final long FIRST_NONZERO_IDENTITY = (long)0; + private static final long MAX_IDENTITY = Long.MIN_VALUE; + private static final long MIN_IDENTITY = Long.MAX_VALUE; + private static final long MUL_IDENTITY = (long)1; + private static final long OR_IDENTITY = (long)0; + private static final long SUADD_IDENTITY = (long)0; + private static final long UMAX_IDENTITY = (long)0; // Minimum unsigned value + private static final long UMIN_IDENTITY = (long)-1; // Maximum unsigned value + private static final long XOR_IDENTITY = (long)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 128); static void assertArraysStrictlyEquals(long[] r, long[] a) { @@ -350,6 +362,36 @@ public class Long128VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { long apply(long a, long b); } @@ -1219,8 +1261,23 @@ public class Long128VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3632,7 +3689,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long ANDReduce(long[] a, int idx) { - long res = -1; + long res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3641,7 +3698,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long ANDReduceAll(long[] a) { - long res = -1; + long res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3653,20 +3710,15 @@ public class Long128VectorTests extends AbstractVectorTest { static void ANDReduceLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = -1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + long v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3674,8 +3726,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::ANDReduce, Long128VectorTests::ANDReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = AND_IDENTITY; + + Assert.assertEquals((long) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id & x), x); + Assert.assertEquals((long) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static long ANDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = -1; + long res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3685,7 +3760,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long ANDReduceAllMasked(long[] a, boolean[] mask) { - long res = -1; + long res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3699,20 +3774,15 @@ public class Long128VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = -1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + long v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3721,7 +3791,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long ORReduce(long[] a, int idx) { - long res = 0; + long res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3730,7 +3800,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long ORReduceAll(long[] a) { - long res = 0; + long res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3745,17 +3815,12 @@ public class Long128VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + long v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3763,8 +3828,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::ORReduce, Long128VectorTests::ORReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = OR_IDENTITY; + + Assert.assertEquals((long) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id | x), x); + Assert.assertEquals((long) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static long ORReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3774,7 +3862,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long ORReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3791,17 +3879,12 @@ public class Long128VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + long v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3810,7 +3893,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long XORReduce(long[] a, int idx) { - long res = 0; + long res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3819,7 +3902,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long XORReduceAll(long[] a) { - long res = 0; + long res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3834,17 +3917,12 @@ public class Long128VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + long v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3852,8 +3930,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::XORReduce, Long128VectorTests::XORReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = XOR_IDENTITY; + + Assert.assertEquals((long) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id ^ x), x); + Assert.assertEquals((long) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static long XORReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3863,7 +3964,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long XORReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3880,17 +3981,12 @@ public class Long128VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + long v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3899,7 +3995,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long ADDReduce(long[] a, int idx) { - long res = 0; + long res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3908,7 +4004,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long ADDReduceAll(long[] a) { - long res = 0; + long res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3923,17 +4019,12 @@ public class Long128VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + long v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3941,8 +4032,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::ADDReduce, Long128VectorTests::ADDReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = ADD_IDENTITY; + + Assert.assertEquals((long) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id + x), x); + Assert.assertEquals((long) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static long ADDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3952,7 +4066,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long ADDReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3969,17 +4083,12 @@ public class Long128VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + long v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3988,7 +4097,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long MULReduce(long[] a, int idx) { - long res = 1; + long res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3997,7 +4106,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long MULReduceAll(long[] a) { - long res = 1; + long res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -4009,20 +4118,15 @@ public class Long128VectorTests extends AbstractVectorTest { static void MULReduceLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = 1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + long v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -4030,8 +4134,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::MULReduce, Long128VectorTests::MULReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MUL_IDENTITY; + + Assert.assertEquals((long) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id * x), x); + Assert.assertEquals((long) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static long MULReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 1; + long res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -4041,7 +4168,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long MULReduceAllMasked(long[] a, boolean[] mask) { - long res = 1; + long res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -4055,20 +4182,15 @@ public class Long128VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = 1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + long v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4077,7 +4199,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long MINReduce(long[] a, int idx) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) Math.min(res, a[i]); } @@ -4086,7 +4208,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long MINReduceAll(long[] a) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.min(res, MINReduce(a, i)); } @@ -4098,20 +4220,15 @@ public class Long128VectorTests extends AbstractVectorTest { static void MINReduceLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + long v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (long) Math.min(ra, v); } } @@ -4119,8 +4236,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::MINReduce, Long128VectorTests::MINReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MIN_IDENTITY; + + Assert.assertEquals((long) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) Math.min(id, x), x); + Assert.assertEquals((long) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static long MINReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) Math.min(res, a[i]); @@ -4130,7 +4270,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long MINReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4144,20 +4284,15 @@ public class Long128VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + long v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (long) Math.min(ra, v); } } @@ -4166,7 +4301,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long MAXReduce(long[] a, int idx) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) Math.max(res, a[i]); } @@ -4175,7 +4310,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long MAXReduceAll(long[] a) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.max(res, MAXReduce(a, i)); } @@ -4187,20 +4322,15 @@ public class Long128VectorTests extends AbstractVectorTest { static void MAXReduceLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + long v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (long) Math.max(ra, v); } } @@ -4208,8 +4338,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::MAXReduce, Long128VectorTests::MAXReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MAX_IDENTITY; + + Assert.assertEquals((long) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) Math.max(id, x), x); + Assert.assertEquals((long) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static long MAXReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) Math.max(res, a[i]); @@ -4219,7 +4372,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long MAXReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4233,20 +4386,15 @@ public class Long128VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + long v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (long) Math.max(ra, v); } } @@ -4255,7 +4403,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long UMINReduce(long[] a, int idx) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.minUnsigned(res, a[i]); } @@ -4264,7 +4412,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long UMINReduceAll(long[] a) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4276,20 +4424,15 @@ public class Long128VectorTests extends AbstractVectorTest { static void UMINReduceLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + long v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (long) VectorMath.minUnsigned(ra, v); } } @@ -4297,8 +4440,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::UMINReduce, Long128VectorTests::UMINReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = UMIN_IDENTITY; + + Assert.assertEquals((long) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static long UMINReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.minUnsigned(res, a[i]); @@ -4308,7 +4474,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long UMINReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4322,20 +4488,15 @@ public class Long128VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + long v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (long) VectorMath.minUnsigned(ra, v); } } @@ -4344,7 +4505,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long UMAXReduce(long[] a, int idx) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.maxUnsigned(res, a[i]); } @@ -4353,7 +4514,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long UMAXReduceAll(long[] a) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4365,20 +4526,15 @@ public class Long128VectorTests extends AbstractVectorTest { static void UMAXReduceLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + long v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (long) VectorMath.maxUnsigned(ra, v); } } @@ -4386,8 +4542,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::UMAXReduce, Long128VectorTests::UMAXReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = UMAX_IDENTITY; + + Assert.assertEquals((long) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static long UMAXReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.maxUnsigned(res, a[i]); @@ -4397,7 +4576,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long UMAXReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4411,20 +4590,15 @@ public class Long128VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + long v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (long) VectorMath.maxUnsigned(ra, v); } } @@ -4433,7 +4607,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduce(long[] a, int idx) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4442,7 +4616,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduceAll(long[] a) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4454,20 +4628,15 @@ public class Long128VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = (long) 0; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (long) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + long v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4475,8 +4644,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::FIRST_NONZEROReduce, Long128VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static long FIRST_NONZEROReduceMasked(long[] a, int idx, boolean[] mask) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4486,7 +4678,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduceAllMasked(long[] a, boolean[] mask) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4500,20 +4692,15 @@ public class Long128VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = (long) 0; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (long) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + long v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4570,7 +4757,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long SUADDReduce(long[] a, int idx) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4579,7 +4766,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long SUADDReduceAll(long[] a) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4594,17 +4781,12 @@ public class Long128VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + long v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (long) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4612,8 +4794,31 @@ public class Long128VectorTests extends AbstractVectorTest { Long128VectorTests::SUADDReduce, Long128VectorTests::SUADDReduceAll); } + @Test(dataProvider = "longSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = SUADD_IDENTITY; + + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static long SUADDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4623,7 +4828,7 @@ public class Long128VectorTests extends AbstractVectorTest { } static long SUADDReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4639,17 +4844,12 @@ public class Long128VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + long v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (long) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6386,6 +6586,157 @@ public class Long128VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Long128VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandLong128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long128VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorLong128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long128VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorLong128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long128VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotLong128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long128VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqLong128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long128VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotLong128VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Long128VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongLong128VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "longCompareOpProvider") static void ltLong128VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { long[] a = fa.apply(SPECIES.length()); @@ -6619,115 +6970,22 @@ public class Long128VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsLong128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsLong128VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndLong128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long128VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrLong128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long128VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorLong128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long128VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotLong128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long128VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqLong128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long128VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeLong128VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6832,23 +7090,6 @@ public class Long128VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongLong128VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Long256VectorTests.java b/test/jdk/jdk/incubator/vector/Long256VectorTests.java index a394a59699f..c37e68e3728 100644 --- a/test/jdk/jdk/incubator/vector/Long256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Long256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Long256VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final long CONST_SHIFT = Long.SIZE / 2; + // Identity values for reduction operations + private static final long ADD_IDENTITY = (long)0; + private static final long AND_IDENTITY = (long)-1; + private static final long FIRST_NONZERO_IDENTITY = (long)0; + private static final long MAX_IDENTITY = Long.MIN_VALUE; + private static final long MIN_IDENTITY = Long.MAX_VALUE; + private static final long MUL_IDENTITY = (long)1; + private static final long OR_IDENTITY = (long)0; + private static final long SUADD_IDENTITY = (long)0; + private static final long UMAX_IDENTITY = (long)0; // Minimum unsigned value + private static final long UMIN_IDENTITY = (long)-1; // Maximum unsigned value + private static final long XOR_IDENTITY = (long)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 256); static void assertArraysStrictlyEquals(long[] r, long[] a) { @@ -350,6 +362,36 @@ public class Long256VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { long apply(long a, long b); } @@ -1219,8 +1261,23 @@ public class Long256VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3632,7 +3689,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long ANDReduce(long[] a, int idx) { - long res = -1; + long res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3641,7 +3698,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long ANDReduceAll(long[] a) { - long res = -1; + long res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3653,20 +3710,15 @@ public class Long256VectorTests extends AbstractVectorTest { static void ANDReduceLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = -1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + long v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3674,8 +3726,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::ANDReduce, Long256VectorTests::ANDReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = AND_IDENTITY; + + Assert.assertEquals((long) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id & x), x); + Assert.assertEquals((long) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static long ANDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = -1; + long res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3685,7 +3760,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long ANDReduceAllMasked(long[] a, boolean[] mask) { - long res = -1; + long res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3699,20 +3774,15 @@ public class Long256VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = -1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + long v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3721,7 +3791,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long ORReduce(long[] a, int idx) { - long res = 0; + long res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3730,7 +3800,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long ORReduceAll(long[] a) { - long res = 0; + long res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3745,17 +3815,12 @@ public class Long256VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + long v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3763,8 +3828,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::ORReduce, Long256VectorTests::ORReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = OR_IDENTITY; + + Assert.assertEquals((long) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id | x), x); + Assert.assertEquals((long) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static long ORReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3774,7 +3862,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long ORReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3791,17 +3879,12 @@ public class Long256VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + long v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3810,7 +3893,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long XORReduce(long[] a, int idx) { - long res = 0; + long res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3819,7 +3902,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long XORReduceAll(long[] a) { - long res = 0; + long res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3834,17 +3917,12 @@ public class Long256VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + long v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3852,8 +3930,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::XORReduce, Long256VectorTests::XORReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = XOR_IDENTITY; + + Assert.assertEquals((long) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id ^ x), x); + Assert.assertEquals((long) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static long XORReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3863,7 +3964,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long XORReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3880,17 +3981,12 @@ public class Long256VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + long v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3899,7 +3995,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long ADDReduce(long[] a, int idx) { - long res = 0; + long res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3908,7 +4004,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long ADDReduceAll(long[] a) { - long res = 0; + long res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3923,17 +4019,12 @@ public class Long256VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + long v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3941,8 +4032,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::ADDReduce, Long256VectorTests::ADDReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = ADD_IDENTITY; + + Assert.assertEquals((long) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id + x), x); + Assert.assertEquals((long) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static long ADDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3952,7 +4066,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long ADDReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3969,17 +4083,12 @@ public class Long256VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + long v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3988,7 +4097,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long MULReduce(long[] a, int idx) { - long res = 1; + long res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3997,7 +4106,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long MULReduceAll(long[] a) { - long res = 1; + long res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -4009,20 +4118,15 @@ public class Long256VectorTests extends AbstractVectorTest { static void MULReduceLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = 1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + long v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -4030,8 +4134,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::MULReduce, Long256VectorTests::MULReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MUL_IDENTITY; + + Assert.assertEquals((long) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id * x), x); + Assert.assertEquals((long) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static long MULReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 1; + long res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -4041,7 +4168,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long MULReduceAllMasked(long[] a, boolean[] mask) { - long res = 1; + long res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -4055,20 +4182,15 @@ public class Long256VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = 1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + long v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4077,7 +4199,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long MINReduce(long[] a, int idx) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) Math.min(res, a[i]); } @@ -4086,7 +4208,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long MINReduceAll(long[] a) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.min(res, MINReduce(a, i)); } @@ -4098,20 +4220,15 @@ public class Long256VectorTests extends AbstractVectorTest { static void MINReduceLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + long v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (long) Math.min(ra, v); } } @@ -4119,8 +4236,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::MINReduce, Long256VectorTests::MINReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MIN_IDENTITY; + + Assert.assertEquals((long) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) Math.min(id, x), x); + Assert.assertEquals((long) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static long MINReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) Math.min(res, a[i]); @@ -4130,7 +4270,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long MINReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4144,20 +4284,15 @@ public class Long256VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + long v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (long) Math.min(ra, v); } } @@ -4166,7 +4301,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long MAXReduce(long[] a, int idx) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) Math.max(res, a[i]); } @@ -4175,7 +4310,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long MAXReduceAll(long[] a) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.max(res, MAXReduce(a, i)); } @@ -4187,20 +4322,15 @@ public class Long256VectorTests extends AbstractVectorTest { static void MAXReduceLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + long v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (long) Math.max(ra, v); } } @@ -4208,8 +4338,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::MAXReduce, Long256VectorTests::MAXReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MAX_IDENTITY; + + Assert.assertEquals((long) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) Math.max(id, x), x); + Assert.assertEquals((long) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static long MAXReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) Math.max(res, a[i]); @@ -4219,7 +4372,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long MAXReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4233,20 +4386,15 @@ public class Long256VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + long v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (long) Math.max(ra, v); } } @@ -4255,7 +4403,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long UMINReduce(long[] a, int idx) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.minUnsigned(res, a[i]); } @@ -4264,7 +4412,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long UMINReduceAll(long[] a) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4276,20 +4424,15 @@ public class Long256VectorTests extends AbstractVectorTest { static void UMINReduceLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + long v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (long) VectorMath.minUnsigned(ra, v); } } @@ -4297,8 +4440,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::UMINReduce, Long256VectorTests::UMINReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = UMIN_IDENTITY; + + Assert.assertEquals((long) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static long UMINReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.minUnsigned(res, a[i]); @@ -4308,7 +4474,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long UMINReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4322,20 +4488,15 @@ public class Long256VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + long v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (long) VectorMath.minUnsigned(ra, v); } } @@ -4344,7 +4505,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long UMAXReduce(long[] a, int idx) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.maxUnsigned(res, a[i]); } @@ -4353,7 +4514,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long UMAXReduceAll(long[] a) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4365,20 +4526,15 @@ public class Long256VectorTests extends AbstractVectorTest { static void UMAXReduceLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + long v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (long) VectorMath.maxUnsigned(ra, v); } } @@ -4386,8 +4542,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::UMAXReduce, Long256VectorTests::UMAXReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = UMAX_IDENTITY; + + Assert.assertEquals((long) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static long UMAXReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.maxUnsigned(res, a[i]); @@ -4397,7 +4576,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long UMAXReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4411,20 +4590,15 @@ public class Long256VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + long v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (long) VectorMath.maxUnsigned(ra, v); } } @@ -4433,7 +4607,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduce(long[] a, int idx) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4442,7 +4616,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduceAll(long[] a) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4454,20 +4628,15 @@ public class Long256VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = (long) 0; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (long) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + long v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4475,8 +4644,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::FIRST_NONZEROReduce, Long256VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static long FIRST_NONZEROReduceMasked(long[] a, int idx, boolean[] mask) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4486,7 +4678,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduceAllMasked(long[] a, boolean[] mask) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4500,20 +4692,15 @@ public class Long256VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = (long) 0; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (long) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + long v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4570,7 +4757,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long SUADDReduce(long[] a, int idx) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4579,7 +4766,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long SUADDReduceAll(long[] a) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4594,17 +4781,12 @@ public class Long256VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + long v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (long) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4612,8 +4794,31 @@ public class Long256VectorTests extends AbstractVectorTest { Long256VectorTests::SUADDReduce, Long256VectorTests::SUADDReduceAll); } + @Test(dataProvider = "longSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = SUADD_IDENTITY; + + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static long SUADDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4623,7 +4828,7 @@ public class Long256VectorTests extends AbstractVectorTest { } static long SUADDReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4639,17 +4844,12 @@ public class Long256VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + long v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (long) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6386,6 +6586,157 @@ public class Long256VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Long256VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandLong256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long256VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorLong256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long256VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorLong256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long256VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotLong256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long256VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqLong256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long256VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotLong256VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Long256VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongLong256VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "longCompareOpProvider") static void ltLong256VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { long[] a = fa.apply(SPECIES.length()); @@ -6619,115 +6970,22 @@ public class Long256VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsLong256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsLong256VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndLong256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long256VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrLong256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long256VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorLong256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long256VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotLong256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long256VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqLong256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long256VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeLong256VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6832,23 +7090,6 @@ public class Long256VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongLong256VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Long512VectorTests.java b/test/jdk/jdk/incubator/vector/Long512VectorTests.java index 2f12ea98399..5f8abb5bdd5 100644 --- a/test/jdk/jdk/incubator/vector/Long512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Long512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Long512VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final long CONST_SHIFT = Long.SIZE / 2; + // Identity values for reduction operations + private static final long ADD_IDENTITY = (long)0; + private static final long AND_IDENTITY = (long)-1; + private static final long FIRST_NONZERO_IDENTITY = (long)0; + private static final long MAX_IDENTITY = Long.MIN_VALUE; + private static final long MIN_IDENTITY = Long.MAX_VALUE; + private static final long MUL_IDENTITY = (long)1; + private static final long OR_IDENTITY = (long)0; + private static final long SUADD_IDENTITY = (long)0; + private static final long UMAX_IDENTITY = (long)0; // Minimum unsigned value + private static final long UMIN_IDENTITY = (long)-1; // Maximum unsigned value + private static final long XOR_IDENTITY = (long)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 512); static void assertArraysStrictlyEquals(long[] r, long[] a) { @@ -350,6 +362,36 @@ public class Long512VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { long apply(long a, long b); } @@ -1219,8 +1261,23 @@ public class Long512VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3632,7 +3689,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long ANDReduce(long[] a, int idx) { - long res = -1; + long res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3641,7 +3698,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long ANDReduceAll(long[] a) { - long res = -1; + long res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3653,20 +3710,15 @@ public class Long512VectorTests extends AbstractVectorTest { static void ANDReduceLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = -1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + long v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3674,8 +3726,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::ANDReduce, Long512VectorTests::ANDReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = AND_IDENTITY; + + Assert.assertEquals((long) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id & x), x); + Assert.assertEquals((long) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static long ANDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = -1; + long res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3685,7 +3760,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long ANDReduceAllMasked(long[] a, boolean[] mask) { - long res = -1; + long res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3699,20 +3774,15 @@ public class Long512VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = -1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + long v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3721,7 +3791,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long ORReduce(long[] a, int idx) { - long res = 0; + long res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3730,7 +3800,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long ORReduceAll(long[] a) { - long res = 0; + long res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3745,17 +3815,12 @@ public class Long512VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + long v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3763,8 +3828,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::ORReduce, Long512VectorTests::ORReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = OR_IDENTITY; + + Assert.assertEquals((long) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id | x), x); + Assert.assertEquals((long) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static long ORReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3774,7 +3862,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long ORReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3791,17 +3879,12 @@ public class Long512VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + long v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3810,7 +3893,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long XORReduce(long[] a, int idx) { - long res = 0; + long res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3819,7 +3902,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long XORReduceAll(long[] a) { - long res = 0; + long res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3834,17 +3917,12 @@ public class Long512VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + long v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3852,8 +3930,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::XORReduce, Long512VectorTests::XORReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = XOR_IDENTITY; + + Assert.assertEquals((long) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id ^ x), x); + Assert.assertEquals((long) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static long XORReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3863,7 +3964,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long XORReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3880,17 +3981,12 @@ public class Long512VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + long v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3899,7 +3995,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long ADDReduce(long[] a, int idx) { - long res = 0; + long res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3908,7 +4004,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long ADDReduceAll(long[] a) { - long res = 0; + long res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3923,17 +4019,12 @@ public class Long512VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + long v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3941,8 +4032,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::ADDReduce, Long512VectorTests::ADDReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = ADD_IDENTITY; + + Assert.assertEquals((long) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id + x), x); + Assert.assertEquals((long) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static long ADDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3952,7 +4066,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long ADDReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3969,17 +4083,12 @@ public class Long512VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + long v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3988,7 +4097,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long MULReduce(long[] a, int idx) { - long res = 1; + long res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3997,7 +4106,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long MULReduceAll(long[] a) { - long res = 1; + long res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -4009,20 +4118,15 @@ public class Long512VectorTests extends AbstractVectorTest { static void MULReduceLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = 1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + long v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -4030,8 +4134,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::MULReduce, Long512VectorTests::MULReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MUL_IDENTITY; + + Assert.assertEquals((long) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id * x), x); + Assert.assertEquals((long) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static long MULReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 1; + long res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -4041,7 +4168,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long MULReduceAllMasked(long[] a, boolean[] mask) { - long res = 1; + long res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -4055,20 +4182,15 @@ public class Long512VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = 1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + long v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4077,7 +4199,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long MINReduce(long[] a, int idx) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) Math.min(res, a[i]); } @@ -4086,7 +4208,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long MINReduceAll(long[] a) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.min(res, MINReduce(a, i)); } @@ -4098,20 +4220,15 @@ public class Long512VectorTests extends AbstractVectorTest { static void MINReduceLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + long v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (long) Math.min(ra, v); } } @@ -4119,8 +4236,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::MINReduce, Long512VectorTests::MINReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MIN_IDENTITY; + + Assert.assertEquals((long) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) Math.min(id, x), x); + Assert.assertEquals((long) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static long MINReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) Math.min(res, a[i]); @@ -4130,7 +4270,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long MINReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4144,20 +4284,15 @@ public class Long512VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + long v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (long) Math.min(ra, v); } } @@ -4166,7 +4301,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long MAXReduce(long[] a, int idx) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) Math.max(res, a[i]); } @@ -4175,7 +4310,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long MAXReduceAll(long[] a) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.max(res, MAXReduce(a, i)); } @@ -4187,20 +4322,15 @@ public class Long512VectorTests extends AbstractVectorTest { static void MAXReduceLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + long v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (long) Math.max(ra, v); } } @@ -4208,8 +4338,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::MAXReduce, Long512VectorTests::MAXReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MAX_IDENTITY; + + Assert.assertEquals((long) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) Math.max(id, x), x); + Assert.assertEquals((long) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static long MAXReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) Math.max(res, a[i]); @@ -4219,7 +4372,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long MAXReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4233,20 +4386,15 @@ public class Long512VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + long v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (long) Math.max(ra, v); } } @@ -4255,7 +4403,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long UMINReduce(long[] a, int idx) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.minUnsigned(res, a[i]); } @@ -4264,7 +4412,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long UMINReduceAll(long[] a) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4276,20 +4424,15 @@ public class Long512VectorTests extends AbstractVectorTest { static void UMINReduceLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + long v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (long) VectorMath.minUnsigned(ra, v); } } @@ -4297,8 +4440,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::UMINReduce, Long512VectorTests::UMINReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = UMIN_IDENTITY; + + Assert.assertEquals((long) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static long UMINReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.minUnsigned(res, a[i]); @@ -4308,7 +4474,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long UMINReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4322,20 +4488,15 @@ public class Long512VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + long v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (long) VectorMath.minUnsigned(ra, v); } } @@ -4344,7 +4505,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long UMAXReduce(long[] a, int idx) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.maxUnsigned(res, a[i]); } @@ -4353,7 +4514,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long UMAXReduceAll(long[] a) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4365,20 +4526,15 @@ public class Long512VectorTests extends AbstractVectorTest { static void UMAXReduceLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + long v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (long) VectorMath.maxUnsigned(ra, v); } } @@ -4386,8 +4542,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::UMAXReduce, Long512VectorTests::UMAXReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = UMAX_IDENTITY; + + Assert.assertEquals((long) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static long UMAXReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.maxUnsigned(res, a[i]); @@ -4397,7 +4576,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long UMAXReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4411,20 +4590,15 @@ public class Long512VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + long v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (long) VectorMath.maxUnsigned(ra, v); } } @@ -4433,7 +4607,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduce(long[] a, int idx) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4442,7 +4616,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduceAll(long[] a) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4454,20 +4628,15 @@ public class Long512VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = (long) 0; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (long) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + long v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4475,8 +4644,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::FIRST_NONZEROReduce, Long512VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static long FIRST_NONZEROReduceMasked(long[] a, int idx, boolean[] mask) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4486,7 +4678,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduceAllMasked(long[] a, boolean[] mask) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4500,20 +4692,15 @@ public class Long512VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = (long) 0; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (long) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + long v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4570,7 +4757,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long SUADDReduce(long[] a, int idx) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4579,7 +4766,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long SUADDReduceAll(long[] a) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4594,17 +4781,12 @@ public class Long512VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + long v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (long) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4612,8 +4794,31 @@ public class Long512VectorTests extends AbstractVectorTest { Long512VectorTests::SUADDReduce, Long512VectorTests::SUADDReduceAll); } + @Test(dataProvider = "longSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = SUADD_IDENTITY; + + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static long SUADDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4623,7 +4828,7 @@ public class Long512VectorTests extends AbstractVectorTest { } static long SUADDReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4639,17 +4844,12 @@ public class Long512VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + long v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (long) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6386,6 +6586,157 @@ public class Long512VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Long512VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandLong512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long512VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorLong512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long512VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorLong512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long512VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotLong512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long512VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqLong512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long512VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotLong512VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Long512VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongLong512VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "longCompareOpProvider") static void ltLong512VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { long[] a = fa.apply(SPECIES.length()); @@ -6619,115 +6970,22 @@ public class Long512VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsLong512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsLong512VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndLong512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long512VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrLong512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long512VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorLong512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long512VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotLong512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long512VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqLong512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long512VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeLong512VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6832,23 +7090,6 @@ public class Long512VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongLong512VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Long64VectorTests.java b/test/jdk/jdk/incubator/vector/Long64VectorTests.java index 0fda0abed58..5f8a9018384 100644 --- a/test/jdk/jdk/incubator/vector/Long64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Long64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Long64VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final long CONST_SHIFT = Long.SIZE / 2; + // Identity values for reduction operations + private static final long ADD_IDENTITY = (long)0; + private static final long AND_IDENTITY = (long)-1; + private static final long FIRST_NONZERO_IDENTITY = (long)0; + private static final long MAX_IDENTITY = Long.MIN_VALUE; + private static final long MIN_IDENTITY = Long.MAX_VALUE; + private static final long MUL_IDENTITY = (long)1; + private static final long OR_IDENTITY = (long)0; + private static final long SUADD_IDENTITY = (long)0; + private static final long UMAX_IDENTITY = (long)0; // Minimum unsigned value + private static final long UMIN_IDENTITY = (long)-1; // Maximum unsigned value + private static final long XOR_IDENTITY = (long)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 64); static void assertArraysStrictlyEquals(long[] r, long[] a) { @@ -350,6 +362,36 @@ public class Long64VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { long apply(long a, long b); } @@ -1219,8 +1261,23 @@ public class Long64VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3632,7 +3689,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long ANDReduce(long[] a, int idx) { - long res = -1; + long res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3641,7 +3698,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long ANDReduceAll(long[] a) { - long res = -1; + long res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3653,20 +3710,15 @@ public class Long64VectorTests extends AbstractVectorTest { static void ANDReduceLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = -1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + long v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3674,8 +3726,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::ANDReduce, Long64VectorTests::ANDReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = AND_IDENTITY; + + Assert.assertEquals((long) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id & x), x); + Assert.assertEquals((long) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static long ANDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = -1; + long res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3685,7 +3760,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long ANDReduceAllMasked(long[] a, boolean[] mask) { - long res = -1; + long res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3699,20 +3774,15 @@ public class Long64VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = -1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + long v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3721,7 +3791,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long ORReduce(long[] a, int idx) { - long res = 0; + long res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3730,7 +3800,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long ORReduceAll(long[] a) { - long res = 0; + long res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3745,17 +3815,12 @@ public class Long64VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + long v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3763,8 +3828,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::ORReduce, Long64VectorTests::ORReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = OR_IDENTITY; + + Assert.assertEquals((long) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id | x), x); + Assert.assertEquals((long) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static long ORReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3774,7 +3862,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long ORReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3791,17 +3879,12 @@ public class Long64VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + long v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3810,7 +3893,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long XORReduce(long[] a, int idx) { - long res = 0; + long res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3819,7 +3902,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long XORReduceAll(long[] a) { - long res = 0; + long res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3834,17 +3917,12 @@ public class Long64VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + long v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3852,8 +3930,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::XORReduce, Long64VectorTests::XORReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = XOR_IDENTITY; + + Assert.assertEquals((long) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id ^ x), x); + Assert.assertEquals((long) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static long XORReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3863,7 +3964,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long XORReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3880,17 +3981,12 @@ public class Long64VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + long v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3899,7 +3995,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long ADDReduce(long[] a, int idx) { - long res = 0; + long res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3908,7 +4004,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long ADDReduceAll(long[] a) { - long res = 0; + long res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3923,17 +4019,12 @@ public class Long64VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + long v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3941,8 +4032,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::ADDReduce, Long64VectorTests::ADDReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = ADD_IDENTITY; + + Assert.assertEquals((long) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id + x), x); + Assert.assertEquals((long) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static long ADDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3952,7 +4066,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long ADDReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3969,17 +4083,12 @@ public class Long64VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + long v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3988,7 +4097,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long MULReduce(long[] a, int idx) { - long res = 1; + long res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3997,7 +4106,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long MULReduceAll(long[] a) { - long res = 1; + long res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -4009,20 +4118,15 @@ public class Long64VectorTests extends AbstractVectorTest { static void MULReduceLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = 1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + long v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -4030,8 +4134,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::MULReduce, Long64VectorTests::MULReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MUL_IDENTITY; + + Assert.assertEquals((long) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id * x), x); + Assert.assertEquals((long) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static long MULReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 1; + long res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -4041,7 +4168,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long MULReduceAllMasked(long[] a, boolean[] mask) { - long res = 1; + long res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -4055,20 +4182,15 @@ public class Long64VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = 1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + long v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4077,7 +4199,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long MINReduce(long[] a, int idx) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) Math.min(res, a[i]); } @@ -4086,7 +4208,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long MINReduceAll(long[] a) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.min(res, MINReduce(a, i)); } @@ -4098,20 +4220,15 @@ public class Long64VectorTests extends AbstractVectorTest { static void MINReduceLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + long v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (long) Math.min(ra, v); } } @@ -4119,8 +4236,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::MINReduce, Long64VectorTests::MINReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MIN_IDENTITY; + + Assert.assertEquals((long) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) Math.min(id, x), x); + Assert.assertEquals((long) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static long MINReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) Math.min(res, a[i]); @@ -4130,7 +4270,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long MINReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4144,20 +4284,15 @@ public class Long64VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + long v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (long) Math.min(ra, v); } } @@ -4166,7 +4301,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long MAXReduce(long[] a, int idx) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) Math.max(res, a[i]); } @@ -4175,7 +4310,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long MAXReduceAll(long[] a) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.max(res, MAXReduce(a, i)); } @@ -4187,20 +4322,15 @@ public class Long64VectorTests extends AbstractVectorTest { static void MAXReduceLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + long v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (long) Math.max(ra, v); } } @@ -4208,8 +4338,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::MAXReduce, Long64VectorTests::MAXReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MAX_IDENTITY; + + Assert.assertEquals((long) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) Math.max(id, x), x); + Assert.assertEquals((long) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static long MAXReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) Math.max(res, a[i]); @@ -4219,7 +4372,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long MAXReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4233,20 +4386,15 @@ public class Long64VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + long v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (long) Math.max(ra, v); } } @@ -4255,7 +4403,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long UMINReduce(long[] a, int idx) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.minUnsigned(res, a[i]); } @@ -4264,7 +4412,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long UMINReduceAll(long[] a) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4276,20 +4424,15 @@ public class Long64VectorTests extends AbstractVectorTest { static void UMINReduceLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + long v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (long) VectorMath.minUnsigned(ra, v); } } @@ -4297,8 +4440,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::UMINReduce, Long64VectorTests::UMINReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = UMIN_IDENTITY; + + Assert.assertEquals((long) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static long UMINReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.minUnsigned(res, a[i]); @@ -4308,7 +4474,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long UMINReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4322,20 +4488,15 @@ public class Long64VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + long v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (long) VectorMath.minUnsigned(ra, v); } } @@ -4344,7 +4505,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long UMAXReduce(long[] a, int idx) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.maxUnsigned(res, a[i]); } @@ -4353,7 +4514,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long UMAXReduceAll(long[] a) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4365,20 +4526,15 @@ public class Long64VectorTests extends AbstractVectorTest { static void UMAXReduceLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + long v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (long) VectorMath.maxUnsigned(ra, v); } } @@ -4386,8 +4542,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::UMAXReduce, Long64VectorTests::UMAXReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = UMAX_IDENTITY; + + Assert.assertEquals((long) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static long UMAXReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.maxUnsigned(res, a[i]); @@ -4397,7 +4576,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long UMAXReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4411,20 +4590,15 @@ public class Long64VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + long v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (long) VectorMath.maxUnsigned(ra, v); } } @@ -4433,7 +4607,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduce(long[] a, int idx) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4442,7 +4616,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduceAll(long[] a) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4454,20 +4628,15 @@ public class Long64VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = (long) 0; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (long) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + long v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4475,8 +4644,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::FIRST_NONZEROReduce, Long64VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static long FIRST_NONZEROReduceMasked(long[] a, int idx, boolean[] mask) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4486,7 +4678,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduceAllMasked(long[] a, boolean[] mask) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4500,20 +4692,15 @@ public class Long64VectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = (long) 0; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (long) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + long v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4570,7 +4757,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long SUADDReduce(long[] a, int idx) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4579,7 +4766,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long SUADDReduceAll(long[] a) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4594,17 +4781,12 @@ public class Long64VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + long v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (long) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4612,8 +4794,31 @@ public class Long64VectorTests extends AbstractVectorTest { Long64VectorTests::SUADDReduce, Long64VectorTests::SUADDReduceAll); } + @Test(dataProvider = "longSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = SUADD_IDENTITY; + + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static long SUADDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4623,7 +4828,7 @@ public class Long64VectorTests extends AbstractVectorTest { } static long SUADDReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4639,17 +4844,12 @@ public class Long64VectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + long v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (long) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6386,6 +6586,157 @@ public class Long64VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Long64VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandLong64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long64VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorLong64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long64VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorLong64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long64VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotLong64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long64VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqLong64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Long64VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotLong64VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Long64VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongLong64VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "longCompareOpProvider") static void ltLong64VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { long[] a = fa.apply(SPECIES.length()); @@ -6619,115 +6970,22 @@ public class Long64VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsLong64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsLong64VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndLong64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long64VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrLong64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long64VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorLong64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long64VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotLong64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long64VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqLong64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Long64VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeLong64VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6832,23 +7090,6 @@ public class Long64VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongLong64VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java b/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java index 7aa2bc4c510..17fee0a7765 100644 --- a/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -71,6 +71,19 @@ public class LongMaxVectorTests extends AbstractVectorTest { private static final long CONST_SHIFT = Long.SIZE / 2; + // Identity values for reduction operations + private static final long ADD_IDENTITY = (long)0; + private static final long AND_IDENTITY = (long)-1; + private static final long FIRST_NONZERO_IDENTITY = (long)0; + private static final long MAX_IDENTITY = Long.MIN_VALUE; + private static final long MIN_IDENTITY = Long.MAX_VALUE; + private static final long MUL_IDENTITY = (long)1; + private static final long OR_IDENTITY = (long)0; + private static final long SUADD_IDENTITY = (long)0; + private static final long UMAX_IDENTITY = (long)0; // Minimum unsigned value + private static final long UMIN_IDENTITY = (long)-1; // Maximum unsigned value + private static final long XOR_IDENTITY = (long)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / Max); static void assertArraysStrictlyEquals(long[] r, long[] a) { @@ -355,6 +368,36 @@ public class LongMaxVectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { long apply(long a, long b); } @@ -1224,8 +1267,23 @@ public class LongMaxVectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3637,7 +3695,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long ANDReduce(long[] a, int idx) { - long res = -1; + long res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3646,7 +3704,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long ANDReduceAll(long[] a) { - long res = -1; + long res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3658,20 +3716,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { static void ANDReduceLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = -1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + long v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3679,8 +3732,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::ANDReduce, LongMaxVectorTests::ANDReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = AND_IDENTITY; + + Assert.assertEquals((long) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id & x), x); + Assert.assertEquals((long) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static long ANDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = -1; + long res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3690,7 +3766,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long ANDReduceAllMasked(long[] a, boolean[] mask) { - long res = -1; + long res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3704,20 +3780,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = -1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + long v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3726,7 +3797,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long ORReduce(long[] a, int idx) { - long res = 0; + long res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3735,7 +3806,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long ORReduceAll(long[] a) { - long res = 0; + long res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3750,17 +3821,12 @@ public class LongMaxVectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + long v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3768,8 +3834,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::ORReduce, LongMaxVectorTests::ORReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = OR_IDENTITY; + + Assert.assertEquals((long) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id | x), x); + Assert.assertEquals((long) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static long ORReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3779,7 +3868,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long ORReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3796,17 +3885,12 @@ public class LongMaxVectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + long v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3815,7 +3899,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long XORReduce(long[] a, int idx) { - long res = 0; + long res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3824,7 +3908,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long XORReduceAll(long[] a) { - long res = 0; + long res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3839,17 +3923,12 @@ public class LongMaxVectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + long v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3857,8 +3936,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::XORReduce, LongMaxVectorTests::XORReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = XOR_IDENTITY; + + Assert.assertEquals((long) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id ^ x), x); + Assert.assertEquals((long) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static long XORReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3868,7 +3970,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long XORReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3885,17 +3987,12 @@ public class LongMaxVectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + long v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3904,7 +4001,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long ADDReduce(long[] a, int idx) { - long res = 0; + long res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3913,7 +4010,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long ADDReduceAll(long[] a) { - long res = 0; + long res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3928,17 +4025,12 @@ public class LongMaxVectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + long v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3946,8 +4038,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::ADDReduce, LongMaxVectorTests::ADDReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = ADD_IDENTITY; + + Assert.assertEquals((long) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id + x), x); + Assert.assertEquals((long) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static long ADDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3957,7 +4072,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long ADDReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3974,17 +4089,12 @@ public class LongMaxVectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + long v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3993,7 +4103,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long MULReduce(long[] a, int idx) { - long res = 1; + long res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -4002,7 +4112,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long MULReduceAll(long[] a) { - long res = 1; + long res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -4014,20 +4124,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { static void MULReduceLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = 1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + long v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -4035,8 +4140,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::MULReduce, LongMaxVectorTests::MULReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MUL_IDENTITY; + + Assert.assertEquals((long) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) (id * x), x); + Assert.assertEquals((long) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static long MULReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 1; + long res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -4046,7 +4174,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long MULReduceAllMasked(long[] a, boolean[] mask) { - long res = 1; + long res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -4060,20 +4188,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = 1; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + long v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4082,7 +4205,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long MINReduce(long[] a, int idx) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) Math.min(res, a[i]); } @@ -4091,7 +4214,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long MINReduceAll(long[] a) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.min(res, MINReduce(a, i)); } @@ -4103,20 +4226,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { static void MINReduceLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + long v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (long) Math.min(ra, v); } } @@ -4124,8 +4242,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::MINReduce, LongMaxVectorTests::MINReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MIN_IDENTITY; + + Assert.assertEquals((long) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) Math.min(id, x), x); + Assert.assertEquals((long) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static long MINReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) Math.min(res, a[i]); @@ -4135,7 +4276,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long MINReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4149,20 +4290,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + long v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (long) Math.min(ra, v); } } @@ -4171,7 +4307,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long MAXReduce(long[] a, int idx) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) Math.max(res, a[i]); } @@ -4180,7 +4316,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long MAXReduceAll(long[] a) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.max(res, MAXReduce(a, i)); } @@ -4192,20 +4328,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { static void MAXReduceLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + long v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (long) Math.max(ra, v); } } @@ -4213,8 +4344,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::MAXReduce, LongMaxVectorTests::MAXReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = MAX_IDENTITY; + + Assert.assertEquals((long) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) Math.max(id, x), x); + Assert.assertEquals((long) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static long MAXReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) Math.max(res, a[i]); @@ -4224,7 +4378,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long MAXReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4238,20 +4392,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + long v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (long) Math.max(ra, v); } } @@ -4260,7 +4409,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long UMINReduce(long[] a, int idx) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.minUnsigned(res, a[i]); } @@ -4269,7 +4418,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long UMINReduceAll(long[] a) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4281,20 +4430,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { static void UMINReduceLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + long v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (long) VectorMath.minUnsigned(ra, v); } } @@ -4302,8 +4446,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::UMINReduce, LongMaxVectorTests::UMINReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = UMIN_IDENTITY; + + Assert.assertEquals((long) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static long UMINReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.minUnsigned(res, a[i]); @@ -4313,7 +4480,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long UMINReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MAX_VALUE; + long res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4327,20 +4494,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MAX_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + long v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (long) VectorMath.minUnsigned(ra, v); } } @@ -4349,7 +4511,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long UMAXReduce(long[] a, int idx) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.maxUnsigned(res, a[i]); } @@ -4358,7 +4520,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long UMAXReduceAll(long[] a) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4370,20 +4532,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { static void UMAXReduceLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + long v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (long) VectorMath.maxUnsigned(ra, v); } } @@ -4391,8 +4548,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::UMAXReduce, LongMaxVectorTests::UMAXReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = UMAX_IDENTITY; + + Assert.assertEquals((long) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static long UMAXReduceMasked(long[] a, int idx, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.maxUnsigned(res, a[i]); @@ -4402,7 +4582,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long UMAXReduceAllMasked(long[] a, boolean[] mask) { - long res = Long.MIN_VALUE; + long res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4416,20 +4596,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = Long.MIN_VALUE; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Long.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + long v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (long) VectorMath.maxUnsigned(ra, v); } } @@ -4438,7 +4613,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduce(long[] a, int idx) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4447,7 +4622,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduceAll(long[] a) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4459,20 +4634,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = fr.apply(SPECIES.length()); - long ra = (long) 0; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (long) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + long v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4480,8 +4650,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::FIRST_NONZEROReduce, LongMaxVectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "longUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static long FIRST_NONZEROReduceMasked(long[] a, int idx, boolean[] mask) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4491,7 +4684,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long FIRST_NONZEROReduceAllMasked(long[] a, boolean[] mask) { - long res = (long) 0; + long res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4505,20 +4698,15 @@ public class LongMaxVectorTests extends AbstractVectorTest { long[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - long ra = (long) 0; + long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (long) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + long v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4575,7 +4763,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long SUADDReduce(long[] a, int idx) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (long) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4584,7 +4772,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long SUADDReduceAll(long[] a) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4599,17 +4787,12 @@ public class LongMaxVectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + long v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (long) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4617,8 +4800,31 @@ public class LongMaxVectorTests extends AbstractVectorTest { LongMaxVectorTests::SUADDReduce, LongMaxVectorTests::SUADDReduceAll); } + @Test(dataProvider = "longSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long id = SUADD_IDENTITY; + + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + long x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((long) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static long SUADDReduceMasked(long[] a, int idx, boolean[] mask) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (long) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4628,7 +4834,7 @@ public class LongMaxVectorTests extends AbstractVectorTest { } static long SUADDReduceAllMasked(long[] a, boolean[] mask) { - long res = 0; + long res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (long) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4644,17 +4850,12 @@ public class LongMaxVectorTests extends AbstractVectorTest { long ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - LongVector av = LongVector.fromArray(SPECIES, a, i); - ra = (long) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + long v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (long) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6391,6 +6592,157 @@ public class LongMaxVectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, LongMaxVectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandLongMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, LongMaxVectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorLongMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, LongMaxVectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorLongMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, LongMaxVectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotLongMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, LongMaxVectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqLongMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, LongMaxVectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotLongMaxVectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, LongMaxVectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongLongMaxVectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "longCompareOpProvider") static void ltLongMaxVectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { long[] a = fa.apply(SPECIES.length()); @@ -6624,115 +6976,22 @@ public class LongMaxVectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsLongMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsLongMaxVectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndLongMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, LongMaxVectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrLongMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, LongMaxVectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorLongMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, LongMaxVectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotLongMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, LongMaxVectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqLongMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, LongMaxVectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeLongMaxVectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6837,7 +7096,6 @@ public class LongMaxVectorTests extends AbstractVectorTest { } } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Short128VectorTests.java b/test/jdk/jdk/incubator/vector/Short128VectorTests.java index 5f4c54bb708..fb740fedfd4 100644 --- a/test/jdk/jdk/incubator/vector/Short128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Short128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Short128VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final short CONST_SHIFT = Short.SIZE / 2; + // Identity values for reduction operations + private static final short ADD_IDENTITY = (short)0; + private static final short AND_IDENTITY = (short)-1; + private static final short FIRST_NONZERO_IDENTITY = (short)0; + private static final short MAX_IDENTITY = Short.MIN_VALUE; + private static final short MIN_IDENTITY = Short.MAX_VALUE; + private static final short MUL_IDENTITY = (short)1; + private static final short OR_IDENTITY = (short)0; + private static final short SUADD_IDENTITY = (short)0; + private static final short UMAX_IDENTITY = (short)0; // Minimum unsigned value + private static final short UMIN_IDENTITY = (short)-1; // Maximum unsigned value + private static final short XOR_IDENTITY = (short)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 128); static void assertArraysStrictlyEquals(short[] r, short[] a) { @@ -393,6 +405,36 @@ public class Short128VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { short apply(short a, short b); } @@ -1222,8 +1264,23 @@ public class Short128VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3557,7 +3614,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short ANDReduce(short[] a, int idx) { - short res = -1; + short res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3566,7 +3623,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short ANDReduceAll(short[] a) { - short res = -1; + short res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3578,20 +3635,15 @@ public class Short128VectorTests extends AbstractVectorTest { static void ANDReduceShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = -1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + short v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3599,8 +3651,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::ANDReduce, Short128VectorTests::ANDReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = AND_IDENTITY; + + Assert.assertEquals((short) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id & x), x); + Assert.assertEquals((short) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static short ANDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = -1; + short res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3610,7 +3685,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short ANDReduceAllMasked(short[] a, boolean[] mask) { - short res = -1; + short res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3624,20 +3699,15 @@ public class Short128VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = -1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + short v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3646,7 +3716,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short ORReduce(short[] a, int idx) { - short res = 0; + short res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3655,7 +3725,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short ORReduceAll(short[] a) { - short res = 0; + short res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3670,17 +3740,12 @@ public class Short128VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + short v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3688,8 +3753,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::ORReduce, Short128VectorTests::ORReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = OR_IDENTITY; + + Assert.assertEquals((short) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id | x), x); + Assert.assertEquals((short) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static short ORReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3699,7 +3787,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short ORReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3716,17 +3804,12 @@ public class Short128VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + short v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3735,7 +3818,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short XORReduce(short[] a, int idx) { - short res = 0; + short res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3744,7 +3827,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short XORReduceAll(short[] a) { - short res = 0; + short res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3759,17 +3842,12 @@ public class Short128VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + short v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3777,8 +3855,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::XORReduce, Short128VectorTests::XORReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = XOR_IDENTITY; + + Assert.assertEquals((short) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id ^ x), x); + Assert.assertEquals((short) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static short XORReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3788,7 +3889,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short XORReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3805,17 +3906,12 @@ public class Short128VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + short v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3824,7 +3920,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short ADDReduce(short[] a, int idx) { - short res = 0; + short res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3833,7 +3929,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short ADDReduceAll(short[] a) { - short res = 0; + short res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3848,17 +3944,12 @@ public class Short128VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + short v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3866,8 +3957,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::ADDReduce, Short128VectorTests::ADDReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = ADD_IDENTITY; + + Assert.assertEquals((short) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id + x), x); + Assert.assertEquals((short) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static short ADDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3877,7 +3991,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short ADDReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3894,17 +4008,12 @@ public class Short128VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + short v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3913,7 +4022,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short MULReduce(short[] a, int idx) { - short res = 1; + short res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3922,7 +4031,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short MULReduceAll(short[] a) { - short res = 1; + short res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3934,20 +4043,15 @@ public class Short128VectorTests extends AbstractVectorTest { static void MULReduceShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = 1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + short v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -3955,8 +4059,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::MULReduce, Short128VectorTests::MULReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MUL_IDENTITY; + + Assert.assertEquals((short) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id * x), x); + Assert.assertEquals((short) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static short MULReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 1; + short res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -3966,7 +4093,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short MULReduceAllMasked(short[] a, boolean[] mask) { - short res = 1; + short res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -3980,20 +4107,15 @@ public class Short128VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = 1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + short v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4002,7 +4124,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short MINReduce(short[] a, int idx) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) Math.min(res, a[i]); } @@ -4011,7 +4133,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short MINReduceAll(short[] a) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.min(res, MINReduce(a, i)); } @@ -4023,20 +4145,15 @@ public class Short128VectorTests extends AbstractVectorTest { static void MINReduceShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + short v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (short) Math.min(ra, v); } } @@ -4044,8 +4161,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::MINReduce, Short128VectorTests::MINReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MIN_IDENTITY; + + Assert.assertEquals((short) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) Math.min(id, x), x); + Assert.assertEquals((short) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static short MINReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) Math.min(res, a[i]); @@ -4055,7 +4195,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short MINReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4069,20 +4209,15 @@ public class Short128VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + short v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (short) Math.min(ra, v); } } @@ -4091,7 +4226,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short MAXReduce(short[] a, int idx) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) Math.max(res, a[i]); } @@ -4100,7 +4235,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short MAXReduceAll(short[] a) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.max(res, MAXReduce(a, i)); } @@ -4112,20 +4247,15 @@ public class Short128VectorTests extends AbstractVectorTest { static void MAXReduceShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + short v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (short) Math.max(ra, v); } } @@ -4133,8 +4263,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::MAXReduce, Short128VectorTests::MAXReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MAX_IDENTITY; + + Assert.assertEquals((short) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) Math.max(id, x), x); + Assert.assertEquals((short) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static short MAXReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) Math.max(res, a[i]); @@ -4144,7 +4297,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short MAXReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4158,20 +4311,15 @@ public class Short128VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + short v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (short) Math.max(ra, v); } } @@ -4180,7 +4328,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short UMINReduce(short[] a, int idx) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.minUnsigned(res, a[i]); } @@ -4189,7 +4337,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short UMINReduceAll(short[] a) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4201,20 +4349,15 @@ public class Short128VectorTests extends AbstractVectorTest { static void UMINReduceShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + short v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (short) VectorMath.minUnsigned(ra, v); } } @@ -4222,8 +4365,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::UMINReduce, Short128VectorTests::UMINReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = UMIN_IDENTITY; + + Assert.assertEquals((short) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static short UMINReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.minUnsigned(res, a[i]); @@ -4233,7 +4399,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short UMINReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4247,20 +4413,15 @@ public class Short128VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + short v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (short) VectorMath.minUnsigned(ra, v); } } @@ -4269,7 +4430,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short UMAXReduce(short[] a, int idx) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.maxUnsigned(res, a[i]); } @@ -4278,7 +4439,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short UMAXReduceAll(short[] a) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4290,20 +4451,15 @@ public class Short128VectorTests extends AbstractVectorTest { static void UMAXReduceShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + short v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (short) VectorMath.maxUnsigned(ra, v); } } @@ -4311,8 +4467,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::UMAXReduce, Short128VectorTests::UMAXReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = UMAX_IDENTITY; + + Assert.assertEquals((short) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static short UMAXReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.maxUnsigned(res, a[i]); @@ -4322,7 +4501,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short UMAXReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4336,20 +4515,15 @@ public class Short128VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + short v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (short) VectorMath.maxUnsigned(ra, v); } } @@ -4358,7 +4532,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduce(short[] a, int idx) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4367,7 +4541,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduceAll(short[] a) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4379,20 +4553,15 @@ public class Short128VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = (short) 0; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (short) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + short v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4400,8 +4569,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::FIRST_NONZEROReduce, Short128VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static short FIRST_NONZEROReduceMasked(short[] a, int idx, boolean[] mask) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4411,7 +4603,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduceAllMasked(short[] a, boolean[] mask) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4425,20 +4617,15 @@ public class Short128VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = (short) 0; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (short) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + short v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4495,7 +4682,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short SUADDReduce(short[] a, int idx) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4504,7 +4691,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short SUADDReduceAll(short[] a) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4519,17 +4706,12 @@ public class Short128VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + short v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (short) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4537,8 +4719,31 @@ public class Short128VectorTests extends AbstractVectorTest { Short128VectorTests::SUADDReduce, Short128VectorTests::SUADDReduceAll); } + @Test(dataProvider = "shortSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = SUADD_IDENTITY; + + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static short SUADDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4548,7 +4753,7 @@ public class Short128VectorTests extends AbstractVectorTest { } static short SUADDReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4564,17 +4769,12 @@ public class Short128VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + short v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (short) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6381,6 +6581,157 @@ public class Short128VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Short128VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandShort128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short128VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorShort128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short128VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorShort128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short128VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotShort128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short128VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqShort128VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short128VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotShort128VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Short128VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongShort128VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "shortCompareOpProvider") static void ltShort128VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { short[] a = fa.apply(SPECIES.length()); @@ -6680,115 +7031,22 @@ public class Short128VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsShort128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsShort128VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndShort128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short128VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrShort128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short128VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorShort128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short128VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotShort128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short128VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqShort128VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short128VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeShort128VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6893,23 +7151,6 @@ public class Short128VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongShort128VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Short256VectorTests.java b/test/jdk/jdk/incubator/vector/Short256VectorTests.java index 88986575f60..cd6aa113b84 100644 --- a/test/jdk/jdk/incubator/vector/Short256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Short256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Short256VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final short CONST_SHIFT = Short.SIZE / 2; + // Identity values for reduction operations + private static final short ADD_IDENTITY = (short)0; + private static final short AND_IDENTITY = (short)-1; + private static final short FIRST_NONZERO_IDENTITY = (short)0; + private static final short MAX_IDENTITY = Short.MIN_VALUE; + private static final short MIN_IDENTITY = Short.MAX_VALUE; + private static final short MUL_IDENTITY = (short)1; + private static final short OR_IDENTITY = (short)0; + private static final short SUADD_IDENTITY = (short)0; + private static final short UMAX_IDENTITY = (short)0; // Minimum unsigned value + private static final short UMIN_IDENTITY = (short)-1; // Maximum unsigned value + private static final short XOR_IDENTITY = (short)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 256); static void assertArraysStrictlyEquals(short[] r, short[] a) { @@ -393,6 +405,36 @@ public class Short256VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { short apply(short a, short b); } @@ -1222,8 +1264,23 @@ public class Short256VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3557,7 +3614,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short ANDReduce(short[] a, int idx) { - short res = -1; + short res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3566,7 +3623,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short ANDReduceAll(short[] a) { - short res = -1; + short res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3578,20 +3635,15 @@ public class Short256VectorTests extends AbstractVectorTest { static void ANDReduceShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = -1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + short v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3599,8 +3651,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::ANDReduce, Short256VectorTests::ANDReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = AND_IDENTITY; + + Assert.assertEquals((short) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id & x), x); + Assert.assertEquals((short) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static short ANDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = -1; + short res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3610,7 +3685,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short ANDReduceAllMasked(short[] a, boolean[] mask) { - short res = -1; + short res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3624,20 +3699,15 @@ public class Short256VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = -1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + short v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3646,7 +3716,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short ORReduce(short[] a, int idx) { - short res = 0; + short res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3655,7 +3725,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short ORReduceAll(short[] a) { - short res = 0; + short res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3670,17 +3740,12 @@ public class Short256VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + short v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3688,8 +3753,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::ORReduce, Short256VectorTests::ORReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = OR_IDENTITY; + + Assert.assertEquals((short) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id | x), x); + Assert.assertEquals((short) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static short ORReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3699,7 +3787,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short ORReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3716,17 +3804,12 @@ public class Short256VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + short v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3735,7 +3818,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short XORReduce(short[] a, int idx) { - short res = 0; + short res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3744,7 +3827,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short XORReduceAll(short[] a) { - short res = 0; + short res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3759,17 +3842,12 @@ public class Short256VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + short v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3777,8 +3855,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::XORReduce, Short256VectorTests::XORReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = XOR_IDENTITY; + + Assert.assertEquals((short) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id ^ x), x); + Assert.assertEquals((short) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static short XORReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3788,7 +3889,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short XORReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3805,17 +3906,12 @@ public class Short256VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + short v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3824,7 +3920,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short ADDReduce(short[] a, int idx) { - short res = 0; + short res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3833,7 +3929,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short ADDReduceAll(short[] a) { - short res = 0; + short res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3848,17 +3944,12 @@ public class Short256VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + short v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3866,8 +3957,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::ADDReduce, Short256VectorTests::ADDReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = ADD_IDENTITY; + + Assert.assertEquals((short) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id + x), x); + Assert.assertEquals((short) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static short ADDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3877,7 +3991,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short ADDReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3894,17 +4008,12 @@ public class Short256VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + short v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3913,7 +4022,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short MULReduce(short[] a, int idx) { - short res = 1; + short res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3922,7 +4031,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short MULReduceAll(short[] a) { - short res = 1; + short res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3934,20 +4043,15 @@ public class Short256VectorTests extends AbstractVectorTest { static void MULReduceShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = 1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + short v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -3955,8 +4059,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::MULReduce, Short256VectorTests::MULReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MUL_IDENTITY; + + Assert.assertEquals((short) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id * x), x); + Assert.assertEquals((short) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static short MULReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 1; + short res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -3966,7 +4093,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short MULReduceAllMasked(short[] a, boolean[] mask) { - short res = 1; + short res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -3980,20 +4107,15 @@ public class Short256VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = 1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + short v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4002,7 +4124,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short MINReduce(short[] a, int idx) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) Math.min(res, a[i]); } @@ -4011,7 +4133,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short MINReduceAll(short[] a) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.min(res, MINReduce(a, i)); } @@ -4023,20 +4145,15 @@ public class Short256VectorTests extends AbstractVectorTest { static void MINReduceShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + short v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (short) Math.min(ra, v); } } @@ -4044,8 +4161,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::MINReduce, Short256VectorTests::MINReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MIN_IDENTITY; + + Assert.assertEquals((short) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) Math.min(id, x), x); + Assert.assertEquals((short) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static short MINReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) Math.min(res, a[i]); @@ -4055,7 +4195,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short MINReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4069,20 +4209,15 @@ public class Short256VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + short v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (short) Math.min(ra, v); } } @@ -4091,7 +4226,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short MAXReduce(short[] a, int idx) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) Math.max(res, a[i]); } @@ -4100,7 +4235,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short MAXReduceAll(short[] a) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.max(res, MAXReduce(a, i)); } @@ -4112,20 +4247,15 @@ public class Short256VectorTests extends AbstractVectorTest { static void MAXReduceShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + short v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (short) Math.max(ra, v); } } @@ -4133,8 +4263,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::MAXReduce, Short256VectorTests::MAXReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MAX_IDENTITY; + + Assert.assertEquals((short) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) Math.max(id, x), x); + Assert.assertEquals((short) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static short MAXReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) Math.max(res, a[i]); @@ -4144,7 +4297,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short MAXReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4158,20 +4311,15 @@ public class Short256VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + short v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (short) Math.max(ra, v); } } @@ -4180,7 +4328,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short UMINReduce(short[] a, int idx) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.minUnsigned(res, a[i]); } @@ -4189,7 +4337,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short UMINReduceAll(short[] a) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4201,20 +4349,15 @@ public class Short256VectorTests extends AbstractVectorTest { static void UMINReduceShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + short v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (short) VectorMath.minUnsigned(ra, v); } } @@ -4222,8 +4365,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::UMINReduce, Short256VectorTests::UMINReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = UMIN_IDENTITY; + + Assert.assertEquals((short) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static short UMINReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.minUnsigned(res, a[i]); @@ -4233,7 +4399,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short UMINReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4247,20 +4413,15 @@ public class Short256VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + short v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (short) VectorMath.minUnsigned(ra, v); } } @@ -4269,7 +4430,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short UMAXReduce(short[] a, int idx) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.maxUnsigned(res, a[i]); } @@ -4278,7 +4439,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short UMAXReduceAll(short[] a) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4290,20 +4451,15 @@ public class Short256VectorTests extends AbstractVectorTest { static void UMAXReduceShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + short v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (short) VectorMath.maxUnsigned(ra, v); } } @@ -4311,8 +4467,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::UMAXReduce, Short256VectorTests::UMAXReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = UMAX_IDENTITY; + + Assert.assertEquals((short) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static short UMAXReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.maxUnsigned(res, a[i]); @@ -4322,7 +4501,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short UMAXReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4336,20 +4515,15 @@ public class Short256VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + short v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (short) VectorMath.maxUnsigned(ra, v); } } @@ -4358,7 +4532,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduce(short[] a, int idx) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4367,7 +4541,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduceAll(short[] a) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4379,20 +4553,15 @@ public class Short256VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = (short) 0; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (short) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + short v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4400,8 +4569,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::FIRST_NONZEROReduce, Short256VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static short FIRST_NONZEROReduceMasked(short[] a, int idx, boolean[] mask) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4411,7 +4603,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduceAllMasked(short[] a, boolean[] mask) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4425,20 +4617,15 @@ public class Short256VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = (short) 0; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (short) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + short v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4495,7 +4682,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short SUADDReduce(short[] a, int idx) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4504,7 +4691,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short SUADDReduceAll(short[] a) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4519,17 +4706,12 @@ public class Short256VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + short v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (short) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4537,8 +4719,31 @@ public class Short256VectorTests extends AbstractVectorTest { Short256VectorTests::SUADDReduce, Short256VectorTests::SUADDReduceAll); } + @Test(dataProvider = "shortSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = SUADD_IDENTITY; + + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static short SUADDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4548,7 +4753,7 @@ public class Short256VectorTests extends AbstractVectorTest { } static short SUADDReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4564,17 +4769,12 @@ public class Short256VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + short v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (short) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6381,6 +6581,157 @@ public class Short256VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Short256VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandShort256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short256VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorShort256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short256VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorShort256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short256VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotShort256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short256VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqShort256VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short256VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotShort256VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Short256VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongShort256VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "shortCompareOpProvider") static void ltShort256VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { short[] a = fa.apply(SPECIES.length()); @@ -6680,115 +7031,22 @@ public class Short256VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsShort256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsShort256VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndShort256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short256VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrShort256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short256VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorShort256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short256VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotShort256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short256VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqShort256VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short256VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeShort256VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6893,23 +7151,6 @@ public class Short256VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongShort256VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Short512VectorTests.java b/test/jdk/jdk/incubator/vector/Short512VectorTests.java index 0f474375a47..722f826f3e9 100644 --- a/test/jdk/jdk/incubator/vector/Short512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Short512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Short512VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final short CONST_SHIFT = Short.SIZE / 2; + // Identity values for reduction operations + private static final short ADD_IDENTITY = (short)0; + private static final short AND_IDENTITY = (short)-1; + private static final short FIRST_NONZERO_IDENTITY = (short)0; + private static final short MAX_IDENTITY = Short.MIN_VALUE; + private static final short MIN_IDENTITY = Short.MAX_VALUE; + private static final short MUL_IDENTITY = (short)1; + private static final short OR_IDENTITY = (short)0; + private static final short SUADD_IDENTITY = (short)0; + private static final short UMAX_IDENTITY = (short)0; // Minimum unsigned value + private static final short UMIN_IDENTITY = (short)-1; // Maximum unsigned value + private static final short XOR_IDENTITY = (short)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 512); static void assertArraysStrictlyEquals(short[] r, short[] a) { @@ -393,6 +405,36 @@ public class Short512VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { short apply(short a, short b); } @@ -1222,8 +1264,23 @@ public class Short512VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3557,7 +3614,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short ANDReduce(short[] a, int idx) { - short res = -1; + short res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3566,7 +3623,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short ANDReduceAll(short[] a) { - short res = -1; + short res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3578,20 +3635,15 @@ public class Short512VectorTests extends AbstractVectorTest { static void ANDReduceShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = -1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + short v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3599,8 +3651,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::ANDReduce, Short512VectorTests::ANDReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = AND_IDENTITY; + + Assert.assertEquals((short) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id & x), x); + Assert.assertEquals((short) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static short ANDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = -1; + short res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3610,7 +3685,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short ANDReduceAllMasked(short[] a, boolean[] mask) { - short res = -1; + short res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3624,20 +3699,15 @@ public class Short512VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = -1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + short v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3646,7 +3716,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short ORReduce(short[] a, int idx) { - short res = 0; + short res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3655,7 +3725,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short ORReduceAll(short[] a) { - short res = 0; + short res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3670,17 +3740,12 @@ public class Short512VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + short v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3688,8 +3753,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::ORReduce, Short512VectorTests::ORReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = OR_IDENTITY; + + Assert.assertEquals((short) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id | x), x); + Assert.assertEquals((short) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static short ORReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3699,7 +3787,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short ORReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3716,17 +3804,12 @@ public class Short512VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + short v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3735,7 +3818,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short XORReduce(short[] a, int idx) { - short res = 0; + short res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3744,7 +3827,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short XORReduceAll(short[] a) { - short res = 0; + short res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3759,17 +3842,12 @@ public class Short512VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + short v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3777,8 +3855,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::XORReduce, Short512VectorTests::XORReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = XOR_IDENTITY; + + Assert.assertEquals((short) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id ^ x), x); + Assert.assertEquals((short) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static short XORReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3788,7 +3889,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short XORReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3805,17 +3906,12 @@ public class Short512VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + short v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3824,7 +3920,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short ADDReduce(short[] a, int idx) { - short res = 0; + short res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3833,7 +3929,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short ADDReduceAll(short[] a) { - short res = 0; + short res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3848,17 +3944,12 @@ public class Short512VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + short v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3866,8 +3957,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::ADDReduce, Short512VectorTests::ADDReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = ADD_IDENTITY; + + Assert.assertEquals((short) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id + x), x); + Assert.assertEquals((short) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static short ADDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3877,7 +3991,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short ADDReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3894,17 +4008,12 @@ public class Short512VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + short v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3913,7 +4022,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short MULReduce(short[] a, int idx) { - short res = 1; + short res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3922,7 +4031,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short MULReduceAll(short[] a) { - short res = 1; + short res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3934,20 +4043,15 @@ public class Short512VectorTests extends AbstractVectorTest { static void MULReduceShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = 1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + short v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -3955,8 +4059,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::MULReduce, Short512VectorTests::MULReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MUL_IDENTITY; + + Assert.assertEquals((short) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id * x), x); + Assert.assertEquals((short) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static short MULReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 1; + short res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -3966,7 +4093,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short MULReduceAllMasked(short[] a, boolean[] mask) { - short res = 1; + short res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -3980,20 +4107,15 @@ public class Short512VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = 1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + short v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4002,7 +4124,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short MINReduce(short[] a, int idx) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) Math.min(res, a[i]); } @@ -4011,7 +4133,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short MINReduceAll(short[] a) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.min(res, MINReduce(a, i)); } @@ -4023,20 +4145,15 @@ public class Short512VectorTests extends AbstractVectorTest { static void MINReduceShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + short v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (short) Math.min(ra, v); } } @@ -4044,8 +4161,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::MINReduce, Short512VectorTests::MINReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MIN_IDENTITY; + + Assert.assertEquals((short) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) Math.min(id, x), x); + Assert.assertEquals((short) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static short MINReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) Math.min(res, a[i]); @@ -4055,7 +4195,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short MINReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4069,20 +4209,15 @@ public class Short512VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + short v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (short) Math.min(ra, v); } } @@ -4091,7 +4226,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short MAXReduce(short[] a, int idx) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) Math.max(res, a[i]); } @@ -4100,7 +4235,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short MAXReduceAll(short[] a) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.max(res, MAXReduce(a, i)); } @@ -4112,20 +4247,15 @@ public class Short512VectorTests extends AbstractVectorTest { static void MAXReduceShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + short v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (short) Math.max(ra, v); } } @@ -4133,8 +4263,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::MAXReduce, Short512VectorTests::MAXReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MAX_IDENTITY; + + Assert.assertEquals((short) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) Math.max(id, x), x); + Assert.assertEquals((short) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static short MAXReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) Math.max(res, a[i]); @@ -4144,7 +4297,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short MAXReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4158,20 +4311,15 @@ public class Short512VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + short v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (short) Math.max(ra, v); } } @@ -4180,7 +4328,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short UMINReduce(short[] a, int idx) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.minUnsigned(res, a[i]); } @@ -4189,7 +4337,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short UMINReduceAll(short[] a) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4201,20 +4349,15 @@ public class Short512VectorTests extends AbstractVectorTest { static void UMINReduceShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + short v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (short) VectorMath.minUnsigned(ra, v); } } @@ -4222,8 +4365,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::UMINReduce, Short512VectorTests::UMINReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = UMIN_IDENTITY; + + Assert.assertEquals((short) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static short UMINReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.minUnsigned(res, a[i]); @@ -4233,7 +4399,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short UMINReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4247,20 +4413,15 @@ public class Short512VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + short v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (short) VectorMath.minUnsigned(ra, v); } } @@ -4269,7 +4430,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short UMAXReduce(short[] a, int idx) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.maxUnsigned(res, a[i]); } @@ -4278,7 +4439,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short UMAXReduceAll(short[] a) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4290,20 +4451,15 @@ public class Short512VectorTests extends AbstractVectorTest { static void UMAXReduceShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + short v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (short) VectorMath.maxUnsigned(ra, v); } } @@ -4311,8 +4467,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::UMAXReduce, Short512VectorTests::UMAXReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = UMAX_IDENTITY; + + Assert.assertEquals((short) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static short UMAXReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.maxUnsigned(res, a[i]); @@ -4322,7 +4501,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short UMAXReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4336,20 +4515,15 @@ public class Short512VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + short v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (short) VectorMath.maxUnsigned(ra, v); } } @@ -4358,7 +4532,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduce(short[] a, int idx) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4367,7 +4541,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduceAll(short[] a) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4379,20 +4553,15 @@ public class Short512VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = (short) 0; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (short) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + short v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4400,8 +4569,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::FIRST_NONZEROReduce, Short512VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static short FIRST_NONZEROReduceMasked(short[] a, int idx, boolean[] mask) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4411,7 +4603,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduceAllMasked(short[] a, boolean[] mask) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4425,20 +4617,15 @@ public class Short512VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = (short) 0; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (short) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + short v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4495,7 +4682,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short SUADDReduce(short[] a, int idx) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4504,7 +4691,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short SUADDReduceAll(short[] a) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4519,17 +4706,12 @@ public class Short512VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + short v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (short) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4537,8 +4719,31 @@ public class Short512VectorTests extends AbstractVectorTest { Short512VectorTests::SUADDReduce, Short512VectorTests::SUADDReduceAll); } + @Test(dataProvider = "shortSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = SUADD_IDENTITY; + + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static short SUADDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4548,7 +4753,7 @@ public class Short512VectorTests extends AbstractVectorTest { } static short SUADDReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4564,17 +4769,12 @@ public class Short512VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + short v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (short) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6381,6 +6581,157 @@ public class Short512VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Short512VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandShort512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short512VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorShort512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short512VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorShort512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short512VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotShort512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short512VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqShort512VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short512VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotShort512VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Short512VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongShort512VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "shortCompareOpProvider") static void ltShort512VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { short[] a = fa.apply(SPECIES.length()); @@ -6680,115 +7031,22 @@ public class Short512VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsShort512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsShort512VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndShort512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short512VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrShort512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short512VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorShort512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short512VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotShort512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short512VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqShort512VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short512VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeShort512VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6893,23 +7151,6 @@ public class Short512VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongShort512VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/Short64VectorTests.java b/test/jdk/jdk/incubator/vector/Short64VectorTests.java index 4b99ed6d84c..9ec8ac08789 100644 --- a/test/jdk/jdk/incubator/vector/Short64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Short64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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,9 +63,21 @@ public class Short64VectorTests extends AbstractVectorTest { static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - private static final short CONST_SHIFT = Short.SIZE / 2; + // Identity values for reduction operations + private static final short ADD_IDENTITY = (short)0; + private static final short AND_IDENTITY = (short)-1; + private static final short FIRST_NONZERO_IDENTITY = (short)0; + private static final short MAX_IDENTITY = Short.MIN_VALUE; + private static final short MIN_IDENTITY = Short.MAX_VALUE; + private static final short MUL_IDENTITY = (short)1; + private static final short OR_IDENTITY = (short)0; + private static final short SUADD_IDENTITY = (short)0; + private static final short UMAX_IDENTITY = (short)0; // Minimum unsigned value + private static final short UMIN_IDENTITY = (short)-1; // Maximum unsigned value + private static final short XOR_IDENTITY = (short)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / 64); static void assertArraysStrictlyEquals(short[] r, short[] a) { @@ -393,6 +405,36 @@ public class Short64VectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { short apply(short a, short b); } @@ -1222,8 +1264,23 @@ public class Short64VectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3557,7 +3614,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short ANDReduce(short[] a, int idx) { - short res = -1; + short res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3566,7 +3623,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short ANDReduceAll(short[] a) { - short res = -1; + short res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3578,20 +3635,15 @@ public class Short64VectorTests extends AbstractVectorTest { static void ANDReduceShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = -1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + short v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3599,8 +3651,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::ANDReduce, Short64VectorTests::ANDReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = AND_IDENTITY; + + Assert.assertEquals((short) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id & x), x); + Assert.assertEquals((short) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static short ANDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = -1; + short res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3610,7 +3685,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short ANDReduceAllMasked(short[] a, boolean[] mask) { - short res = -1; + short res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3624,20 +3699,15 @@ public class Short64VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = -1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + short v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3646,7 +3716,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short ORReduce(short[] a, int idx) { - short res = 0; + short res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3655,7 +3725,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short ORReduceAll(short[] a) { - short res = 0; + short res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3670,17 +3740,12 @@ public class Short64VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + short v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3688,8 +3753,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::ORReduce, Short64VectorTests::ORReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = OR_IDENTITY; + + Assert.assertEquals((short) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id | x), x); + Assert.assertEquals((short) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static short ORReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3699,7 +3787,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short ORReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3716,17 +3804,12 @@ public class Short64VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + short v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3735,7 +3818,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short XORReduce(short[] a, int idx) { - short res = 0; + short res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3744,7 +3827,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short XORReduceAll(short[] a) { - short res = 0; + short res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3759,17 +3842,12 @@ public class Short64VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + short v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3777,8 +3855,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::XORReduce, Short64VectorTests::XORReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = XOR_IDENTITY; + + Assert.assertEquals((short) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id ^ x), x); + Assert.assertEquals((short) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static short XORReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3788,7 +3889,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short XORReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3805,17 +3906,12 @@ public class Short64VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + short v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3824,7 +3920,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short ADDReduce(short[] a, int idx) { - short res = 0; + short res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3833,7 +3929,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short ADDReduceAll(short[] a) { - short res = 0; + short res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3848,17 +3944,12 @@ public class Short64VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + short v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3866,8 +3957,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::ADDReduce, Short64VectorTests::ADDReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = ADD_IDENTITY; + + Assert.assertEquals((short) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id + x), x); + Assert.assertEquals((short) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static short ADDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3877,7 +3991,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short ADDReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3894,17 +4008,12 @@ public class Short64VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + short v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3913,7 +4022,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short MULReduce(short[] a, int idx) { - short res = 1; + short res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3922,7 +4031,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short MULReduceAll(short[] a) { - short res = 1; + short res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3934,20 +4043,15 @@ public class Short64VectorTests extends AbstractVectorTest { static void MULReduceShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = 1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + short v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -3955,8 +4059,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::MULReduce, Short64VectorTests::MULReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MUL_IDENTITY; + + Assert.assertEquals((short) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id * x), x); + Assert.assertEquals((short) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static short MULReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 1; + short res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -3966,7 +4093,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short MULReduceAllMasked(short[] a, boolean[] mask) { - short res = 1; + short res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -3980,20 +4107,15 @@ public class Short64VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = 1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + short v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4002,7 +4124,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short MINReduce(short[] a, int idx) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) Math.min(res, a[i]); } @@ -4011,7 +4133,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short MINReduceAll(short[] a) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.min(res, MINReduce(a, i)); } @@ -4023,20 +4145,15 @@ public class Short64VectorTests extends AbstractVectorTest { static void MINReduceShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + short v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (short) Math.min(ra, v); } } @@ -4044,8 +4161,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::MINReduce, Short64VectorTests::MINReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MIN_IDENTITY; + + Assert.assertEquals((short) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) Math.min(id, x), x); + Assert.assertEquals((short) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static short MINReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) Math.min(res, a[i]); @@ -4055,7 +4195,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short MINReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4069,20 +4209,15 @@ public class Short64VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + short v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (short) Math.min(ra, v); } } @@ -4091,7 +4226,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short MAXReduce(short[] a, int idx) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) Math.max(res, a[i]); } @@ -4100,7 +4235,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short MAXReduceAll(short[] a) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.max(res, MAXReduce(a, i)); } @@ -4112,20 +4247,15 @@ public class Short64VectorTests extends AbstractVectorTest { static void MAXReduceShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + short v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (short) Math.max(ra, v); } } @@ -4133,8 +4263,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::MAXReduce, Short64VectorTests::MAXReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MAX_IDENTITY; + + Assert.assertEquals((short) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) Math.max(id, x), x); + Assert.assertEquals((short) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static short MAXReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) Math.max(res, a[i]); @@ -4144,7 +4297,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short MAXReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4158,20 +4311,15 @@ public class Short64VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + short v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (short) Math.max(ra, v); } } @@ -4180,7 +4328,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short UMINReduce(short[] a, int idx) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.minUnsigned(res, a[i]); } @@ -4189,7 +4337,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short UMINReduceAll(short[] a) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4201,20 +4349,15 @@ public class Short64VectorTests extends AbstractVectorTest { static void UMINReduceShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + short v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (short) VectorMath.minUnsigned(ra, v); } } @@ -4222,8 +4365,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::UMINReduce, Short64VectorTests::UMINReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = UMIN_IDENTITY; + + Assert.assertEquals((short) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static short UMINReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.minUnsigned(res, a[i]); @@ -4233,7 +4399,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short UMINReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4247,20 +4413,15 @@ public class Short64VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + short v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (short) VectorMath.minUnsigned(ra, v); } } @@ -4269,7 +4430,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short UMAXReduce(short[] a, int idx) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.maxUnsigned(res, a[i]); } @@ -4278,7 +4439,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short UMAXReduceAll(short[] a) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4290,20 +4451,15 @@ public class Short64VectorTests extends AbstractVectorTest { static void UMAXReduceShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + short v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (short) VectorMath.maxUnsigned(ra, v); } } @@ -4311,8 +4467,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::UMAXReduce, Short64VectorTests::UMAXReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = UMAX_IDENTITY; + + Assert.assertEquals((short) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static short UMAXReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.maxUnsigned(res, a[i]); @@ -4322,7 +4501,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short UMAXReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4336,20 +4515,15 @@ public class Short64VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + short v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (short) VectorMath.maxUnsigned(ra, v); } } @@ -4358,7 +4532,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduce(short[] a, int idx) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4367,7 +4541,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduceAll(short[] a) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4379,20 +4553,15 @@ public class Short64VectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = (short) 0; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (short) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + short v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4400,8 +4569,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::FIRST_NONZEROReduce, Short64VectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static short FIRST_NONZEROReduceMasked(short[] a, int idx, boolean[] mask) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4411,7 +4603,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduceAllMasked(short[] a, boolean[] mask) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4425,20 +4617,15 @@ public class Short64VectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = (short) 0; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (short) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + short v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4495,7 +4682,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short SUADDReduce(short[] a, int idx) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4504,7 +4691,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short SUADDReduceAll(short[] a) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4519,17 +4706,12 @@ public class Short64VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + short v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (short) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4537,8 +4719,31 @@ public class Short64VectorTests extends AbstractVectorTest { Short64VectorTests::SUADDReduce, Short64VectorTests::SUADDReduceAll); } + @Test(dataProvider = "shortSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = SUADD_IDENTITY; + + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static short SUADDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4548,7 +4753,7 @@ public class Short64VectorTests extends AbstractVectorTest { } static short SUADDReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4564,17 +4769,12 @@ public class Short64VectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + short v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (short) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6381,6 +6581,157 @@ public class Short64VectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, Short64VectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandShort64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short64VectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorShort64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short64VectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorShort64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short64VectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotShort64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short64VectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqShort64VectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, Short64VectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotShort64VectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, Short64VectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongShort64VectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "shortCompareOpProvider") static void ltShort64VectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { short[] a = fa.apply(SPECIES.length()); @@ -6680,115 +7031,22 @@ public class Short64VectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsShort64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsShort64VectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndShort64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short64VectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrShort64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short64VectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorShort64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short64VectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotShort64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short64VectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqShort64VectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, Short64VectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeShort64VectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6893,23 +7151,6 @@ public class Short64VectorTests extends AbstractVectorTest { } } - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLongShort64VectorTestsSmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java b/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java index 2bb3b9c1557..ad2efd3575d 100644 --- a/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -71,6 +71,19 @@ public class ShortMaxVectorTests extends AbstractVectorTest { private static final short CONST_SHIFT = Short.SIZE / 2; + // Identity values for reduction operations + private static final short ADD_IDENTITY = (short)0; + private static final short AND_IDENTITY = (short)-1; + private static final short FIRST_NONZERO_IDENTITY = (short)0; + private static final short MAX_IDENTITY = Short.MIN_VALUE; + private static final short MIN_IDENTITY = Short.MAX_VALUE; + private static final short MUL_IDENTITY = (short)1; + private static final short OR_IDENTITY = (short)0; + private static final short SUADD_IDENTITY = (short)0; + private static final short UMAX_IDENTITY = (short)0; // Minimum unsigned value + private static final short UMIN_IDENTITY = (short)-1; // Maximum unsigned value + private static final short XOR_IDENTITY = (short)0; + static final int BUFFER_REPS = Integer.getInteger("jdk.incubator.vector.test.buffer-vectors", 25000 / Max); static void assertArraysStrictlyEquals(short[] r, short[] a) { @@ -398,6 +411,36 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { short apply(short a, short b); } @@ -1227,8 +1270,23 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } @@ -3562,7 +3620,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short ANDReduce(short[] a, int idx) { - short res = -1; + short res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res &= a[i]; } @@ -3571,7 +3629,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short ANDReduceAll(short[] a) { - short res = -1; + short res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduce(a, i); } @@ -3583,20 +3641,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { static void ANDReduceShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = -1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND); + short v = av.reduceLanes(VectorOperators.AND); + r[i] = v; + ra &= v; } } @@ -3604,8 +3657,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::ANDReduce, ShortMaxVectorTests::ANDReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ANDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = AND_IDENTITY; + + Assert.assertEquals((short) (id & id), id, + "AND(AND_IDENTITY, AND_IDENTITY) != AND_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id & x), x); + Assert.assertEquals((short) (x & id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id & x), x, + "AND(AND_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x & id), x, + "AND(" + x + ", AND_IDENTITY) != " + x); + } + } + static short ANDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = -1; + short res = AND_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res &= a[i]; @@ -3615,7 +3691,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short ANDReduceAllMasked(short[] a, boolean[] mask) { - short res = -1; + short res = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res &= ANDReduceMasked(a, i, mask); } @@ -3629,20 +3705,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = -1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = AND_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.AND, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = -1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra &= av.reduceLanes(VectorOperators.AND, vmask); + short v = av.reduceLanes(VectorOperators.AND, vmask); + r[i] = v; + ra &= v; } } @@ -3651,7 +3722,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short ORReduce(short[] a, int idx) { - short res = 0; + short res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res |= a[i]; } @@ -3660,7 +3731,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short ORReduceAll(short[] a) { - short res = 0; + short res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduce(a, i); } @@ -3675,17 +3746,12 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR); + short v = av.reduceLanes(VectorOperators.OR); + r[i] = v; + ra |= v; } } @@ -3693,8 +3759,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::ORReduce, ShortMaxVectorTests::ORReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ORReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = OR_IDENTITY; + + Assert.assertEquals((short) (id | id), id, + "OR(OR_IDENTITY, OR_IDENTITY) != OR_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id | x), x); + Assert.assertEquals((short) (x | id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id | x), x, + "OR(OR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x | id), x, + "OR(" + x + ", OR_IDENTITY) != " + x); + } + } + static short ORReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = OR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res |= a[i]; @@ -3704,7 +3793,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short ORReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res |= ORReduceMasked(a, i, mask); } @@ -3721,17 +3810,12 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = OR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.OR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra |= av.reduceLanes(VectorOperators.OR, vmask); + short v = av.reduceLanes(VectorOperators.OR, vmask); + r[i] = v; + ra |= v; } } @@ -3740,7 +3824,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short XORReduce(short[] a, int idx) { - short res = 0; + short res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res ^= a[i]; } @@ -3749,7 +3833,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short XORReduceAll(short[] a) { - short res = 0; + short res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduce(a, i); } @@ -3764,17 +3848,12 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR); + short v = av.reduceLanes(VectorOperators.XOR); + r[i] = v; + ra ^= v; } } @@ -3782,8 +3861,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::XORReduce, ShortMaxVectorTests::XORReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void XORReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = XOR_IDENTITY; + + Assert.assertEquals((short) (id ^ id), id, + "XOR(XOR_IDENTITY, XOR_IDENTITY) != XOR_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id ^ x), x); + Assert.assertEquals((short) (x ^ id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id ^ x), x, + "XOR(XOR_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x ^ id), x, + "XOR(" + x + ", XOR_IDENTITY) != " + x); + } + } + static short XORReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = XOR_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res ^= a[i]; @@ -3793,7 +3895,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short XORReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res ^= XORReduceMasked(a, i, mask); } @@ -3810,17 +3912,12 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = XOR_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.XOR, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra ^= av.reduceLanes(VectorOperators.XOR, vmask); + short v = av.reduceLanes(VectorOperators.XOR, vmask); + r[i] = v; + ra ^= v; } } @@ -3829,7 +3926,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short ADDReduce(short[] a, int idx) { - short res = 0; + short res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res += a[i]; } @@ -3838,7 +3935,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short ADDReduceAll(short[] a) { - short res = 0; + short res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduce(a, i); } @@ -3853,17 +3950,12 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD); + short v = av.reduceLanes(VectorOperators.ADD); + r[i] = v; + ra += v; } } @@ -3871,8 +3963,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::ADDReduce, ShortMaxVectorTests::ADDReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void ADDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = ADD_IDENTITY; + + Assert.assertEquals((short) (id + id), id, + "ADD(ADD_IDENTITY, ADD_IDENTITY) != ADD_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id + x), x); + Assert.assertEquals((short) (x + id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id + x), x, + "ADD(ADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x + id), x, + "ADD(" + x + ", ADD_IDENTITY) != " + x); + } + } + static short ADDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = ADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res += a[i]; @@ -3882,7 +3997,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short ADDReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res += ADDReduceMasked(a, i, mask); } @@ -3899,17 +4014,12 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = ADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.ADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra += av.reduceLanes(VectorOperators.ADD, vmask); + short v = av.reduceLanes(VectorOperators.ADD, vmask); + r[i] = v; + ra += v; } } @@ -3918,7 +4028,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short MULReduce(short[] a, int idx) { - short res = 1; + short res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res *= a[i]; } @@ -3927,7 +4037,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short MULReduceAll(short[] a) { - short res = 1; + short res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduce(a, i); } @@ -3939,20 +4049,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { static void MULReduceShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = 1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL); + short v = av.reduceLanes(VectorOperators.MUL); + r[i] = v; + ra *= v; } } @@ -3960,8 +4065,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::MULReduce, ShortMaxVectorTests::MULReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MULReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MUL_IDENTITY; + + Assert.assertEquals((short) (id * id), id, + "MUL(MUL_IDENTITY, MUL_IDENTITY) != MUL_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) (id * x), x); + Assert.assertEquals((short) (x * id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) (id * x), x, + "MUL(MUL_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) (x * id), x, + "MUL(" + x + ", MUL_IDENTITY) != " + x); + } + } + static short MULReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 1; + short res = MUL_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res *= a[i]; @@ -3971,7 +4099,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short MULReduceAllMasked(short[] a, boolean[] mask) { - short res = 1; + short res = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res *= MULReduceMasked(a, i, mask); } @@ -3985,20 +4113,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = 1; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MUL_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MUL, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 1; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra *= av.reduceLanes(VectorOperators.MUL, vmask); + short v = av.reduceLanes(VectorOperators.MUL, vmask); + r[i] = v; + ra *= v; } } @@ -4007,7 +4130,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short MINReduce(short[] a, int idx) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) Math.min(res, a[i]); } @@ -4016,7 +4139,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short MINReduceAll(short[] a) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.min(res, MINReduce(a, i)); } @@ -4028,20 +4151,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { static void MINReduceShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.min(ra, av.reduceLanes(VectorOperators.MIN)); + short v = av.reduceLanes(VectorOperators.MIN); + r[i] = v; + ra = (short) Math.min(ra, v); } } @@ -4049,8 +4167,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::MINReduce, ShortMaxVectorTests::MINReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MINReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MIN_IDENTITY; + + Assert.assertEquals((short) Math.min(id, id), id, + "MIN(MIN_IDENTITY, MIN_IDENTITY) != MIN_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) Math.min(id, x), x); + Assert.assertEquals((short) Math.min(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) Math.min(id, x), x, + "MIN(MIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) Math.min(x, id), x, + "MIN(" + x + ", MIN_IDENTITY) != " + x); + } + } + static short MINReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) Math.min(res, a[i]); @@ -4060,7 +4201,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short MINReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.min(res, MINReduceMasked(a, i, mask)); } @@ -4074,20 +4215,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.min(ra, av.reduceLanes(VectorOperators.MIN, vmask)); + short v = av.reduceLanes(VectorOperators.MIN, vmask); + r[i] = v; + ra = (short) Math.min(ra, v); } } @@ -4096,7 +4232,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short MAXReduce(short[] a, int idx) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) Math.max(res, a[i]); } @@ -4105,7 +4241,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short MAXReduceAll(short[] a) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.max(res, MAXReduce(a, i)); } @@ -4117,20 +4253,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { static void MAXReduceShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.max(ra, av.reduceLanes(VectorOperators.MAX)); + short v = av.reduceLanes(VectorOperators.MAX); + r[i] = v; + ra = (short) Math.max(ra, v); } } @@ -4138,8 +4269,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::MAXReduce, ShortMaxVectorTests::MAXReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void MAXReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = MAX_IDENTITY; + + Assert.assertEquals((short) Math.max(id, id), id, + "MAX(MAX_IDENTITY, MAX_IDENTITY) != MAX_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) Math.max(id, x), x); + Assert.assertEquals((short) Math.max(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) Math.max(id, x), x, + "MAX(MAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) Math.max(x, id), x, + "MAX(" + x + ", MAX_IDENTITY) != " + x); + } + } + static short MAXReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) Math.max(res, a[i]); @@ -4149,7 +4303,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short MAXReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) Math.max(res, MAXReduceMasked(a, i, mask)); } @@ -4163,20 +4317,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = MAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.MAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) Math.max(ra, av.reduceLanes(VectorOperators.MAX, vmask)); + short v = av.reduceLanes(VectorOperators.MAX, vmask); + r[i] = v; + ra = (short) Math.max(ra, v); } } @@ -4185,7 +4334,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short UMINReduce(short[] a, int idx) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.minUnsigned(res, a[i]); } @@ -4194,7 +4343,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short UMINReduceAll(short[] a) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.minUnsigned(res, UMINReduce(a, i)); } @@ -4206,20 +4355,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { static void UMINReduceShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN)); + short v = av.reduceLanes(VectorOperators.UMIN); + r[i] = v; + ra = (short) VectorMath.minUnsigned(ra, v); } } @@ -4227,8 +4371,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::UMINReduce, ShortMaxVectorTests::UMINReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void UMINReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = UMIN_IDENTITY; + + Assert.assertEquals((short) VectorMath.minUnsigned(id, id), id, + "UMIN(UMIN_IDENTITY, UMIN_IDENTITY) != UMIN_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.minUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.minUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.minUnsigned(id, x), x, + "UMIN(UMIN_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.minUnsigned(x, id), x, + "UMIN(" + x + ", UMIN_IDENTITY) != " + x); + } + } + static short UMINReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.minUnsigned(res, a[i]); @@ -4238,7 +4405,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short UMINReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MAX_VALUE; + short res = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.minUnsigned(res, UMINReduceMasked(a, i, mask)); } @@ -4252,20 +4419,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MAX_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMIN_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMIN, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MAX_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.minUnsigned(ra, av.reduceLanes(VectorOperators.UMIN, vmask)); + short v = av.reduceLanes(VectorOperators.UMIN, vmask); + r[i] = v; + ra = (short) VectorMath.minUnsigned(ra, v); } } @@ -4274,7 +4436,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short UMAXReduce(short[] a, int idx) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.maxUnsigned(res, a[i]); } @@ -4283,7 +4445,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short UMAXReduceAll(short[] a) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.maxUnsigned(res, UMAXReduce(a, i)); } @@ -4295,20 +4457,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { static void UMAXReduceShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX)); + short v = av.reduceLanes(VectorOperators.UMAX); + r[i] = v; + ra = (short) VectorMath.maxUnsigned(ra, v); } } @@ -4316,8 +4473,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::UMAXReduce, ShortMaxVectorTests::UMAXReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void UMAXReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = UMAX_IDENTITY; + + Assert.assertEquals((short) VectorMath.maxUnsigned(id, id), id, + "UMAX(UMAX_IDENTITY, UMAX_IDENTITY) != UMAX_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.maxUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.maxUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.maxUnsigned(id, x), x, + "UMAX(UMAX_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.maxUnsigned(x, id), x, + "UMAX(" + x + ", UMAX_IDENTITY) != " + x); + } + } + static short UMAXReduceMasked(short[] a, int idx, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.maxUnsigned(res, a[i]); @@ -4327,7 +4507,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short UMAXReduceAllMasked(short[] a, boolean[] mask) { - short res = Short.MIN_VALUE; + short res = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.maxUnsigned(res, UMAXReduceMasked(a, i, mask)); } @@ -4341,20 +4521,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = Short.MIN_VALUE; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = UMAX_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.UMAX, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = Short.MIN_VALUE; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.maxUnsigned(ra, av.reduceLanes(VectorOperators.UMAX, vmask)); + short v = av.reduceLanes(VectorOperators.UMAX, vmask); + r[i] = v; + ra = (short) VectorMath.maxUnsigned(ra, v); } } @@ -4363,7 +4538,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduce(short[] a, int idx) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = firstNonZero(res, a[i]); } @@ -4372,7 +4547,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduceAll(short[] a) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduce(a, i)); } @@ -4384,20 +4559,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { static void FIRST_NONZEROReduceShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = fr.apply(SPECIES.length()); - short ra = (short) 0; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (short) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO)); + short v = av.reduceLanes(VectorOperators.FIRST_NONZERO); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4405,8 +4575,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::FIRST_NONZEROReduce, ShortMaxVectorTests::FIRST_NONZEROReduceAll); } + @Test(dataProvider = "shortUnaryOpProvider") + static void FIRST_NONZEROReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = FIRST_NONZERO_IDENTITY; + + Assert.assertEquals(firstNonZero(id, id), id, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, FIRST_NONZERO_IDENTITY) != FIRST_NONZERO_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(firstNonZero(id, x), x); + Assert.assertEquals(firstNonZero(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(firstNonZero(id, x), x, + "FIRST_NONZERO(FIRST_NONZERO_IDENTITY, " + x + ") != " + x); + Assert.assertEquals(firstNonZero(x, id), x, + "FIRST_NONZERO(" + x + ", FIRST_NONZERO_IDENTITY) != " + x); + } + } + static short FIRST_NONZEROReduceMasked(short[] a, int idx, boolean[] mask) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = firstNonZero(res, a[i]); @@ -4416,7 +4609,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short FIRST_NONZEROReduceAllMasked(short[] a, boolean[] mask) { - short res = (short) 0; + short res = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = firstNonZero(res, FIRST_NONZEROReduceMasked(a, i, mask)); } @@ -4430,20 +4623,15 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); - short ra = (short) 0; + short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = FIRST_NONZERO_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = (short) 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = firstNonZero(ra, av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask)); + short v = av.reduceLanes(VectorOperators.FIRST_NONZERO, vmask); + r[i] = v; + ra = firstNonZero(ra, v); } } @@ -4500,7 +4688,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short SUADDReduce(short[] a, int idx) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { res = (short) VectorMath.addSaturatingUnsigned(res, a[i]); } @@ -4509,7 +4697,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short SUADDReduceAll(short[] a) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.addSaturatingUnsigned(res, SUADDReduce(a, i)); } @@ -4524,17 +4712,12 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD)); + short v = av.reduceLanes(VectorOperators.SUADD); + r[i] = v; + ra = (short) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -4542,8 +4725,31 @@ public class ShortMaxVectorTests extends AbstractVectorTest { ShortMaxVectorTests::SUADDReduce, ShortMaxVectorTests::SUADDReduceAll); } + @Test(dataProvider = "shortSaturatingUnaryOpProvider") + static void SUADDReduceIdentityValueTests(IntFunction fa) { + short[] a = fa.apply(SPECIES.length()); + short id = SUADD_IDENTITY; + + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, id), id, + "SUADD(SUADD_IDENTITY, SUADD_IDENTITY) != SUADD_IDENTITY"); + + short x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, x), x); + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(id, x), x, + "SUADD(SUADD_IDENTITY, " + x + ") != " + x); + Assert.assertEquals((short) VectorMath.addSaturatingUnsigned(x, id), x, + "SUADD(" + x + ", SUADD_IDENTITY) != " + x); + } + } + static short SUADDReduceMasked(short[] a, int idx, boolean[] mask) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = idx; i < (idx + SPECIES.length()); i++) { if (mask[i % SPECIES.length()]) res = (short) VectorMath.addSaturatingUnsigned(res, a[i]); @@ -4553,7 +4759,7 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } static short SUADDReduceAllMasked(short[] a, boolean[] mask) { - short res = 0; + short res = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { res = (short) VectorMath.addSaturatingUnsigned(res, SUADDReduceMasked(a, i, mask)); } @@ -4569,17 +4775,12 @@ public class ShortMaxVectorTests extends AbstractVectorTest { short ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { + ra = SUADD_IDENTITY; for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.SUADD, vmask); - } - } - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - ra = 0; - for (int i = 0; i < a.length; i += SPECIES.length()) { - ShortVector av = ShortVector.fromArray(SPECIES, a, i); - ra = (short) VectorMath.addSaturatingUnsigned(ra, av.reduceLanes(VectorOperators.SUADD, vmask)); + short v = av.reduceLanes(VectorOperators.SUADD, vmask); + r[i] = v; + ra = (short) VectorMath.addSaturatingUnsigned(ra, v); } } @@ -6386,6 +6587,157 @@ public class ShortMaxVectorTests extends AbstractVectorTest { assertArraysEquals(r, a, mask, ShortMaxVectorTests::REVERSE_BYTES); } + static boolean band(boolean a, boolean b) { + return a & b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandShortMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.and(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, ShortMaxVectorTests::band); + } + + static boolean bor(boolean a, boolean b) { + return a | b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskorShortMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.or(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, ShortMaxVectorTests::bor); + } + + static boolean bxor(boolean a, boolean b) { + return a != b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskxorShortMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.xor(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, ShortMaxVectorTests::bxor); + } + + static boolean bandNot(boolean a, boolean b) { + return a & !b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskandNotShortMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.andNot(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, ShortMaxVectorTests::bandNot); + } + + static boolean beq(boolean a, boolean b) { + return a == b; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskeqShortMaxVectorTests(IntFunction fa, IntFunction fb) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.eq(bv).intoArray(r, i); + } + } + + assertArraysEquals(r, a, b, ShortMaxVectorTests::beq); + } + + static boolean unot(boolean a) { + return !a; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void masknotShortMaxVectorTests(IntFunction fa) { + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.not().intoArray(r, i); + } + } + + assertArraysEquals(r, a, ShortMaxVectorTests::unot); + } + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void maskFromToLongShortMaxVectorTests(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } + @Test(dataProvider = "shortCompareOpProvider") static void ltShortMaxVectorTestsBroadcastSmokeTest(IntFunction fa, IntFunction fb) { short[] a = fa.apply(SPECIES.length()); @@ -6685,115 +7037,22 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqualsShortMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEqualsShortMaxVectorTests(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndShortMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, ShortMaxVectorTests::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOrShortMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, ShortMaxVectorTests::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXorShortMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, ShortMaxVectorTests::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNotShortMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, ShortMaxVectorTests::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEqShortMaxVectorTestsSmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, ShortMaxVectorTests::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCodeShortMaxVectorTestsSmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -6898,7 +7157,6 @@ public class ShortMaxVectorTests extends AbstractVectorTest { } } - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/gen-template.sh b/test/jdk/jdk/incubator/vector/gen-template.sh index a6f794a5559..d2528b13b78 100644 --- a/test/jdk/jdk/incubator/vector/gen-template.sh +++ b/test/jdk/jdk/incubator/vector/gen-template.sh @@ -1,6 +1,6 @@ #!/bin/bash # -# Copyright (c) 2018, 2024, 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 @@ -73,6 +73,9 @@ binary_math_template="Binary-op-math" binary_math_broadcast_template="Binary-Broadcast-op-math" bool_reduction_scalar="BoolReduction-Scalar-op" bool_reduction_template="BoolReduction-op" +bool_binary_template="BoolBinary-op" +bool_unary_template="BoolUnary-op" +mask_fromtolong_template="Mask-FromToLong" with_op_template="With-Op" shift_template="Shift-op" shift_masked_template="Shift-Masked-op" @@ -230,7 +233,8 @@ function gen_op_tmpl { local gen_perf_tests=$generate_perf_tests if [[ $template == *"-Broadcast-"* ]] || [[ $template == "Miscellaneous" ]] || - [[ $template == *"Compare-Masked"* ]] || [[ $template == *"Compare-Broadcast"* ]]; then + [[ $template == *"Compare-Masked"* ]] || [[ $template == *"Compare-Broadcast"* ]] || + [[ $template == *"Mask-Binary"* ]]; then gen_perf_tests=false fi if [ $gen_perf_tests == true ]; then @@ -507,23 +511,23 @@ gen_binary_bcst_op_no_masked "MAX+max" "Math.max(a, b)" gen_saturating_binary_op_associative "SUADD" "VectorMath.addSaturatingUnsigned(a, b)" "BITWISE" # Reductions. -gen_reduction_op "AND" "\&" "BITWISE" "-1" -gen_reduction_op "OR" "|" "BITWISE" "0" -gen_reduction_op "XOR" "^" "BITWISE" "0" -gen_reduction_op "ADD" "+" "" "0" -gen_reduction_op "MUL" "*" "" "1" -gen_reduction_op_func "MIN" "(\$type\$) Math.min" "" "\$Wideboxtype\$.\$MaxValue\$" -gen_reduction_op_func "MAX" "(\$type\$) Math.max" "" "\$Wideboxtype\$.\$MinValue\$" -gen_reduction_op_func "UMIN" "(\$type\$) VectorMath.minUnsigned" "BITWISE" "\$Wideboxtype\$.\$MaxValue\$" -gen_reduction_op_func "UMAX" "(\$type\$) VectorMath.maxUnsigned" "BITWISE" "\$Wideboxtype\$.\$MinValue\$" -gen_reduction_op_func "FIRST_NONZERO" "firstNonZero" "" "(\$type\$) 0" +gen_reduction_op "AND" "\&" "BITWISE" "AND_IDENTITY" +gen_reduction_op "OR" "|" "BITWISE" "OR_IDENTITY" +gen_reduction_op "XOR" "^" "BITWISE" "XOR_IDENTITY" +gen_reduction_op "ADD" "+" "" "ADD_IDENTITY" +gen_reduction_op "MUL" "*" "" "MUL_IDENTITY" +gen_reduction_op_func "MIN" "(\$type\$) Math.min" "" "MIN_IDENTITY" +gen_reduction_op_func "MAX" "(\$type\$) Math.max" "" "MAX_IDENTITY" +gen_reduction_op_func "UMIN" "(\$type\$) VectorMath.minUnsigned" "BITWISE" "UMIN_IDENTITY" +gen_reduction_op_func "UMAX" "(\$type\$) VectorMath.maxUnsigned" "BITWISE" "UMAX_IDENTITY" +gen_reduction_op_func "FIRST_NONZERO" "firstNonZero" "" "FIRST_NONZERO_IDENTITY" # Boolean reductions. gen_bool_reduction_op "anyTrue" "|" "BITWISE" "false" gen_bool_reduction_op "allTrue" "\&" "BITWISE" "true" # Saturating reductions. -gen_saturating_reduction_op "SUADD" "(\$type\$) VectorMath.addSaturatingUnsigned" "BITWISE" "0" +gen_saturating_reduction_op "SUADD" "(\$type\$) VectorMath.addSaturatingUnsigned" "BITWISE" "SUADD_IDENTITY" #Insert gen_with_op "withLane" "" "" "" @@ -625,6 +629,15 @@ gen_unary_alu_op "REVERSE_BYTES" "\$Boxtype\$.reverseBytes(a)" "intOrLong" gen_unary_alu_op "REVERSE_BYTES" "\$Boxtype\$.reverseBytes(a)" "short" gen_unary_alu_op "REVERSE_BYTES" "a" "byte" +# Mask operations +gen_op_tmpl $bool_binary_template "and" "a \& b" +gen_op_tmpl $bool_binary_template "or" "a | b" +gen_op_tmpl $bool_binary_template "xor" "a != b" +gen_op_tmpl $bool_binary_template "andNot" "a \& !b" +gen_op_tmpl $bool_binary_template "eq" "a == b" +gen_op_tmpl $bool_unary_template "not" "!a" +gen_op_tmpl $mask_fromtolong_template "FromToLong" "" + # Miscellaneous Smoke Tests gen_op_tmpl $miscellaneous_template "MISC" "" "" diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-BoolBinary-op.template b/test/jdk/jdk/incubator/vector/templates/Kernel-BoolBinary-op.template new file mode 100644 index 00000000000..3f5bc428cdd --- /dev/null +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-BoolBinary-op.template @@ -0,0 +1,11 @@ + boolean[] a = fa.apply(SPECIES.length()); + boolean[] b = fb.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + VectorMask bv = SPECIES.loadMask(b, i); + av.[[TEST]](bv).intoArray(r, i); + } + } diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-BoolUnary-op.template b/test/jdk/jdk/incubator/vector/templates/Kernel-BoolUnary-op.template new file mode 100644 index 00000000000..836db281c1b --- /dev/null +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-BoolUnary-op.template @@ -0,0 +1,9 @@ + boolean[] a = fa.apply(SPECIES.length()); + boolean[] r = new boolean[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + VectorMask av = SPECIES.loadMask(a, i); + av.[[TEST]]().intoArray(r, i); + } + } diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-Masked-op-func.template b/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-Masked-op-func.template index bf03a4d0430..73e02bf68dd 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-Masked-op-func.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-Masked-op-func.template @@ -2,20 +2,15 @@ $type$[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask<$Wideboxtype$> vmask = VectorMask.fromArray(SPECIES, mask, 0); - $type$ ra = [[TEST_INIT]]; - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - for (int i = 0; i < a.length; i += SPECIES.length()) { - $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.[[TEST]], vmask); - } - } + $type$ ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { ra = [[TEST_INIT]]; for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - ra = [[TEST_OP]](ra, av.reduceLanes(VectorOperators.[[TEST]], vmask)); + $type$ v = av.reduceLanes(VectorOperators.[[TEST]], vmask); + r[i] = v; + ra = [[TEST_OP]](ra, v); } } diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-Masked-op.template b/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-Masked-op.template index f108491523e..82e20d594b6 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-Masked-op.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-Masked-op.template @@ -2,20 +2,15 @@ $type$[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask<$Wideboxtype$> vmask = VectorMask.fromArray(SPECIES, mask, 0); - $type$ ra = [[TEST_INIT]]; - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - for (int i = 0; i < a.length; i += SPECIES.length()) { - $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.[[TEST]], vmask); - } - } + $type$ ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { ra = [[TEST_INIT]]; for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - ra [[TEST_OP]]= av.reduceLanes(VectorOperators.[[TEST]], vmask); + $type$ v = av.reduceLanes(VectorOperators.[[TEST]], vmask); + r[i] = v; + ra [[TEST_OP]]= v; } } diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-op-func.template b/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-op-func.template index 7082ff0795e..94fae420cdd 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-op-func.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-op-func.template @@ -1,19 +1,14 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] r = fr.apply(SPECIES.length()); - $type$ ra = [[TEST_INIT]]; - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - for (int i = 0; i < a.length; i += SPECIES.length()) { - $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.[[TEST]]); - } - } + $type$ ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { ra = [[TEST_INIT]]; for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - ra = [[TEST_OP]](ra, av.reduceLanes(VectorOperators.[[TEST]])); + $type$ v = av.reduceLanes(VectorOperators.[[TEST]]); + r[i] = v; + ra = [[TEST_OP]](ra, v); } } diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-op.template b/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-op.template index 66250c09213..3edc2b27e3e 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-op.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-Reduction-op.template @@ -1,19 +1,14 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] r = fr.apply(SPECIES.length()); - $type$ ra = [[TEST_INIT]]; - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - for (int i = 0; i < a.length; i += SPECIES.length()) { - $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.[[TEST]]); - } - } + $type$ ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { ra = [[TEST_INIT]]; for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - ra [[TEST_OP]]= av.reduceLanes(VectorOperators.[[TEST]]); + $type$ v = av.reduceLanes(VectorOperators.[[TEST]]); + r[i] = v; + ra [[TEST_OP]]= v; } } diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-SaturatingReduction-Masked-op.template b/test/jdk/jdk/incubator/vector/templates/Kernel-SaturatingReduction-Masked-op.template index bf03a4d0430..73e02bf68dd 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-SaturatingReduction-Masked-op.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-SaturatingReduction-Masked-op.template @@ -2,20 +2,15 @@ $type$[] r = fr.apply(SPECIES.length()); boolean[] mask = fm.apply(SPECIES.length()); VectorMask<$Wideboxtype$> vmask = VectorMask.fromArray(SPECIES, mask, 0); - $type$ ra = [[TEST_INIT]]; - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - for (int i = 0; i < a.length; i += SPECIES.length()) { - $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.[[TEST]], vmask); - } - } + $type$ ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { ra = [[TEST_INIT]]; for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - ra = [[TEST_OP]](ra, av.reduceLanes(VectorOperators.[[TEST]], vmask)); + $type$ v = av.reduceLanes(VectorOperators.[[TEST]], vmask); + r[i] = v; + ra = [[TEST_OP]](ra, v); } } diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-SaturatingReduction-op.template b/test/jdk/jdk/incubator/vector/templates/Kernel-SaturatingReduction-op.template index 7082ff0795e..94fae420cdd 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-SaturatingReduction-op.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-SaturatingReduction-op.template @@ -1,19 +1,14 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] r = fr.apply(SPECIES.length()); - $type$ ra = [[TEST_INIT]]; - - for (int ic = 0; ic < INVOC_COUNT; ic++) { - for (int i = 0; i < a.length; i += SPECIES.length()) { - $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - r[i] = av.reduceLanes(VectorOperators.[[TEST]]); - } - } + $type$ ra = 0; for (int ic = 0; ic < INVOC_COUNT; ic++) { ra = [[TEST_INIT]]; for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); - ra = [[TEST_OP]](ra, av.reduceLanes(VectorOperators.[[TEST]])); + $type$ v = av.reduceLanes(VectorOperators.[[TEST]]); + r[i] = v; + ra = [[TEST_OP]](ra, v); } } diff --git a/test/jdk/jdk/incubator/vector/templates/Unit-BoolBinary-op.template b/test/jdk/jdk/incubator/vector/templates/Unit-BoolBinary-op.template new file mode 100644 index 00000000000..9ee79e05363 --- /dev/null +++ b/test/jdk/jdk/incubator/vector/templates/Unit-BoolBinary-op.template @@ -0,0 +1,10 @@ + + static boolean b[[TEST]](boolean a, boolean b) { + return [[TEST_OP]]; + } + + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void mask[[TEST]]$vectorteststype$(IntFunction fa, IntFunction fb) { +[[KERNEL]] + assertArraysEquals(r, a, b, $vectorteststype$::b[[TEST]]); + } diff --git a/test/jdk/jdk/incubator/vector/templates/Unit-BoolUnary-op.template b/test/jdk/jdk/incubator/vector/templates/Unit-BoolUnary-op.template new file mode 100644 index 00000000000..6b1f2185528 --- /dev/null +++ b/test/jdk/jdk/incubator/vector/templates/Unit-BoolUnary-op.template @@ -0,0 +1,10 @@ + + static boolean u[[TEST]](boolean a) { + return [[TEST_OP]]; + } + + @Test(dataProvider = "boolMaskUnaryOpProvider") + static void mask[[TEST]]$vectorteststype$(IntFunction fa) { +[[KERNEL]] + assertArraysEquals(r, a, $vectorteststype$::u[[TEST]]); + } diff --git a/test/jdk/jdk/incubator/vector/templates/Unit-Mask-FromToLong.template b/test/jdk/jdk/incubator/vector/templates/Unit-Mask-FromToLong.template new file mode 100644 index 00000000000..784ef5f81b9 --- /dev/null +++ b/test/jdk/jdk/incubator/vector/templates/Unit-Mask-FromToLong.template @@ -0,0 +1,27 @@ + + private static final long LONG_MASK_BITS = 0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length()); + + static void assertArraysEquals(long[] r, long[] a, long bits) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], a[i] & bits); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], a[i] & bits, "(" + a[i] + ") at index #" + i); + } + } + + @Test(dataProvider = "longMaskProvider") + static void mask[[TEST]]$vectorteststype$(IntFunction fa) { + long[] a = fa.apply(SPECIES.length()); + long[] r = new long[a.length]; + + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i++) { + VectorMask vmask = VectorMask.fromLong(SPECIES, a[i]); + r[i] = vmask.toLong(); + } + } + assertArraysEquals(r, a, LONG_MASK_BITS); + } diff --git a/test/jdk/jdk/incubator/vector/templates/Unit-Miscellaneous.template b/test/jdk/jdk/incubator/vector/templates/Unit-Miscellaneous.template index 9a020c66d52..460f7624f2c 100644 --- a/test/jdk/jdk/incubator/vector/templates/Unit-Miscellaneous.template +++ b/test/jdk/jdk/incubator/vector/templates/Unit-Miscellaneous.template @@ -382,115 +382,22 @@ } } - @Test(dataProvider = "maskCompareOpProvider") - static void maskEquals$vectorteststype$SmokeTest(IntFunction fa, IntFunction fb) { + @Test(dataProvider = "boolMaskBinaryOpProvider") + static void maskEquals$vectorteststype$(IntFunction fa, IntFunction fb) { boolean[] a = fa.apply(SPECIES.length()); boolean[] b = fb.apply(SPECIES.length()); - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - boolean equals = av.equals(bv); - int to = i + SPECIES.length(); - Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + for (int ic = 0; ic < INVOC_COUNT; ic++) { + for (int i = 0; i < a.length; i += SPECIES.length()) { + var av = SPECIES.loadMask(a, i); + var bv = SPECIES.loadMask(b, i); + boolean equals = av.equals(bv); + int to = i + SPECIES.length(); + Assert.assertEquals(equals, Arrays.equals(a, i, to, b, i, to)); + } } } - static boolean band(boolean a, boolean b) { - return a & b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAnd$vectorteststype$SmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.and(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, $vectorteststype$::band); - } - - static boolean bor(boolean a, boolean b) { - return a | b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskOr$vectorteststype$SmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.or(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, $vectorteststype$::bor); - } - - static boolean bxor(boolean a, boolean b) { - return a != b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskXor$vectorteststype$SmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.xor(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, $vectorteststype$::bxor); - } - - static boolean bandNot(boolean a, boolean b) { - return a & !b; - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskAndNot$vectorteststype$SmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.andNot(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, $vectorteststype$::bandNot); - } - - static boolean beq(boolean a, boolean b) { - return (a == b); - } - - @Test(dataProvider = "maskCompareOpProvider") - static void maskEq$vectorteststype$SmokeTest(IntFunction fa, IntFunction fb) { - boolean[] a = fa.apply(SPECIES.length()); - boolean[] b = fb.apply(SPECIES.length()); - boolean[] r = new boolean[a.length]; - - for (int i = 0; i < a.length; i += SPECIES.length()) { - var av = SPECIES.loadMask(a, i); - var bv = SPECIES.loadMask(b, i); - var cv = av.eq(bv); - cv.intoArray(r, i); - } - assertArraysEquals(r, a, b, $vectorteststype$::beq); - } - @Test(dataProvider = "maskProvider") static void maskHashCode$vectorteststype$SmokeTest(IntFunction fa) { boolean[] a = fa.apply(SPECIES.length()); @@ -595,25 +502,6 @@ } } -#if[!MaxBit] - @DataProvider - public static Object[][] longMaskProvider() { - return new Object[][]{ - {0xFFFFFFFFFFFFFFFFL}, - {0x0000000000000000L}, - {0x5555555555555555L}, - {0x0123456789abcdefL}, - }; - } - - @Test(dataProvider = "longMaskProvider") - static void maskFromToLong$vectorteststype$SmokeTest(long inputLong) { - var vmask = VectorMask.fromLong(SPECIES, inputLong); - long outputLong = vmask.toLong(); - Assert.assertEquals(outputLong, (inputLong & (((0xFFFFFFFFFFFFFFFFL >>> (64 - SPECIES.length())))))); - } -#end[!MaxBit] - @DataProvider public static Object[][] offsetProvider() { return new Object[][]{ diff --git a/test/jdk/jdk/incubator/vector/templates/Unit-Reduction-op-func.template b/test/jdk/jdk/incubator/vector/templates/Unit-Reduction-op-func.template index e6bcdb83c2e..c797ad907fb 100644 --- a/test/jdk/jdk/incubator/vector/templates/Unit-Reduction-op-func.template +++ b/test/jdk/jdk/incubator/vector/templates/Unit-Reduction-op-func.template @@ -5,3 +5,26 @@ assertReductionArraysEquals(r, ra, a, $vectorteststype$::[[TEST]]Reduce, $vectorteststype$::[[TEST]]ReduceAll); } + + @Test(dataProvider = "$type$UnaryOpProvider") + static void [[TEST]]ReduceIdentityValueTests(IntFunction<$type$[]> fa) { + $type$[] a = fa.apply(SPECIES.length()); + $type$ id = [[TEST_INIT]]; + + Assert.assertEquals([[TEST_OP]](id, id), id, + "[[TEST]]([[TEST_INIT]], [[TEST_INIT]]) != [[TEST_INIT]]"); + + $type$ x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals([[TEST_OP]](id, x), x); + Assert.assertEquals([[TEST_OP]](x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals([[TEST_OP]](id, x), x, + "[[TEST]]([[TEST_INIT]], " + x + ") != " + x); + Assert.assertEquals([[TEST_OP]](x, id), x, + "[[TEST]](" + x + ", [[TEST_INIT]]) != " + x); + } + } diff --git a/test/jdk/jdk/incubator/vector/templates/Unit-Reduction-op.template b/test/jdk/jdk/incubator/vector/templates/Unit-Reduction-op.template index 5638940045d..f8438fa58c8 100644 --- a/test/jdk/jdk/incubator/vector/templates/Unit-Reduction-op.template +++ b/test/jdk/jdk/incubator/vector/templates/Unit-Reduction-op.template @@ -9,3 +9,26 @@ $vectorteststype$::[[TEST]]Reduce, $vectorteststype$::[[TEST]]ReduceAll); #end[FP] } + + @Test(dataProvider = "$type$UnaryOpProvider") + static void [[TEST]]ReduceIdentityValueTests(IntFunction<$type$[]> fa) { + $type$[] a = fa.apply(SPECIES.length()); + $type$ id = [[TEST_INIT]]; + + Assert.assertEquals(($type$) (id [[TEST_OP]] id), id, + "[[TEST]]([[TEST_INIT]], [[TEST_INIT]]) != [[TEST_INIT]]"); + + $type$ x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals(($type$) (id [[TEST_OP]] x), x); + Assert.assertEquals(($type$) (x [[TEST_OP]] id), x); + } + } catch (AssertionError e) { + Assert.assertEquals(($type$) (id [[TEST_OP]] x), x, + "[[TEST]]([[TEST_INIT]], " + x + ") != " + x); + Assert.assertEquals(($type$) (x [[TEST_OP]] id), x, + "[[TEST]](" + x + ", [[TEST_INIT]]) != " + x); + } + } diff --git a/test/jdk/jdk/incubator/vector/templates/Unit-SaturatingReduction-op.template b/test/jdk/jdk/incubator/vector/templates/Unit-SaturatingReduction-op.template index fdd9e47167e..d961a29e5c8 100644 --- a/test/jdk/jdk/incubator/vector/templates/Unit-SaturatingReduction-op.template +++ b/test/jdk/jdk/incubator/vector/templates/Unit-SaturatingReduction-op.template @@ -5,3 +5,26 @@ assertReductionArraysEquals(r, ra, a, $vectorteststype$::[[TEST]]Reduce, $vectorteststype$::[[TEST]]ReduceAll); } + + @Test(dataProvider = "$type$SaturatingUnaryOpProvider") + static void [[TEST]]ReduceIdentityValueTests(IntFunction<$type$[]> fa) { + $type$[] a = fa.apply(SPECIES.length()); + $type$ id = [[TEST_INIT]]; + + Assert.assertEquals([[TEST_OP]](id, id), id, + "[[TEST]]([[TEST_INIT]], [[TEST_INIT]]) != [[TEST_INIT]]"); + + $type$ x = 0; + try { + for (int i = 0; i < a.length; i++) { + x = a[i]; + Assert.assertEquals([[TEST_OP]](id, x), x); + Assert.assertEquals([[TEST_OP]](x, id), x); + } + } catch (AssertionError e) { + Assert.assertEquals([[TEST_OP]](id, x), x, + "[[TEST]]([[TEST_INIT]], " + x + ") != " + x); + Assert.assertEquals([[TEST_OP]](x, id), x, + "[[TEST]](" + x + ", [[TEST_INIT]]) != " + x); + } + } diff --git a/test/jdk/jdk/incubator/vector/templates/Unit-header.template b/test/jdk/jdk/incubator/vector/templates/Unit-header.template index 33c52f18c1c..e1ec6624022 100644 --- a/test/jdk/jdk/incubator/vector/templates/Unit-header.template +++ b/test/jdk/jdk/incubator/vector/templates/Unit-header.template @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, 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 @@ -86,19 +86,37 @@ public class $vectorteststype$ extends AbstractVectorTest { #end[MaxBit] static final int INVOC_COUNT = Integer.getInteger("jdk.incubator.vector.test.loop-iterations", 100); - #if[MaxBit] + static VectorShape getMaxBit() { return VectorShape.S_Max_BIT; } private static final int Max = 256; // juts so we can do N/$bits$ #end[MaxBit] - #if[BITWISE] + private static final $type$ CONST_SHIFT = $Boxtype$.SIZE / 2; #end[BITWISE] + + // Identity values for reduction operations + private static final $type$ ADD_IDENTITY = ($type$)0; +#if[BITWISE] + private static final $type$ AND_IDENTITY = ($type$)-1; +#end[BITWISE] + private static final $type$ FIRST_NONZERO_IDENTITY = ($type$)0; + private static final $type$ MAX_IDENTITY = $Wideboxtype$.$MinValue$; + private static final $type$ MIN_IDENTITY = $Wideboxtype$.$MaxValue$; + private static final $type$ MUL_IDENTITY = ($type$)1; +#if[BITWISE] + private static final $type$ OR_IDENTITY = ($type$)0; + private static final $type$ SUADD_IDENTITY = ($type$)0; + private static final $type$ UMAX_IDENTITY = ($type$)0; // Minimum unsigned value + private static final $type$ UMIN_IDENTITY = ($type$)-1; // Maximum unsigned value + private static final $type$ XOR_IDENTITY = ($type$)0; +#end[BITWISE] #if[FP] + // for floating point addition reduction ops that may introduce rounding errors private static final $type$ RELATIVE_ROUNDING_ERROR_FACTOR_ADD = ($type$)10.0; @@ -490,6 +508,36 @@ relativeError)); } } + interface FBoolUnOp { + boolean apply(boolean a); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, FBoolUnOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i]), "(" + a[i] + ") at index #" + i); + } + } + + interface FBoolBinOp { + boolean apply(boolean a, boolean b); + } + + static void assertArraysEquals(boolean[] r, boolean[] a, boolean[] b, FBoolBinOp f) { + int i = 0; + try { + for (; i < a.length; i++) { + Assert.assertEquals(r[i], f.apply(a[i], b[i])); + } + } catch (AssertionError e) { + Assert.assertEquals(r[i], f.apply(a[i], b[i]), "(" + a[i] + ", " + b[i] + ") at index #" + i); + } + } + interface FBinOp { $type$ apply($type$ a, $type$ b); } @@ -1521,8 +1569,23 @@ relativeError)); } @DataProvider - public Object[][] maskCompareOpProvider() { - return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream().map(List::toArray). + public Object[][] longMaskProvider() { + return LONG_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskBinaryOpProvider() { + return BOOLEAN_MASK_COMPARE_GENERATOR_PAIRS.stream(). + map(List::toArray). + toArray(Object[][]::new); + } + + @DataProvider + public Object[][] boolMaskUnaryOpProvider() { + return BOOLEAN_MASK_GENERATORS.stream(). + map(f -> new Object[]{f}). toArray(Object[][]::new); } diff --git a/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java b/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java index dbcb30255a8..b86593d84ba 100644 --- a/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java +++ b/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java @@ -24,6 +24,7 @@ /** * @test * @requires vm.flagless + * @requires test.thread.factory == null * @library /test/lib * @modules java.base/jdk.internal.misc * jdk.zipfs diff --git a/test/jdk/jdk/internal/platform/docker/MetricsCpuTester.java b/test/jdk/jdk/internal/platform/docker/MetricsCpuTester.java index 62549e7b518..9ec9b2bbf0e 100644 --- a/test/jdk/jdk/internal/platform/docker/MetricsCpuTester.java +++ b/test/jdk/jdk/internal/platform/docker/MetricsCpuTester.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 diff --git a/test/jdk/jdk/internal/platform/docker/TestDockerBasic.java b/test/jdk/jdk/internal/platform/docker/TestDockerBasic.java index 9a531d692ed..bfc628a25fc 100644 --- a/test/jdk/jdk/internal/platform/docker/TestDockerBasic.java +++ b/test/jdk/jdk/internal/platform/docker/TestDockerBasic.java @@ -1,6 +1,6 @@ /* * Copyright (c) 2022, Red Hat, Inc. - * 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 @@ -30,6 +30,7 @@ * @requires container.support * @requires !vm.asan * @library /test/lib + * @modules java.base/jdk.internal.platform * @run main/timeout=360 TestDockerBasic */ @@ -42,10 +43,8 @@ public class TestDockerBasic { private static final String imageName = Common.imageName("javaDockerBasic"); public static void main(String[] args) throws Exception { - if (!DockerTestUtils.canTestDocker()) { - return; - } - + DockerTestUtils.checkCanTestDocker(); + DockerTestUtils.checkCanUseResourceLimits(); DockerTestUtils.buildJdkContainerImage(imageName); try { diff --git a/test/jdk/jdk/internal/platform/docker/TestDockerCpuMetrics.java b/test/jdk/jdk/internal/platform/docker/TestDockerCpuMetrics.java index ff039913b8f..042996a353b 100644 --- a/test/jdk/jdk/internal/platform/docker/TestDockerCpuMetrics.java +++ b/test/jdk/jdk/internal/platform/docker/TestDockerCpuMetrics.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 @@ -46,9 +46,8 @@ public class TestDockerCpuMetrics { private static final String imageName = Common.imageName("metrics-cpu"); public static void main(String[] args) throws Exception { - if (!DockerTestUtils.canTestDocker()) { - return; - } + DockerTestUtils.checkCanTestDocker(); + DockerTestUtils.checkCanUseResourceLimits(); // These tests create a docker image and run this image with // varying docker cpu options. The arguments passed to the docker diff --git a/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetrics.java b/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetrics.java index 2afb5ed93b1..12f90d65516 100644 --- a/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetrics.java +++ b/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetrics.java @@ -45,9 +45,8 @@ public class TestDockerMemoryMetrics { private static final String imageName = Common.imageName("metrics-memory"); public static void main(String[] args) throws Exception { - if (!DockerTestUtils.canTestDocker()) { - return; - } + DockerTestUtils.checkCanTestDocker(); + DockerTestUtils.checkCanUseResourceLimits(); // These tests create a docker image and run this image with // varying docker memory options. The arguments passed to the docker @@ -82,9 +81,7 @@ public class TestDockerMemoryMetrics { testMemorySoftLimit("500m","200m"); } finally { - if (!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) { - DockerTestUtils.removeDockerImage(imageName); - } + DockerTestUtils.removeDockerImage(imageName); } } diff --git a/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetricsSubgroup.java b/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetricsSubgroup.java index f9dd405891c..7d5dbca6f7c 100644 --- a/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetricsSubgroup.java +++ b/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetricsSubgroup.java @@ -58,10 +58,7 @@ public class TestDockerMemoryMetricsSubgroup { System.out.println("Cgroup not configured."); return; } - if (!DockerTestUtils.canTestDocker()) { - System.out.println("Unable to run docker tests."); - return; - } + DockerTestUtils.checkCanTestDocker(); ContainerRuntimeVersionTestUtils.checkContainerVersionSupported(); diff --git a/test/jdk/jdk/internal/platform/docker/TestGetFreeSwapSpaceSize.java b/test/jdk/jdk/internal/platform/docker/TestGetFreeSwapSpaceSize.java index dc70fe32b16..6e07d2e9ed5 100644 --- a/test/jdk/jdk/internal/platform/docker/TestGetFreeSwapSpaceSize.java +++ b/test/jdk/jdk/internal/platform/docker/TestGetFreeSwapSpaceSize.java @@ -29,9 +29,11 @@ * @requires container.support * @requires !vm.asan * @library /test/lib + * @modules java.base/jdk.internal.platform * @build GetFreeSwapSpaceSize * @run driver/timeout=480 TestGetFreeSwapSpaceSize */ + import jdk.test.lib.containers.docker.Common; import jdk.test.lib.containers.docker.DockerRunOptions; import jdk.test.lib.containers.docker.DockerTestUtils; @@ -41,10 +43,8 @@ public class TestGetFreeSwapSpaceSize { private static final String imageName = Common.imageName("osbeanSwapSpace"); public static void main(String[] args) throws Exception { - if (!DockerTestUtils.canTestDocker()) { - return; - } - + DockerTestUtils.checkCanTestDocker(); + DockerTestUtils.checkCanUseResourceLimits(); DockerTestUtils.buildJdkContainerImage(imageName); try { @@ -53,9 +53,7 @@ public class TestGetFreeSwapSpaceSize { "150M", Integer.toString(0) ); } finally { - if (!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) { - DockerTestUtils.removeDockerImage(imageName); - } + DockerTestUtils.removeDockerImage(imageName); } } diff --git a/test/jdk/jdk/internal/platform/docker/TestLimitsUpdating.java b/test/jdk/jdk/internal/platform/docker/TestLimitsUpdating.java index e4decb7f903..a42eee358c3 100644 --- a/test/jdk/jdk/internal/platform/docker/TestLimitsUpdating.java +++ b/test/jdk/jdk/internal/platform/docker/TestLimitsUpdating.java @@ -55,18 +55,14 @@ public class TestLimitsUpdating { private static final String imageName = Common.imageName("limitsUpdatingJDK"); public static void main(String[] args) throws Exception { - if (!DockerTestUtils.canTestDocker()) { - return; - } - + DockerTestUtils.checkCanTestDocker(); + DockerTestUtils.checkCanUseResourceLimits(); DockerTestUtils.buildJdkContainerImage(imageName); try { testLimitUpdates(); } finally { - if (!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) { - DockerTestUtils.removeDockerImage(imageName); - } + DockerTestUtils.removeDockerImage(imageName); } } diff --git a/test/jdk/jdk/internal/platform/docker/TestPidsLimit.java b/test/jdk/jdk/internal/platform/docker/TestPidsLimit.java index 033562b3951..0313fcc582d 100644 --- a/test/jdk/jdk/internal/platform/docker/TestPidsLimit.java +++ b/test/jdk/jdk/internal/platform/docker/TestPidsLimit.java @@ -30,6 +30,7 @@ * @requires container.support * @requires !vm.asan * @library /test/lib + * @modules java.base/jdk.internal.platform * @build TestPidsLimit * @run driver/timeout=480 TestPidsLimit */ @@ -49,10 +50,8 @@ public class TestPidsLimit { private static final int UNLIMITED_PIDS_DOCKER = -1; public static void main(String[] args) throws Exception { - if (!DockerTestUtils.canTestDocker()) { - return; - } - + DockerTestUtils.checkCanTestDocker(); + DockerTestUtils.checkCanUseResourceLimits(); DockerTestUtils.buildJdkContainerImage(imageName); try { @@ -60,9 +59,7 @@ public class TestPidsLimit { testPidsLimit("2000"); testPidsLimit("Unlimited"); } finally { - if (!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) { - DockerTestUtils.removeDockerImage(imageName); - } + DockerTestUtils.removeDockerImage(imageName); } } diff --git a/test/jdk/jdk/internal/platform/docker/TestSystemMetrics.java b/test/jdk/jdk/internal/platform/docker/TestSystemMetrics.java index 49ec5663478..1af38843a5c 100644 --- a/test/jdk/jdk/internal/platform/docker/TestSystemMetrics.java +++ b/test/jdk/jdk/internal/platform/docker/TestSystemMetrics.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 @@ -42,10 +42,7 @@ public class TestSystemMetrics { private static final String imageName = Common.imageName("metrics"); public static void main(String[] args) throws Exception { - if (!DockerTestUtils.canTestDocker()) { - return; - } - + DockerTestUtils.checkCanTestDocker(); DockerTestUtils.buildJdkContainerImage(imageName); try { diff --git a/test/jdk/jdk/internal/platform/docker/TestUseContainerSupport.java b/test/jdk/jdk/internal/platform/docker/TestUseContainerSupport.java index d8d300401a0..d1a43a2ba94 100644 --- a/test/jdk/jdk/internal/platform/docker/TestUseContainerSupport.java +++ b/test/jdk/jdk/internal/platform/docker/TestUseContainerSupport.java @@ -1,6 +1,6 @@ /* * Copyright (c) 2020, Red Hat, Inc. - * 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 @@ -42,10 +42,7 @@ public class TestUseContainerSupport { private static final String imageName = Common.imageName("useContainerSupport"); public static void main(String[] args) throws Exception { - if (!DockerTestUtils.canTestDocker()) { - return; - } - + DockerTestUtils.checkCanTestDocker(); DockerTestUtils.buildJdkContainerImage(imageName); try { diff --git a/test/jdk/jdk/internal/vm/Continuation/OSRWithManyLocals.java b/test/jdk/jdk/internal/vm/Continuation/OSRWithManyLocals.java new file mode 100644 index 00000000000..2a8d4e91001 --- /dev/null +++ b/test/jdk/jdk/internal/vm/Continuation/OSRWithManyLocals.java @@ -0,0 +1,90 @@ +/* +* 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 8372591 +* @summary Test freeze/thaw of OSR frame from method with many locals +* @requires vm.continuations +* @requires vm.compMode != "Xint" & vm.compMode != "Xcomp" +* @modules java.base/jdk.internal.vm +* @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 -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI OSRWithManyLocals +*/ + +import jdk.internal.vm.Continuation; +import jdk.internal.vm.ContinuationScope; + +import jdk.test.lib.Asserts; +import java.lang.reflect.Method; +import jdk.test.whitebox.WhiteBox; + +public class OSRWithManyLocals { + static final WhiteBox wb = WhiteBox.getWhiteBox(); + static final ContinuationScope FOO = new ContinuationScope() {}; + static final Method foo = getMethod("foo"); + + public static void main(String[] args) throws Exception { + runCont(new Continuation(FOO, () -> warmUp())); + runCont(new Continuation(FOO, () -> foo())); + } + + public static void runCont(Continuation cont) { + while (!cont.isDone()) { + cont.run(); + } + } + + public static void warmUp() { + // Trigger compilation of Continuation.yield/yield0 + for (int i = 0; i < 10_000; i++) { + Continuation.yield(FOO); + } + } + + public static void foo() { + // Declare lots of locals so that size of OSR foo + Continuation.yield/yield0 + // frames is less than (foo_sender.unextended_sp() - foo_sender.sp()). + double d1=1,d2=2,d3=3,d4=4,d5=5,d6=6,d7=7,d8=8,d9=9,d10=10,d11=11,d12=12,d13=13,d14=14,d15=15,d16=16,d17=17,d18=18; + double d19=19,d20=20,d21=21,d22=22,d23=23,d24=24,d25=25,d26=26,d27=27,d28=28,d29=29,d30=30,d31=31,d32=32,d33=33,d34=34; + double d35=35,d36=36,d37=37,d38=38,d39=39,d40=40,d41=41,d42=42,d43=43,d44=44,d45=45,d46=46,d47=47,d48=48,d49=49,d50=50; + double d51=51,d52=52,d53=53,d54=54,d55=55,d56=56,d57=57,d58=58,d59=59,d60=60,d61=61,d62=62,d63=63,d64=64,d65=65,d66=66; + double d67=67,d68=68,d69=69,d70=70,d71=71,d72=72,d73=73,d74=74,d75=75,d76=76,d77=77,d78=78,d79=79,d80=80,d81=81,d82=82; + + // Provoke OSR compilation. After we verified the method was compiled keep looping + // until we trigger the _backedge_counter overflow to actually trigger OSR. + for (int i = 0; !wb.isMethodCompiled(foo, true) || i++ < 2_000;) { + } + Continuation.yield(FOO); + } + + static Method getMethod(String method) { + try { + return OSRWithManyLocals.class.getMethod(method); + } catch (Exception e) { + throw new RuntimeException("Exception: couldn't found method " + method + ". " + e.getMessage()); + } + } +} diff --git a/test/jdk/jdk/jfr/api/consumer/TestRecordedClass.java b/test/jdk/jdk/jfr/api/consumer/TestRecordedClass.java index 003e8c91edd..8717db370df 100644 --- a/test/jdk/jdk/jfr/api/consumer/TestRecordedClass.java +++ b/test/jdk/jdk/jfr/api/consumer/TestRecordedClass.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 diff --git a/test/jdk/jdk/jfr/api/consumer/TestRecordedFrameType.java b/test/jdk/jdk/jfr/api/consumer/TestRecordedFrameType.java index c988f37bd0b..e434a5baa8d 100644 --- a/test/jdk/jdk/jfr/api/consumer/TestRecordedFrameType.java +++ b/test/jdk/jdk/jfr/api/consumer/TestRecordedFrameType.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 diff --git a/test/jdk/jdk/jfr/api/consumer/TestRecordingFileSanitization.java b/test/jdk/jdk/jfr/api/consumer/TestRecordingFileSanitization.java index dfa39b4ad85..cf0d7386386 100644 --- a/test/jdk/jdk/jfr/api/consumer/TestRecordingFileSanitization.java +++ b/test/jdk/jdk/jfr/api/consumer/TestRecordingFileSanitization.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 diff --git a/test/jdk/jdk/jfr/api/consumer/TestRecordingFileWrite.java b/test/jdk/jdk/jfr/api/consumer/TestRecordingFileWrite.java index 5fc0dab0d30..a804cc58a88 100644 --- a/test/jdk/jdk/jfr/api/consumer/TestRecordingFileWrite.java +++ b/test/jdk/jdk/jfr/api/consumer/TestRecordingFileWrite.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 diff --git a/test/jdk/jdk/jfr/api/consumer/log/TestContent.java b/test/jdk/jdk/jfr/api/consumer/log/TestContent.java index 75a2b98ac96..4b552af905b 100644 --- a/test/jdk/jdk/jfr/api/consumer/log/TestContent.java +++ b/test/jdk/jdk/jfr/api/consumer/log/TestContent.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 diff --git a/test/jdk/jdk/jfr/api/consumer/log/TestDiskOnOff.java b/test/jdk/jdk/jfr/api/consumer/log/TestDiskOnOff.java index 220820e3c99..34126e9a979 100644 --- a/test/jdk/jdk/jfr/api/consumer/log/TestDiskOnOff.java +++ b/test/jdk/jdk/jfr/api/consumer/log/TestDiskOnOff.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 diff --git a/test/jdk/jdk/jfr/api/consumer/log/TestDynamicStart.java b/test/jdk/jdk/jfr/api/consumer/log/TestDynamicStart.java index e598d4302a1..43923f8ad60 100644 --- a/test/jdk/jdk/jfr/api/consumer/log/TestDynamicStart.java +++ b/test/jdk/jdk/jfr/api/consumer/log/TestDynamicStart.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 diff --git a/test/jdk/jdk/jfr/api/consumer/log/TestMemoryDiskTransition.java b/test/jdk/jdk/jfr/api/consumer/log/TestMemoryDiskTransition.java index 6ffb22a38eb..4e10c74625f 100644 --- a/test/jdk/jdk/jfr/api/consumer/log/TestMemoryDiskTransition.java +++ b/test/jdk/jdk/jfr/api/consumer/log/TestMemoryDiskTransition.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 diff --git a/test/jdk/jdk/jfr/api/consumer/log/TestMemoryOnly.java b/test/jdk/jdk/jfr/api/consumer/log/TestMemoryOnly.java index 618dbaffad8..5ff6305384a 100644 --- a/test/jdk/jdk/jfr/api/consumer/log/TestMemoryOnly.java +++ b/test/jdk/jdk/jfr/api/consumer/log/TestMemoryOnly.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 diff --git a/test/jdk/jdk/jfr/api/consumer/log/TestSystemEvents.java b/test/jdk/jdk/jfr/api/consumer/log/TestSystemEvents.java index 8d90684e523..6df0d82a11e 100644 --- a/test/jdk/jdk/jfr/api/consumer/log/TestSystemEvents.java +++ b/test/jdk/jdk/jfr/api/consumer/log/TestSystemEvents.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 diff --git a/test/jdk/jdk/jfr/api/consumer/log/TestTruncation.java b/test/jdk/jdk/jfr/api/consumer/log/TestTruncation.java index d2f6bf5b051..2741a3beca7 100644 --- a/test/jdk/jdk/jfr/api/consumer/log/TestTruncation.java +++ b/test/jdk/jdk/jfr/api/consumer/log/TestTruncation.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 diff --git a/test/jdk/jdk/jfr/api/consumer/log/TestUserEvents.java b/test/jdk/jdk/jfr/api/consumer/log/TestUserEvents.java index 62feb2b9dbd..8cfee314ad2 100644 --- a/test/jdk/jdk/jfr/api/consumer/log/TestUserEvents.java +++ b/test/jdk/jdk/jfr/api/consumer/log/TestUserEvents.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 diff --git a/test/jdk/jdk/jfr/api/consumer/log/TestVerbosity.java b/test/jdk/jdk/jfr/api/consumer/log/TestVerbosity.java index 841f990a8d3..d617568a996 100644 --- a/test/jdk/jdk/jfr/api/consumer/log/TestVerbosity.java +++ b/test/jdk/jdk/jfr/api/consumer/log/TestVerbosity.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 diff --git a/test/jdk/jdk/jfr/api/consumer/log/TestWithStreaming.java b/test/jdk/jdk/jfr/api/consumer/log/TestWithStreaming.java index 78b4e959182..d1a4148d795 100644 --- a/test/jdk/jdk/jfr/api/consumer/log/TestWithStreaming.java +++ b/test/jdk/jdk/jfr/api/consumer/log/TestWithStreaming.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 diff --git a/test/jdk/jdk/jfr/api/consumer/recordingstream/TestDump.java b/test/jdk/jdk/jfr/api/consumer/recordingstream/TestDump.java index cf4dad5477e..249275a39c1 100644 --- a/test/jdk/jdk/jfr/api/consumer/recordingstream/TestDump.java +++ b/test/jdk/jdk/jfr/api/consumer/recordingstream/TestDump.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 diff --git a/test/jdk/jdk/jfr/api/consumer/recordingstream/TestRecordingName.java b/test/jdk/jdk/jfr/api/consumer/recordingstream/TestRecordingName.java index 18f23375478..41b6a8acab6 100644 --- a/test/jdk/jdk/jfr/api/consumer/recordingstream/TestRecordingName.java +++ b/test/jdk/jdk/jfr/api/consumer/recordingstream/TestRecordingName.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. * Copyright (c) 2020, NTT DATA. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryAfterStart.java b/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryAfterStart.java index 2e0aceb3825..a380d87a750 100644 --- a/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryAfterStart.java +++ b/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryAfterStart.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 diff --git a/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryBeforeStart.java b/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryBeforeStart.java index 180a0098843..bea5fc57145 100644 --- a/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryBeforeStart.java +++ b/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryBeforeStart.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 diff --git a/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryLastModified.java b/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryLastModified.java index 6a9e8376ed2..bf9ed2c0f2c 100644 --- a/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryLastModified.java +++ b/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryLastModified.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 diff --git a/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryMultipleProcesses.java b/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryMultipleProcesses.java index 95f6c5d4e59..c00505b7f2d 100644 --- a/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryMultipleProcesses.java +++ b/test/jdk/jdk/jfr/api/consumer/streaming/TestBaseRepositoryMultipleProcesses.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 diff --git a/test/jdk/jdk/jfr/api/recording/dump/TestDumpDevNull.java b/test/jdk/jdk/jfr/api/recording/dump/TestDumpDevNull.java index b83f9686868..196ecf98b53 100644 --- a/test/jdk/jdk/jfr/api/recording/dump/TestDumpDevNull.java +++ b/test/jdk/jdk/jfr/api/recording/dump/TestDumpDevNull.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 diff --git a/test/jdk/jdk/jfr/api/recording/dump/TestDumpOverwrite.java b/test/jdk/jdk/jfr/api/recording/dump/TestDumpOverwrite.java new file mode 100644 index 00000000000..050b68eb538 --- /dev/null +++ b/test/jdk/jdk/jfr/api/recording/dump/TestDumpOverwrite.java @@ -0,0 +1,79 @@ +/* + * 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.api.recording.dump; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import jdk.jfr.Recording; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordingFile; +import jdk.test.lib.Asserts; +import jdk.test.lib.jfr.SimpleEventHelper; +import jdk.test.lib.jfr.Events; + +/** + * @test + * @summary Test that multiple dumps to the same file by ongoing recordings do not mangle data. + * @requires vm.flagless + * @requires vm.hasJFR + * @library /test/lib + * @run main/othervm jdk.jfr.api.recording.dump.TestDumpOverwrite + */ +public class TestDumpOverwrite { + private static Path DUMP_PATH = Paths.get(".", "rec_TestDumpOverwrite.jfr"); + public static void main(String[] args) throws Exception { + Recording recording1 = new Recording(); + Recording recording2 = new Recording(); + SimpleEventHelper.enable(recording1, true); + SimpleEventHelper.enable(recording2, true); + recording1.setDestination(DUMP_PATH); + recording2.setDestination(DUMP_PATH); + + int actualId = 0; + recording1.start(); + SimpleEventHelper.createEvent(actualId++); + recording2.start(); + SimpleEventHelper.createEvent(actualId++); + // This is results in the initial write to the dump destination + recording2.stop(); + SimpleEventHelper.createEvent(actualId++); + recording2.close(); + SimpleEventHelper.createEvent(actualId++); + // This should first wipe the data previously written by recording2. + recording1.stop(); + recording1.close(); + + Asserts.assertTrue(Files.exists(DUMP_PATH), "Recording file does not exist: " + DUMP_PATH); + + // Verify events are read in order without duplicates (otherwise chunks may be out of order). + // If the dump file is not being overwritten correctly, we will see event ids: 1, 0, 1, 2, 3. + int expectedId = 0; + for (RecordedEvent event : RecordingFile.readAllEvents(DUMP_PATH)) { + Events.assertField(event, "id").equal(expectedId++); + } + Asserts.assertTrue(expectedId == actualId, "incorrect number of events found"); + } +} diff --git a/test/jdk/jdk/jfr/event/allocation/TestObjectAllocationSampleEvent.java b/test/jdk/jdk/jfr/event/allocation/TestObjectAllocationSampleEvent.java index e7effa02382..f69c56ca528 100644 --- a/test/jdk/jdk/jfr/event/allocation/TestObjectAllocationSampleEvent.java +++ b/test/jdk/jdk/jfr/event/allocation/TestObjectAllocationSampleEvent.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 diff --git a/test/jdk/jdk/jfr/event/compiler/TestCompilerQueueUtilization.java b/test/jdk/jdk/jfr/event/compiler/TestCompilerQueueUtilization.java index d4e4e12eaa3..abd761ec592 100644 --- a/test/jdk/jdk/jfr/event/compiler/TestCompilerQueueUtilization.java +++ b/test/jdk/jdk/jfr/event/compiler/TestCompilerQueueUtilization.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 diff --git a/test/jdk/jdk/jfr/event/gc/detailed/TestG1InvalidHeapRegionTypeChangeEvent.java b/test/jdk/jdk/jfr/event/gc/detailed/TestG1InvalidHeapRegionTypeChangeEvent.java index 7939a769ccb..3a63f516bf3 100644 --- a/test/jdk/jdk/jfr/event/gc/detailed/TestG1InvalidHeapRegionTypeChangeEvent.java +++ b/test/jdk/jdk/jfr/event/gc/detailed/TestG1InvalidHeapRegionTypeChangeEvent.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 diff --git a/test/jdk/jdk/jfr/event/gc/detailed/TestGCCPUTimeEvent.java b/test/jdk/jdk/jfr/event/gc/detailed/TestGCCPUTimeEvent.java index cd9f0046cbb..5fc6d7c87ab 100644 --- a/test/jdk/jdk/jfr/event/gc/detailed/TestGCCPUTimeEvent.java +++ b/test/jdk/jdk/jfr/event/gc/detailed/TestGCCPUTimeEvent.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 diff --git a/test/jdk/jdk/jfr/event/gc/detailed/TestGCHeapMemoryPoolUsageEvent.java b/test/jdk/jdk/jfr/event/gc/detailed/TestGCHeapMemoryPoolUsageEvent.java index 1286c53d938..3e988d69b23 100644 --- a/test/jdk/jdk/jfr/event/gc/detailed/TestGCHeapMemoryPoolUsageEvent.java +++ b/test/jdk/jdk/jfr/event/gc/detailed/TestGCHeapMemoryPoolUsageEvent.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 diff --git a/test/jdk/jdk/jfr/event/gc/heapsummary/HeapSummaryEventAllGcs.java b/test/jdk/jdk/jfr/event/gc/heapsummary/HeapSummaryEventAllGcs.java index 16dd6f44fed..2baf87eae31 100644 --- a/test/jdk/jdk/jfr/event/gc/heapsummary/HeapSummaryEventAllGcs.java +++ b/test/jdk/jdk/jfr/event/gc/heapsummary/HeapSummaryEventAllGcs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2023, 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 diff --git a/test/jdk/jdk/jfr/event/io/TestAsynchronousFileChannelEvents.java b/test/jdk/jdk/jfr/event/io/TestAsynchronousFileChannelEvents.java index e0752c6d319..f337d315ba6 100644 --- a/test/jdk/jdk/jfr/event/io/TestAsynchronousFileChannelEvents.java +++ b/test/jdk/jdk/jfr/event/io/TestAsynchronousFileChannelEvents.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 diff --git a/test/jdk/jdk/jfr/event/io/TestSocketAdapterEvents.java b/test/jdk/jdk/jfr/event/io/TestSocketAdapterEvents.java index 77a083ad8fe..6b45d060075 100644 --- a/test/jdk/jdk/jfr/event/io/TestSocketAdapterEvents.java +++ b/test/jdk/jdk/jfr/event/io/TestSocketAdapterEvents.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 diff --git a/test/jdk/jdk/jfr/event/oldobject/TestEmergencyDumpAtOOM.java b/test/jdk/jdk/jfr/event/oldobject/TestEmergencyDumpAtOOM.java index d540acd853b..b3630fa7f77 100644 --- a/test/jdk/jdk/jfr/event/oldobject/TestEmergencyDumpAtOOM.java +++ b/test/jdk/jdk/jfr/event/oldobject/TestEmergencyDumpAtOOM.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. * Copyright (c) 2025, NTT DATA. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -98,8 +98,8 @@ public class TestEmergencyDumpAtOOM { // Check OldObjectSample events if (oldObjects.get() > 0L) { if (shouldCrash) { - Asserts.assertEquals("VM Error", shutdownReason.get()); - Asserts.assertEquals("Out of Memory", dumpReason.get()); + Asserts.assertEquals("CrashOnOutOfMemoryError", shutdownReason.get()); + Asserts.assertEquals("CrashOnOutOfMemoryError", dumpReason.get()); } else { Asserts.assertEquals("No remaining non-daemon Java threads", shutdownReason.get()); } diff --git a/test/jdk/jdk/jfr/event/profiling/BaseTestFullStackTrace.java b/test/jdk/jdk/jfr/event/profiling/BaseTestFullStackTrace.java index de211b8c454..aadd9dded7e 100644 --- a/test/jdk/jdk/jfr/event/profiling/BaseTestFullStackTrace.java +++ b/test/jdk/jdk/jfr/event/profiling/BaseTestFullStackTrace.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2023, 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 diff --git a/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSampleNative.java b/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSampleNative.java index 1617bce4ba3..b79edfeac10 100644 --- a/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSampleNative.java +++ b/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSampleNative.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 diff --git a/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSamplingLongPeriod.java b/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSamplingLongPeriod.java index 69d32d48282..cbaf8d707e8 100644 --- a/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSamplingLongPeriod.java +++ b/test/jdk/jdk/jfr/event/profiling/TestCPUTimeSamplingLongPeriod.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, 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 diff --git a/test/jdk/jdk/jfr/event/runtime/TestBackToBackSensitive.java b/test/jdk/jdk/jfr/event/runtime/TestBackToBackSensitive.java index 147caee82ea..fbef91e73aa 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestBackToBackSensitive.java +++ b/test/jdk/jdk/jfr/event/runtime/TestBackToBackSensitive.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,8 +34,9 @@ import jdk.jfr.Configuration; import jdk.jfr.Event; import jdk.jfr.Recording; import jdk.jfr.StackTrace; +import jdk.jfr.consumer.EventStream; import jdk.jfr.consumer.RecordedClassLoader; -import jdk.jfr.consumer.RecordingStream; +import jdk.test.lib.jfr.TestClassLoader; /** * @test @@ -52,28 +53,17 @@ public class TestBackToBackSensitive { static class FillEvent extends Event { String message; } + public static Object OBJECT; public static void main(String... arg) throws Exception { - Set threadDumps = Collections.synchronizedSet(new LinkedHashSet<>()); - Set classLoaderStatistics = Collections.synchronizedSet(new LinkedHashSet<>()); - Set physicalMemory = Collections.synchronizedSet(new LinkedHashSet<>()); - + TestClassLoader loader = new TestClassLoader(); + Class clazz = loader.loadClass(TestBackToBackSensitive.class.getName()); + String classLoaderName = loader.getClass().getName(); + OBJECT = clazz.getDeclaredConstructor().newInstance(); Configuration configuration = Configuration.getConfiguration("default"); - try (RecordingStream r1 = new RecordingStream(configuration)) { - r1.setMaxSize(Long.MAX_VALUE); - r1.onEvent("jdk.ThreadDump", e -> threadDumps.add(e.getStartTime())); - r1.onEvent("jdk.ClassLoaderStatistics", e -> { - RecordedClassLoader cl = e.getValue("classLoader"); - if (cl != null) { - if (cl.getType().getName().contains("PlatformClassLoader")) { - classLoaderStatistics.add(e.getStartTime()); - System.out.println("Class loader" + e); - } - } - }); - r1.onEvent("jdk.PhysicalMemory", e -> physicalMemory.add(e.getStartTime())); + try (Recording r1 = new Recording(configuration)) { // Start chunk 1 - r1.startAsync(); + r1.start(); try (Recording r2 = new Recording()) { // Start chunk 2 r2.start(); @@ -86,6 +76,25 @@ public class TestBackToBackSensitive { f.commit(); } r1.stop(); + Path file = Path.of("file.jfr"); + r1.dump(file); + Set threadDumps = new LinkedHashSet<>(); + Set classLoaderStatistics = new LinkedHashSet<>(); + Set physicalMemory = new LinkedHashSet<>(); + try (EventStream es = EventStream.openFile(file)) { + es.onEvent("jdk.ThreadDump", e -> threadDumps.add(e.getStartTime())); + es.onEvent("jdk.ClassLoaderStatistics", e -> { + RecordedClassLoader cl = e.getValue("classLoader"); + if (cl != null) { + if (cl.getType().getName().equals(classLoaderName)) { + classLoaderStatistics.add(e.getStartTime()); + System.out.println("Class loader" + e); + } + } + }); + es.onEvent("jdk.PhysicalMemory", e -> physicalMemory.add(e.getStartTime())); + es.start(); + } long chunkFiles = filesInRepository(); System.out.println("Number of chunk files: " + chunkFiles); // When jdk.PhysicalMemory is expected to be emitted: @@ -93,15 +102,15 @@ public class TestBackToBackSensitive { // Chunk 2: begin, end // Chunk 3: begin, end // Chunk 4: begin, end - assertCount(r1, "jdk.PhysicalMemory", physicalMemory, 2 * chunkFiles); + assertCount("jdk.PhysicalMemory", physicalMemory, 2 * chunkFiles); // When jdk.ClassLoaderStatistics and jdk.ThreadThreadDump are expected to be // emitted: // Chunk 1: begin, end // Chunk 2: begin, end // Chunk 3: end // Chunk 4: end - assertCount(r1, "jdk.ThreadDump", threadDumps, 2 + 2 + (chunkFiles - 2)); - assertCount(r1, "jdk.ClassLoaderStatistics", classLoaderStatistics, 2 + 2 + (chunkFiles - 2)); + assertCount("jdk.ThreadDump", threadDumps, 2 + 2 + (chunkFiles - 2)); + assertCount("jdk.ClassLoaderStatistics", classLoaderStatistics, 2 + 2 + (chunkFiles - 2)); } } @@ -110,15 +119,13 @@ public class TestBackToBackSensitive { return Files.list(repository).filter(p -> p.toString().endsWith(".jfr")).count(); } - private static void assertCount(RecordingStream stream, String eventName, Set timestamps, long expected) throws Exception { + private static void assertCount(String eventName, Set timestamps, long expected) throws Exception { System.out.println("Timestamps for " + eventName + ":"); for (Instant timestamp : timestamps) { System.out.println(timestamp); } int count = timestamps.size(); if (count != expected) { - System.out.println("Dumping failure file."); - stream.dump(Path.of("failure.jfr")); throw new Exception("Expected " + expected + " timestamps for event " + eventName + ", but got " + count); } } diff --git a/test/jdk/jdk/jfr/event/runtime/TestClassDefineEvent.java b/test/jdk/jdk/jfr/event/runtime/TestClassDefineEvent.java index b0522741a1e..74fb8e71e87 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestClassDefineEvent.java +++ b/test/jdk/jdk/jfr/event/runtime/TestClassDefineEvent.java @@ -70,6 +70,8 @@ public final class TestClassDefineEvent { "Expected type " + cl.getClass().getName() + ", got type " + definingClassLoaderType.getName()); Asserts.assertEquals(cl.getName(), definingClassLoader.getName(), "Defining Class Loader should have the same name as the original class loader"); + Asserts.assertTrue(event.getString("source").startsWith("file:/"), "Invalid source location"); + Asserts.assertTrue(event.getString("source").endsWith(TEST_CLASS_NAME.substring(TEST_CLASS_NAME.lastIndexOf('.') + 1) + ".class"), "Invalid source location"); foundTestClasses = true; } } diff --git a/test/jdk/jdk/jfr/event/runtime/TestDeprecatedEvent.java b/test/jdk/jdk/jfr/event/runtime/TestDeprecatedEvent.java index e2ecea43a88..39add0e29fe 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestDeprecatedEvent.java +++ b/test/jdk/jdk/jfr/event/runtime/TestDeprecatedEvent.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 diff --git a/test/jdk/jdk/jfr/event/runtime/TestDirectBufferStatisticsEvent.java b/test/jdk/jdk/jfr/event/runtime/TestDirectBufferStatisticsEvent.java index b007083dde9..581884664a5 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestDirectBufferStatisticsEvent.java +++ b/test/jdk/jdk/jfr/event/runtime/TestDirectBufferStatisticsEvent.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 diff --git a/test/jdk/jdk/jfr/event/runtime/TestFinalizerStatisticsEvent.java b/test/jdk/jdk/jfr/event/runtime/TestFinalizerStatisticsEvent.java index ead77f467ac..cd100e65079 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestFinalizerStatisticsEvent.java +++ b/test/jdk/jdk/jfr/event/runtime/TestFinalizerStatisticsEvent.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 diff --git a/test/jdk/jdk/jfr/event/runtime/TestNativeLibraryLoadEvent.java b/test/jdk/jdk/jfr/event/runtime/TestNativeLibraryLoadEvent.java index e0931d7453f..50b199066e7 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestNativeLibraryLoadEvent.java +++ b/test/jdk/jdk/jfr/event/runtime/TestNativeLibraryLoadEvent.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 diff --git a/test/jdk/jdk/jfr/event/security/TestInitialSecurityPropertyEvent.java b/test/jdk/jdk/jfr/event/security/TestInitialSecurityPropertyEvent.java index bed89be84c2..84f68fa4a18 100644 --- a/test/jdk/jdk/jfr/event/security/TestInitialSecurityPropertyEvent.java +++ b/test/jdk/jdk/jfr/event/security/TestInitialSecurityPropertyEvent.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 diff --git a/test/jdk/jdk/jfr/event/security/TestSecurityProviderServiceEvent.java b/test/jdk/jdk/jfr/event/security/TestSecurityProviderServiceEvent.java index 70ed6f3d867..3acfe5bb3de 100644 --- a/test/jdk/jdk/jfr/event/security/TestSecurityProviderServiceEvent.java +++ b/test/jdk/jdk/jfr/event/security/TestSecurityProviderServiceEvent.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 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/jdk/jfr/jcmd/TestJcmdConfigureReadOnly.java b/test/jdk/jdk/jfr/jcmd/TestJcmdConfigureReadOnly.java index 9eefbd183b2..423b7726880 100644 --- a/test/jdk/jdk/jfr/jcmd/TestJcmdConfigureReadOnly.java +++ b/test/jdk/jdk/jfr/jcmd/TestJcmdConfigureReadOnly.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 diff --git a/test/jdk/jdk/jfr/jcmd/TestJcmdDumpPathToGCRootsBFSDFS.java b/test/jdk/jdk/jfr/jcmd/TestJcmdDumpPathToGCRootsBFSDFS.java new file mode 100644 index 00000000000..6815d354309 --- /dev/null +++ b/test/jdk/jdk/jfr/jcmd/TestJcmdDumpPathToGCRootsBFSDFS.java @@ -0,0 +1,195 @@ +/* + * 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.jcmd; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import jdk.jfr.Enabled; +import jdk.jfr.Recording; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedObject; +import jdk.jfr.consumer.RecordingFile; +import jdk.jfr.internal.test.WhiteBox; +import jdk.test.lib.jfr.EventNames; + +/** + * @test id=dfs-only + * @summary Test dumping with path-to-gc-roots and DFS only + * @bug 8373490 + * @requires vm.hasJFR & vm.flagless + * @modules jdk.jfr/jdk.jfr.internal.test + * @library /test/lib /test/jdk + * + * @run main/othervm -XX:TLABSize=2k -Xmx256m jdk.jfr.jcmd.TestJcmdDumpPathToGCRootsBFSDFS dfs-only + */ + +/** + * @test id=bfs-only + * @summary Test dumping with path-to-gc-roots and BFS only + * @bug 8373490 + * @requires vm.hasJFR & vm.flagless + * @modules jdk.jfr/jdk.jfr.internal.test + * @library /test/lib /test/jdk + * + * @run main/othervm -XX:TLABSize=2k -Xmx256m jdk.jfr.jcmd.TestJcmdDumpPathToGCRootsBFSDFS bfs-only + */ + +/** + * @test id=bfsdfs + * @summary Test dumping with path-to-gc-roots and mixed BFS+DFS + * @bug 8373490 + * @requires vm.hasJFR & vm.flagless + * @modules jdk.jfr/jdk.jfr.internal.test + * @library /test/lib /test/jdk + * + * @run main/othervm -XX:TLABSize=2k -Xmx256m jdk.jfr.jcmd.TestJcmdDumpPathToGCRootsBFSDFS bfsdfs + */ +public class TestJcmdDumpPathToGCRootsBFSDFS { + + // Note: + // - We start with a small heap of 256M in order to get the minimum Edge Queue size in BFS (lower cap is 32MB, enough to hold ~2mio edges) + // - We build a leak with an array containing more than 2mio entries + // That will hit BFS first, then fall back to DFS, showing the performance problem JDK-8373490 describes. + // DFS-only mode should work well, and so should BFS-only mode. + + // The minimum size of the edge queue in BFS (keep in sync with hotspot) + private final static int minimumEdgeQueueSizeCap = 32 * 1024 * 1024; + // The size of the Edge structure (keep in sync with hotspot) + private final static int edgeSizeBytes = 16; + + public static List leak; + + public static void main(String[] args) throws Exception { + WhiteBox.setWriteAllObjectSamples(true); + String settingName = EventNames.OldObjectSample + "#" + "cutoff"; + + int edgesPerMinSizedQueue = minimumEdgeQueueSizeCap / 16; + int lower = 1_000_000; + int upper = 3_000_000; + int fudge = 250_000; + if (edgesPerMinSizedQueue < (lower + fudge)) { + throw new RuntimeException("edgesPerMinSizedQueue lower bound wrong?"); + } + if (edgesPerMinSizedQueue > (upper - fudge)) { + throw new RuntimeException("edgesPerMinSizedQueue upper bound wrong?"); + } + + int leakedObjectCount; + boolean skipBFS; + switch (args[0]) { + case "bfsdfs" -> { + // Mixed mode: enough objects to saturate BFS queue + leakedObjectCount = upper; + skipBFS = false; + } + case "dfs-only" -> { + // DFS-only mode: object count does not matter, we enter DFS right away + leakedObjectCount = upper; + skipBFS = true; + } + case "bfs-only" -> { + // BFS-only mode: not enough objects to saturate BFS queue + leakedObjectCount = lower; + skipBFS = false; + } + default -> { + throw new RuntimeException("Invalid argument"); + } + }; + + WhiteBox.setSkipBFS(skipBFS); + + testDump("path-to-gc-roots=true", Collections.singletonMap(settingName, "infinity"), leakedObjectCount, true); + } + + private static void testDump(String pathToGcRoots, Map settings, int leakedObjectCount, boolean expectedChains) throws Exception { + while (true) { + try (Recording r = new Recording()) { + Map p = new HashMap<>(settings); + p.put(EventNames.OldObjectSample + "#" + Enabled.NAME, "true"); + r.setName("dodo"); + r.setSettings(p); + r.setToDisk(true); + r.start(); + clearLeak(); + System.out.println("Recording id: " + r.getId()); + System.out.println("Settings: " + settings.toString()); + System.out.println("Command: JFR.dump " + pathToGcRoots); + System.out.println("Chains expected: " + expectedChains); + buildLeak(leakedObjectCount); + System.gc(); + System.gc(); + File recording = new File("TestJcmdDumpPathToGCRoots" + r.getId() + ".jfr"); + recording.delete(); + JcmdHelper.jcmd("JFR.dump", "name=dodo", pathToGcRoots, "filename=" + recording.getAbsolutePath()); + r.setSettings(Collections.emptyMap()); + List events = RecordingFile.readAllEvents(recording.toPath()); + if (events.isEmpty()) { + System.out.println("No events found in recording. Retrying."); + continue; + } + boolean chains = hasChains(events); + if (expectedChains && !chains) { + System.out.println(events); + System.out.println("Expected chains but found none. Retrying."); + continue; + } + if (!expectedChains && chains) { + System.out.println(events); + System.out.println("Didn't expect chains but found some. Retrying."); + continue; + } + return; // Success + } + } + } + + private static void clearLeak() { + leak = null; + System.gc(); + } + + private static boolean hasChains(List events) throws IOException { + for (RecordedEvent e : events) { + RecordedObject ro = e.getValue("object"); + if (ro.getValue("referrer") != null) { + return true; + } + } + return false; + } + + private static void buildLeak(int objectCount) { + leak = new ArrayList(objectCount); + for (int i = 0; i < objectCount;i ++) { + leak.add(new Object[0]); + } + } +} diff --git a/test/jdk/jdk/jfr/jcmd/TestJcmdOptionSpecifiedOnce.java b/test/jdk/jdk/jfr/jcmd/TestJcmdOptionSpecifiedOnce.java index a9b9bcc5872..58c79fb11e3 100644 --- a/test/jdk/jdk/jfr/jcmd/TestJcmdOptionSpecifiedOnce.java +++ b/test/jdk/jdk/jfr/jcmd/TestJcmdOptionSpecifiedOnce.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 diff --git a/test/jdk/jdk/jfr/jcmd/TestJcmdStartGeneratedFilename.java b/test/jdk/jdk/jfr/jcmd/TestJcmdStartGeneratedFilename.java index bf365b9c248..938ae48c112 100644 --- a/test/jdk/jdk/jfr/jcmd/TestJcmdStartGeneratedFilename.java +++ b/test/jdk/jdk/jfr/jcmd/TestJcmdStartGeneratedFilename.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 diff --git a/test/jdk/jdk/jfr/jcmd/TestJcmdViewMissingData.java b/test/jdk/jdk/jfr/jcmd/TestJcmdViewMissingData.java index b7a22b1adcc..f9743526d91 100644 --- a/test/jdk/jdk/jfr/jcmd/TestJcmdViewMissingData.java +++ b/test/jdk/jdk/jfr/jcmd/TestJcmdViewMissingData.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 diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestClose.java b/test/jdk/jdk/jfr/jmx/streaming/TestClose.java index 08c302d6d4b..fee6111a77e 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestClose.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestClose.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 diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestDelegated.java b/test/jdk/jdk/jfr/jmx/streaming/TestDelegated.java index e20f92c3014..c3295297e39 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestDelegated.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestDelegated.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 diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestDumpOrder.java b/test/jdk/jdk/jfr/jmx/streaming/TestDumpOrder.java index 7535960366c..e6e269eb12f 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestDumpOrder.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestDumpOrder.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 diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestMetadataEvent.java b/test/jdk/jdk/jfr/jmx/streaming/TestMetadataEvent.java index 3e0e8773f0a..6d3c5fc4156 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestMetadataEvent.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestMetadataEvent.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 diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestMultipleChunks.java b/test/jdk/jdk/jfr/jmx/streaming/TestMultipleChunks.java index 942f64a5da4..41ebc660934 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestMultipleChunks.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestMultipleChunks.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 diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestNew.java b/test/jdk/jdk/jfr/jmx/streaming/TestNew.java index d2489730b03..83a07304a39 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestNew.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestNew.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 diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestRotate.java b/test/jdk/jdk/jfr/jmx/streaming/TestRotate.java index 8a7c7428a99..319fc25b442 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestRotate.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestRotate.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 diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestSetSettings.java b/test/jdk/jdk/jfr/jmx/streaming/TestSetSettings.java index 2d1cb50dcfc..626387896af 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestSetSettings.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestSetSettings.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 diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestStart.java b/test/jdk/jdk/jfr/jmx/streaming/TestStart.java index 6d4bfc10f81..bfb45a6eeae 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestStart.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestStart.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 diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestStop.java b/test/jdk/jdk/jfr/jmx/streaming/TestStop.java index 572577786a1..bff95758a63 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestStop.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestStop.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 diff --git a/test/jdk/jdk/jfr/jvm/TestChunkIntegrity.java b/test/jdk/jdk/jfr/jvm/TestChunkIntegrity.java index dc66d2617af..452f2e24aaf 100644 --- a/test/jdk/jdk/jfr/jvm/TestChunkIntegrity.java +++ b/test/jdk/jdk/jfr/jvm/TestChunkIntegrity.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 diff --git a/test/jdk/jdk/jfr/jvm/TestFatEvent.java b/test/jdk/jdk/jfr/jvm/TestFatEvent.java index 3e10074cce9..c0b73832640 100644 --- a/test/jdk/jdk/jfr/jvm/TestFatEvent.java +++ b/test/jdk/jdk/jfr/jvm/TestFatEvent.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 diff --git a/test/jdk/jdk/jfr/jvm/TestHiddenWait.java b/test/jdk/jdk/jfr/jvm/TestHiddenWait.java index aaefc60527c..1ccc9a9b035 100644 --- a/test/jdk/jdk/jfr/jvm/TestHiddenWait.java +++ b/test/jdk/jdk/jfr/jvm/TestHiddenWait.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 diff --git a/test/jdk/jdk/jfr/jvm/TestLongStringsInPool.java b/test/jdk/jdk/jfr/jvm/TestLongStringsInPool.java index 45b66d508cd..5399668b0e7 100644 --- a/test/jdk/jdk/jfr/jvm/TestLongStringsInPool.java +++ b/test/jdk/jdk/jfr/jvm/TestLongStringsInPool.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 diff --git a/test/jdk/jdk/jfr/jvm/TestVerifyInstrumentation.java b/test/jdk/jdk/jfr/jvm/TestVerifyInstrumentation.java index ec9e64972ec..c2090f43c93 100644 --- a/test/jdk/jdk/jfr/jvm/TestVerifyInstrumentation.java +++ b/test/jdk/jdk/jfr/jvm/TestVerifyInstrumentation.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 diff --git a/test/jdk/jdk/jfr/startupargs/TestPreserveRepository.java b/test/jdk/jdk/jfr/startupargs/TestPreserveRepository.java index 74023639f47..e9c4350408c 100644 --- a/test/jdk/jdk/jfr/startupargs/TestPreserveRepository.java +++ b/test/jdk/jdk/jfr/startupargs/TestPreserveRepository.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 diff --git a/test/jdk/jdk/jfr/startupargs/TestStartHelp.java b/test/jdk/jdk/jfr/startupargs/TestStartHelp.java index 0b3b5869cad..53b18d7ee58 100644 --- a/test/jdk/jdk/jfr/startupargs/TestStartHelp.java +++ b/test/jdk/jdk/jfr/startupargs/TestStartHelp.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 diff --git a/test/jdk/jdk/jfr/startupargs/TestStartupOptionSpecifiedOnce.java b/test/jdk/jdk/jfr/startupargs/TestStartupOptionSpecifiedOnce.java index 11749504eba..7049ad92cae 100644 --- a/test/jdk/jdk/jfr/startupargs/TestStartupOptionSpecifiedOnce.java +++ b/test/jdk/jdk/jfr/startupargs/TestStartupOptionSpecifiedOnce.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 diff --git a/test/jdk/jdk/jfr/threading/TestStringPoolVirtualThreadPinning.java b/test/jdk/jdk/jfr/threading/TestStringPoolVirtualThreadPinning.java index ef2a3698edc..589a77d3e4e 100644 --- a/test/jdk/jdk/jfr/threading/TestStringPoolVirtualThreadPinning.java +++ b/test/jdk/jdk/jfr/threading/TestStringPoolVirtualThreadPinning.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 diff --git a/test/jdk/jdk/jfr/tool/TestConfigure.java b/test/jdk/jdk/jfr/tool/TestConfigure.java index e200054319e..404c657fd98 100644 --- a/test/jdk/jdk/jfr/tool/TestConfigure.java +++ b/test/jdk/jdk/jfr/tool/TestConfigure.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 diff --git a/test/jdk/jdk/jfr/tool/TestView.java b/test/jdk/jdk/jfr/tool/TestView.java index 38174859b51..56a1e3edc3b 100644 --- a/test/jdk/jdk/jfr/tool/TestView.java +++ b/test/jdk/jdk/jfr/tool/TestView.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 diff --git a/test/jdk/jdk/modules/etc/DefaultModules.java b/test/jdk/jdk/modules/etc/DefaultModules.java index febb5baf70f..2c4823e71a0 100644 --- a/test/jdk/jdk/modules/etc/DefaultModules.java +++ b/test/jdk/jdk/modules/etc/DefaultModules.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 diff --git a/test/jdk/jdk/modules/etc/JmodExcludedFiles.java b/test/jdk/jdk/modules/etc/JmodExcludedFiles.java index 90ca6840d52..3929419a080 100644 --- a/test/jdk/jdk/modules/etc/JmodExcludedFiles.java +++ b/test/jdk/jdk/modules/etc/JmodExcludedFiles.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 @@ -25,9 +25,12 @@ * @test * @bug 8159927 * @modules java.base/jdk.internal.util + * @library /test/lib * @requires jlink.packagedModules - * @run main JmodExcludedFiles - * @summary Test that JDK JMOD files do not include native debug symbols + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI JmodExcludedFiles + * @summary Test that JDK JMOD files do not include native debug symbols when it is not configured */ import java.nio.file.DirectoryStream; @@ -37,9 +40,11 @@ import java.nio.file.Paths; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import jdk.internal.util.OperatingSystem; +import jdk.test.whitebox.WhiteBox; public class JmodExcludedFiles { private static String javaHome = System.getProperty("java.home"); + private static final boolean expectSymbols = WhiteBox.getWhiteBox().shipsDebugInfo(); public static void main(String[] args) throws Exception { Path jmods = Path.of(javaHome, "jmods"); @@ -76,24 +81,19 @@ public class JmodExcludedFiles { if (i != -1) { if (n.substring(0, i).endsWith(".dSYM")) { System.err.println("Found symbols in " + jmod + ": " + name); - return true; + return expectSymbols ? false: true; } } } if (OperatingSystem.isWindows() && name.endsWith(".pdb")) { - // on Windows we check if we should have public symbols through --with-external-symbols-in-bundles=public (JDK-8237192) - String strippedpdb = javaHome + "/bin/" + name.substring(index + 1, name.length() - 4) + ".stripped.pdb"; - if (!Files.exists(Paths.get(strippedpdb))) { - System.err.println("Found symbols in " + jmod + ": " + name + - ". No stripped pdb file " + strippedpdb + " exists."); - return true; - } + System.err.println("Found symbols in " + jmod + ": " + name); + return expectSymbols ? false: true; } if (name.endsWith(".diz") || name.endsWith(".debuginfo") || name.endsWith(".map")) { System.err.println("Found symbols in " + jmod + ": " + name); - return true; + return expectSymbols ? false: true; } } return false; diff --git a/test/jdk/jni/nullCaller/NullCallerTest.java b/test/jdk/jni/nullCaller/NullCallerTest.java index 1ba6d6f0add..bd773172eeb 100644 --- a/test/jdk/jni/nullCaller/NullCallerTest.java +++ b/test/jdk/jni/nullCaller/NullCallerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2024, 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 diff --git a/test/jdk/performance/client/SwingMark/src/AbstractSwingTest.java b/test/jdk/performance/client/SwingMark/src/AbstractSwingTest.java index 8a62d196857..8dd2e0b4caa 100644 --- a/test/jdk/performance/client/SwingMark/src/AbstractSwingTest.java +++ b/test/jdk/performance/client/SwingMark/src/AbstractSwingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions diff --git a/test/jdk/performance/client/SwingMark/src/JMTest_01.java b/test/jdk/performance/client/SwingMark/src/JMTest_01.java index fcc5fe309ba..c4af54b16ef 100644 --- a/test/jdk/performance/client/SwingMark/src/JMTest_01.java +++ b/test/jdk/performance/client/SwingMark/src/JMTest_01.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions diff --git a/test/jdk/performance/client/SwingMark/src/JMTest_02.java b/test/jdk/performance/client/SwingMark/src/JMTest_02.java index 680ada9f1df..ca712ce25df 100644 --- a/test/jdk/performance/client/SwingMark/src/JMTest_02.java +++ b/test/jdk/performance/client/SwingMark/src/JMTest_02.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions diff --git a/test/jdk/performance/client/SwingMark/src/JMTest_03.java b/test/jdk/performance/client/SwingMark/src/JMTest_03.java index 38f5dff43bc..a2868798798 100644 --- a/test/jdk/performance/client/SwingMark/src/JMTest_03.java +++ b/test/jdk/performance/client/SwingMark/src/JMTest_03.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions diff --git a/test/jdk/performance/client/SwingMark/src/JMTest_04.java b/test/jdk/performance/client/SwingMark/src/JMTest_04.java index cbb32e5b916..53b0294a9bd 100644 --- a/test/jdk/performance/client/SwingMark/src/JMTest_04.java +++ b/test/jdk/performance/client/SwingMark/src/JMTest_04.java @@ -1,6 +1,6 @@ import java.util.Date; /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions diff --git a/test/jdk/performance/client/SwingMark/src/JMTest_05.java b/test/jdk/performance/client/SwingMark/src/JMTest_05.java index dc2a0bd1489..4c90eb23316 100644 --- a/test/jdk/performance/client/SwingMark/src/JMTest_05.java +++ b/test/jdk/performance/client/SwingMark/src/JMTest_05.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions diff --git a/test/jdk/performance/client/SwingMark/src/MenuTest.java b/test/jdk/performance/client/SwingMark/src/MenuTest.java index 91ce63e7667..9c336814980 100644 --- a/test/jdk/performance/client/SwingMark/src/MenuTest.java +++ b/test/jdk/performance/client/SwingMark/src/MenuTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions diff --git a/test/jdk/performance/client/SwingMark/src/TypingTest.java b/test/jdk/performance/client/SwingMark/src/TypingTest.java index 440b8b09e87..7a29926f7bb 100644 --- a/test/jdk/performance/client/SwingMark/src/TypingTest.java +++ b/test/jdk/performance/client/SwingMark/src/TypingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions diff --git a/test/jdk/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/ButtonDemo.html b/test/jdk/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/ButtonDemo.html index 6e6ff5a21a2..df6e417a669 100644 --- a/test/jdk/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/ButtonDemo.html +++ b/test/jdk/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/ButtonDemo.html @@ -1,6 +1,6 @@