#! /bin/bash
# Last edited on 2021-02-19 15:23:56 by jstolfi

# Usage: "run_test.sh {MODULE}..."
# Runs "tests/{MODULE}_TST.py" with the proper {PYTHONPATH},
# and sends the standard output (if not empty)
# to tests/out/{MODULE}_TST.txt

modules=( "$@" ); shift  # 
opref="tests/out/${modulo}"
ofile="${opref}.html"

if [[ $PWD =~ .*/tests ]]; then cd .. ; fi
mkdir -p tests/out
# ( cd tests && if [[ ! ( -r images ) ]]; then ln -s ../images; fi )
# ( cd tests && if [[ ! ( -r Makefile ) ]]; then ln -s ../Makefile; fi )
( cd tests && if [[ ! ( -r run_test.sh ) ]]; then ln -s ../run_test.sh; fi )
( cd tests && if [[ ! ( -r tests ) ]]; then ln -s ./ tests; fi )
outexts=( ext in txt eps dat gcode gcd png pgm ppm )

for module in "${modules[@]}" ; do 
  echo "=== testing module ${module} =============================" 1>&2
  # Check for functions that are not being tested:
  egrep -e '^def ' ${module}.py \
    | sed \
        -e 's/^def *//g' \
        -e 's/[ ]*[(].*$//g' \
    | sort \
    > .funcs
  find_uses.sh tests/${module}_TST.py ${module} > .uses
  bool 1-2 .funcs .uses > .missing
  if [[ -s .missing ]]; then
    echo "!! these functions are not being tested:" 1>&2
    cat .missing | sed -e 's:^:  :g' 1>&2 
  fi
  
  opref="tests/out/${module}_TST"
  rm -f ${opref}*
  
  # Run the test program, save output:
  tfile="${opref}.txt" # Text output.
  export PYTHONPATH=".:tests:.." ; \
    time python3 tests/${module}_TST.py > ${tfile}
  
  # Remove empty output files:
  for ext in ${outexts[@]} ; do
    for ff in ${opref}*.${ext}; do
      if [[ ( -e ${ff} ) && ( ! ( -s ${ff} ) ) ]]; then 
        if [[ "${ff}" != "tests/out/${module}_TST.txt" ]]; then
          echo "!! ${ff} is empty" 1>&2
        fi
        rm -f ${ff}
      fi
    done
  done

  # Show EPS outputs, if any:
  for efile in ${opref}*.eps; do
    if [[ -s ${efile} ]]; then 
      evince ${efile}
    fi
  done

  # Plot graphs, if any:
  for dfile in ${opref}*.dat; do
    pfile="${dfile/.dat/.png}" # Output plot file
    if [[ -s ${dfile} ]]; then 
      plot_data.sh ${dfile} > ${pfile}
    fi
  done
  
  echo "=== done testing ${module} ==========================="
done
