name: Run Pytest

on:
  pull_request:
    branches:
      - main
    paths:
      - api/**
      - docker/**
      - .github/workflows/api-tests.yml

concurrency:
  group: api-tests-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

jobs:
  test:
    name: API Tests
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version:
          - "3.11"
          - "3.12"

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false

      - name: Setup Poetry and Python ${{ matrix.python-version }}
        uses: ./.github/actions/setup-poetry
        with:
          python-version: ${{ matrix.python-version }}
          poetry-lockfile: api/poetry.lock

      - name: Check Poetry lockfile
        run: |
          poetry check -C api --lock
          poetry show -C api

      - name: Install dependencies
        run: poetry install -C api --with dev

      - name: Check dependencies in pyproject.toml
        run: poetry run -P api bash dev/pytest/pytest_artifacts.sh

      - name: Run Unit tests
        run: poetry run -P api bash dev/pytest/pytest_unit_tests.sh

      - name: Run dify config tests
        run: poetry run -P api python dev/pytest/pytest_config_tests.py

      - name: Run mypy
        run: |
          poetry run -C api python -m mypy --install-types --non-interactive .

      - name: Set up dotenvs
        run: |
          cp docker/.env.example docker/.env
          cp docker/middleware.env.example docker/middleware.env

      - name: Expose Service Ports
        run: sh .github/workflows/expose_service_ports.sh

      - name: Set up Sandbox
        uses: hoverkraft-tech/compose-action@v2.0.2
        with:
          compose-file: |
            docker/docker-compose.middleware.yaml
          services: |
            sandbox
            ssrf_proxy

      - name: Run Workflow
        run: poetry run -P api bash dev/pytest/pytest_workflow.sh
