# Run python unit tests

# Tests real build by default.
# Access the complex build by setting env variable USE_DOLFINX_COMPLEX

if [ "x${USE_DOLFINX_COMPLEX}" != "x" ]; then
    TESTDIR_SUFFIX="-complex"
    TEST_DESCRIPTION="for complex build "
    export PETSC_DIR=/usr/lib/petscdir/petsc-complex
    # process ufl forms for complex test: second argument 1 indicates complex
    UFL_TYPE=1
else
    TESTDIR_SUFFIX="-real"
    export PETSC_DIR=/usr/lib/petsc
fi
export SLEPC_DIR=`grep wPETSC_DIR ${PETSC_DIR}/lib/petsc/conf/petscvariables | awk '{print $3}' | sed "s/petsc/slepc/g"`

# MPI tests are set up to run on no more than 3 processes
NPROC=$( nproc )
if [[ $NPROC > 2 ]]; then
  N_MPI=3
else
  N_MPI=2
fi
# and only 2 processes for unit tests
N_MPI_UNITTEST=2

export OMPI_MCA_plm_rsh_agent=/bin/false
export OMPI_MCA_rmaps_base_oversubscribe=1
export OMPI_MCA_btl_base_warn_component_unused=0

echo "== running python tests ${TEST_DESCRIPTION}=="

mkdir -p ${AUTOPKGTEST_TMP}/python/dist-packages
cp -ra python/dolfinx_utils ${AUTOPKGTEST_TMP}/python/dist-packages
export PYTHONPATH=${PYTHONPATH}:${AUTOPKGTEST_TMP}/python/dist-packages

# help CI tests run a little faster
export DOLFINX_JIT_CFLAGS="-g0 -O0"

# numba is not available on all arches
if ! dpkg -l python3-numba >/dev/null 2>&1; then
    NUMBA_TESTS="custom_jit_kernels custom_assembler expression_evaluation"
    EXCLUDE_NUMBA=
    for nt in NUMBA_TESTS; do
	EXCLUDE_NUMBA="$EXCLUDE_NUMBA --ignore-glob=*${nt}*"
    done
fi

TESTS_SKIPPED="test_RT_N1curl_simplex"
MULTIPLE_TESTS_SKIPPED="test_assembly_solve_taylor_hood test_cube_distance test_read_write_p2_mesh gmsh"

# some tests fail on 32-bit arches. cf. Bug#995599
DEB_HOST_ARCH_BITS=$(dpkg-architecture -qDEB_HOST_ARCH_BITS)
if [ "x${DEB_HOST_ARCH_BITS}" = "x32" ]; then
  TESTS_SKIPPED_32BIT="test_cffi_assembly test_compute_closest_entity_2d"
fi

for test in $MULTIPLE_TESTS_SKIPPED $TESTS_SKIPPED_32BIT; do
  TESTS_SKIPPED="$TESTS_SKIPPED or $test"
done
TEST_KEYWORD="not (${TESTS_SKIPPED})"

echo "=== python unit test (serial) ${TEST_DESCRIPTION}==="
python3 -m pytest --durations=20 $EXCLUDE_NUMBA -k "${TEST_KEYWORD}" python/test/unit/

if [ "x${DEB_HOST_ARCH_BITS}" = "x32" ]; then
   echo "=== python unit tests (MPI) skipped on 32-bit systems (see Bug#995599) ${TEST_DESCRIPTION}==="
else
  echo "=== python unit test (MPI using ${N_MPI_UNITTEST} processors out of $NPROC) ${TEST_DESCRIPTION}==="
  mpirun -n ${N_MPI_UNITTEST} python3 -m pytest --durations=20 $EXCLUDE_NUMBA -k "${TEST_KEYWORD}" python/test/unit/ --color=no
fi
