name: Test

on: [push, pull_request, workflow_dispatch]

env:
  FORCE_COLOR: 1

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        python-version: ["pypy-3.10", "3.8", "3.9", "3.10", "3.11", "3.12"]
        os: [ubuntu-latest]
        include:
          - { python-version: "pypy-3.10", os: windows-latest }
          - { python-version: "pypy-3.10", os: macos-latest }
          - { python-version: "3.10", os: windows-latest }
          - { python-version: "3.10", os: macos-latest }
          - { python-version: "3.11", os: windows-latest }
          - { python-version: "3.11", os: macos-latest }

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
          allow-prereleases: true
          cache: pip
          cache-dependency-path: "setup.py"

      - name: Install dependencies
        run: |
          python -m pip install -U pip
          python -m pip install -U pytest
          python -m pip install .
        env:
          CFLAGS: '-DDEBUG'

      - name: Tests
        run: |
          python -m pytest --capture=no

      - name: Test without debug mode
        run: |
          git clean -Xfd
          python -m pip install --force-reinstall .
          python -m pytest

      - name: Test with coverage
        if: ${{ startsWith(matrix.os, 'ubuntu') && matrix.python-version == '3.10' }}
        env:
          CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
        run: |
          pip install -e .
          pip install coverage
          CFLAGS="--coverage -O0" python setup.py -q build_ext --inplace -f
          coverage run -m pytest
          ./scripts/coverage.sh
          bash <(curl -s https://codecov.io/bash) -X gcov

  cross-arch:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        architecture: [ppc64le, s390x, aarch64, arm/v6, 386]
    steps:
      - uses: actions/checkout@v4
      - run: git fetch --prune --unshallow

      # https://github.com/docker/setup-qemu-action
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Test
        run: |
          docker run -v "$PWD:/io" --platform=linux/${{ matrix.architecture }} python:alpine ash -e -c '
            apk add gcc g++ musl-dev git
            cd /io
            git config --global --add safe.directory /io
            pip install . pytest
            FORCE_COLOR=1 pytest
          '

  success:
    needs: [test, cross-arch]
    runs-on: ubuntu-latest
    name: test successful
    steps:
      - name: Success
        run: echo Test successful
