name: Code Coverage

on: [push, pull_request]

jobs:
  code-coverage:
    runs-on: ubuntu-latest
    steps:
      - name: Check out source repository
        uses: actions/checkout@v5
      - name: Set up Python ${{ matrix.python-version }} environment
        uses: actions/setup-python@v6
        with:
          python-version: "3.13"
      - name: Cache pip dependencies
        uses: actions/cache@v4
        with:
          path: ~/.cache/pip
          key: ${{ runner.os }}-pip-3.13-${{ hashFiles('**/requirements*.txt', '**/setup.py', '**/pyproject.toml') }}
          restore-keys: |
            ${{ runner.os }}-pip-3.13-
            ${{ runner.os }}-pip-
      - name: Run local websockets echo server on port ${{ env.LOCAL_WS_SERVER_PORT }}
        run: |
          pip3 install -U websockets asyncio
          python3 websocket/tests/echo-server.py &
      - name: Run test cases without internet or optional dependencies to verify no offline test failures and verify optional dependencies are optional
        run: |
          pip3 install coverage pytest pytest-cov setuptools
          python3 -c "import setuptools; print('Setup tools version'); print(setuptools.__version__)"
          pip3 install -e .
          pytest -v -r f --cov=websocket websocket/tests --cov-config=.coveragerc
          coverage report
      - name: Install wsaccel and python-socks, then run all test cases for coverage collection
        run: |
          pip3 install wsaccel python-socks
          pytest -v -r f --cov=websocket websocket/tests --cov-config=.coveragerc --cov-append
          coverage report
        env:
          TEST_WITH_INTERNET: 1
          LOCAL_WS_SERVER_PORT: 8765
      - name: Run SSL-specific tests with cert path and cert file, then generate final report
        run: |
          for ca_bundle in "/usr/lib/ssl/certs" "/etc/ssl/certs/ca-certificates.crt"; do
            WEBSOCKET_CLIENT_CA_BUNDLE="$ca_bundle" pytest -v -r f --cov=websocket websocket/tests --cov-config=.coveragerc --cov-append -k "sslopt"
          done
          # Generate final coverage report and XML for Codecov.io
          coverage report
          coverage xml
      - name: Submit code coverage report to Codecov.io
        uses: codecov/codecov-action@v5
        with:
          files: ./coverage.xml
          fail_ci_if_error: true
