# This is a basic workflow to help you get started with Actions

name: Tests

# Controls when the action will run.
on: [pull_request, workflow_dispatch]

jobs:
  # Label of the container job
  integration-tests:
    # Containers must run in Linux based operating systems
    runs-on: ubuntu-latest
    strategy:
      matrix:
        group: [1, 2, 3, 4]

    # Service containers to run with `container-job`
    services:
      # Label used to access the service container
      postgres:
        # Docker Hub image
        image: mdillon/postgis
        # Provide the password for postgres
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: eventcally_tests
        # Set health checks to wait until postgres has started
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          # Maps tcp port 5432 on service container to the host
          - 5432:5432

      redis:
          # Docker Hub image
          image: redis
          # Set health checks to wait until redis has started
          options: >-
            --health-cmd "redis-cli ping"
            --health-interval 10s
            --health-timeout 5s
            --health-retries 5
          ports:
            # Maps port 6379 on service container to the host
            - 6379:6379

    steps:
      - name: Check out repository code
        uses: actions/checkout@v2

      - name: Set up Python 3.8
        uses: actions/setup-python@v2
        with:
          python-version: '3.8'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt

      - name: Run tests
        run: pytest --cov=project --splits 4 --group ${{ matrix.group }}
        env:
          TEST_DATABASE_URL: postgresql://postgres:postgres@localhost/eventcally_tests
          TEST_REDIS_URL: redis://localhost:6379

      - name: Upload coverage
        uses: actions/upload-artifact@v2
        with:
          name: coverage${{ matrix.group }}
          path: .coverage


  coverage:
    needs: integration-tests
    if: ${{ success() }}
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository code
        uses: actions/checkout@v2

      - name: Set up Python 3.8
        uses: actions/setup-python@v2
        with:
          python-version: '3.8'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt

      - name: Download all artifacts
        # Downloads coverage1, coverage2, etc.
        uses: actions/download-artifact@v2

      - name: Combine coverage files
        run: coverage combine coverage*/.coverage*

      - name: Codecov
        uses: codecov/codecov-action@v3
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
          verbose: true
          fail_ci_if_error: true
