name: Flask CI

on:
  push:
    branches: [master, testing]
  pull_request:
    branches: [master, testing]

jobs:
  build:
    runs-on: ubuntu-latest

    # Service containers to run with `container-job`
    services:
      # Label used to access the service container
      postgres:
        # Docker Hub image
        image: postgres:11
        ports:
          - 5432:5432
        # Set health checks to wait until postgres has started
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        env:
          POSTGRES_DB: dh_test
          POSTGRES_USER: dhub
          POSTGRES_PASSWORD: ereuse

    strategy:
      max-parallel: 4
      matrix:
        python-version: [3.7]

    steps:
    - uses: actions/checkout@v2
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v2
      with:
        python-version: ${{ matrix.python-version }}
        cache: 'pip'

    - name: Install dependencies
      run: |
        sudo apt-get update -qy
        sudo apt-get -y install postgresql-client --no-install-recommends
        python -m pip install --upgrade pip
        pip install flake8 pytest coverage
        pip install -r requirements.txt

    - name: Prepare database
      env:
        POSTGRES_DB: dh_test
        POSTGRES_USER: dhub
        POSTGRES_PASSWORD: ereuse
      run: |
        export PGPASSWORD=$POSTGRES_PASSWORD
        psql -h "localhost" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "CREATE EXTENSION pgcrypto SCHEMA public;"
        psql -h "localhost" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "CREATE EXTENSION ltree SCHEMA public;"
        psql -h "localhost" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "CREATE EXTENSION citext SCHEMA public;"
        psql -h "localhost" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "CREATE EXTENSION pg_trgm SCHEMA public;"

    - name: Lint with flake8
      run: |
        # stop the build if:
        # - E9,F63,F7,F82: Python syntax errors or undefined names
        # - E501: line longer than 120 characters
        # - C901: complexity greater than 10
        # - F401: modules imported but unused
        # See: https://flake8.pycqa.org/en/latest/user/error-codes.html
        flake8 . --select=E9,F63,F7,F82,E501,C901,F401
        flake8 . --exit-zero

    - name: Run Tests
      run: |
        export SECRET_KEY=`python3 -c 'import secrets; print(secrets.token_hex())'`
        coverage run --source='ereuse_devicehub' -m pytest -m mvp --maxfail=5 tests/
        coverage report --include='ereuse_devicehub/*'
        coverage xml

    - name: Upload coverage to Codecov
      uses: codecov/codecov-action@v1
      with:
        token: ${{ secrets.CODECOV_TOKEN }}
