#!/bin/bash

[ ! -d .venv ] && ./build.sh venv

.venv/bin/pip install -q \
    py pytest pytest-greendots \
    pytest-xdist pytest-pep8 pytest-flakes pytest-capturelog pytest-cov \
    pytest-instafail pyjack

export PYTHONPATH=$(pwd)/snapshot/lib:$PYTHONPATH
cpu_count=$($PYTHON -c 'import multiprocessing; print(multiprocessing.cpu_count())')

pytest_args=(
    --instafail
)

cp tools/pytest.ini .

path_spec=0

while test -n "$1"; do
    case "$1" in
        --nocov)
            NOCOV=1
            shift
            ;;

        --nobox*)
            NOBOXED=1
            shift
            ;;

        style|bigbang|code)
            TESTTYPE=$1
            shift
            ;;

        benchmark)
            TESTTYPE=$1
            NOCOV=1
            shift
            ;;

        *)
            if [ -d "$1" ] || [ -f "$1" ]; then
                path_spec=1
            fi

            pytest_args=( "${pytest_args[@]}" "$1" )
            shift
            ;;
    esac
done

if [ -z "$NOCOV" ]; then
    base_path=snapshot/lib/heartbeat
    for path in $(ls $base_path); do
        pytest_args=( "${pytest_args[@]}" --cov=$base_path/$path )
    done

    pytest_args=(
        "${pytest_args[@]}"
        --cov-report=html
        --cov-config=tools/coverage.conf
        --no-cov-on-fail
    )
fi

if [ -z "$NOBOXED" ]; then
    boxed_arg="--boxed"
fi

case "$TESTTYPE" in
    style)
        pytest_args=( -m 'pep8 or flakes' "${pytest_args[@]}" )
        shift 1
        ;;
    bigbang)
        pytest_args=( -m 'not pep8 and not flakes' -n $cpu_count $boxed_arg -k 'bigbang and not benchmark' "${pytest_args[@]}" )
        shift 1
        ;;
    code)
        pytest_args=( -m 'not pep8 and not flakes' -n $cpu_count $boxed_arg -k 'not (bigbang or benchmark)' "${pytest_args[@]}" )
        shift 1
        ;;
    benchmark)
        pytest_args=( -m 'not pep8 and not flakes' -n 0 -s -k 'benchmark' "${pytest_args[@]}" )
        shift 1
        ;;
    *)
        pytest_args=( -m 'not pep8 and not flakes' -n $cpu_count $boxed_arg -k 'not benchmark' "${pytest_args[@]}" )
        ;;
esac

if [ $path_spec -eq 0 ]; then
    if [ "$TESTTYPE" = style ]; then
        pytest_args=( "${pytest_args[@]}" src tests )
    else
        pytest_args=( "${pytest_args[@]}" tests )
    fi
fi

.venv/bin/py.test "${pytest_args[@]}"
rm pytest.ini
