name: Reusable - Test

on:
  workflow_call:
    inputs:
      cache-read-only:
        type: boolean
        required: false
      no-build-cache:
        type: boolean
        required: false
    secrets:
      GRADLE_ENTERPRISE_ACCESS_KEY:
        required: false
      GE_CACHE_USERNAME:
        required: false
      GE_CACHE_PASSWORD:
        required: false

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        test-java-version:
          - 8
          - 11
          - 17
        vm:
          - hotspot
          - openj9
      fail-fast: false
    steps:
      - uses: actions/checkout@v3

      - id: setup-test-java
        name: Set up JDK ${{ matrix.test-java-version }}-${{ matrix.vm }} for running tests
        uses: actions/setup-java@v3
        with:
          distribution: ${{ matrix.vm == 'hotspot' && 'temurin' || 'adopt-openj9'}}
          java-version: ${{ matrix.test-java-version }}

      - name: Set up JDK for running Gradle
        uses: actions/setup-java@v3
        with:
          distribution: temurin
          java-version: 17

      # vaadin tests use pnpm
      - name: Cache pnpm modules
        uses: actions/cache@v3
        with:
          path: ~/.pnpm-store
          key: ${{ runner.os }}-test-cache-pnpm-modules

      - name: Start deadlock detector
        run: .github/scripts/deadlock-detector.sh

      - name: Test
        env:
          GRADLE_ENTERPRISE_ACCESS_KEY: ${{ secrets.GRADLE_ENTERPRISE_ACCESS_KEY }}
          GE_CACHE_USERNAME: ${{ secrets.GE_CACHE_USERNAME }}
          GE_CACHE_PASSWORD: ${{ secrets.GE_CACHE_PASSWORD }}
        uses: gradle/gradle-build-action@v2
        with:
          arguments: check -PtestJavaVersion=${{ matrix.test-java-version }} -PtestJavaVM=${{ matrix.vm }} -Porg.gradle.java.installations.paths=${{ steps.setup-test-java.outputs.path }} -Porg.gradle.java.installations.auto-download=false ${{ inputs.no-build-cache && ' --no-build-cache' || '' }}
          # only push cache for one matrix option since github action cache space is limited
          cache-read-only: ${{ inputs.cache-read-only || matrix.test-java-version != 11 || matrix.vm != 'hotspot' }}
          # gradle enterprise is used for the build cache
          gradle-home-cache-excludes: caches/build-cache-1

      - name: Upload deadlock detector artifacts if any
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: deadlock-detector-test-${{ matrix.test-java-version }}-${{ matrix.vm }}
          path: /tmp/deadlock-detector-*
          if-no-files-found: ignore

      - name: Upload jvm crash dump files if any
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: javacore-test-${{ matrix.test-java-version }}
          path: |
            **/hs_err_pid*.log
            **/javacore.*.txt
            **/Snap.*.trc
            **/core.*.dmp
            **/jitdump.*.dmp
          if-no-files-found: ignore
