#!/bin/sh
# Run the unit test suite against the installed package.
#
# Everything that has to be written -- the generated test classmap and phpunit's
# configuration -- is created in $AUTOPKGTEST_TMP, so the test needs no root and
# leaves the unpacked source tree untouched. The application code and its autoload
# file are read from /usr/share/phpmyadmin, which is what makes this a test of the
# installed package rather than of the checkout.
set -eu

# SC1091: the library path is computed at run time, so it cannot be followed
# statically. Its contents are checked on their own.
# shellcheck disable=SC1091
. "$(dirname "$0")/lib/helpers.sh"

dep8_require php phpab phpunit

SRC=$(pwd)
WORK="$AUTOPKGTEST_TMP/phpunit"
if [ -e "$WORK" ]; then
    rm -r "$WORK"
fi
mkdir -p "$WORK"

# The test classes, their fixtures and phpunit's configuration are copied so that
# the classmap can be generated inside the copy: phpab writes paths relative to
# the file it generates, so generating outside the tree would produce entries
# that do not resolve.
# examples/ is copied too: AuthenticationSignonTest points the signon script at
# the relative path ./examples/signon-script.php, so it has to resolve from the
# directory phpunit runs in.
echo "Copying the test suite to $WORK ..."
dep8_run "$WORK/copy.log" cp -a test examples phpunit.xml.dist "$WORK/"

# The classmap template is read from the source tree; it requires the installed
# autoload file, so the tests load the package under test.
echo "Generating the test classmap ..."
dep8_run "$WORK/phpab.log" phpab \
    --template "$SRC/debian/autoload-test-autopkgtest.php.tpl" \
    --output "$WORK/test/autoload.php" \
    "$WORK/test"

cat > "$WORK/bootstrap.php" <<PHP
<?php
// Written by the phpMyAdmin autopkgtest: points the test bootstrap at the copy.
if (! defined('ROOT_PATH')) {
    define('ROOT_PATH', '/usr/share/phpmyadmin/');
}
if (! defined('TEST_PATH')) {
    define('TEST_PATH', '$WORK/');
}
require_once TEST_PATH . 'test/autoload.php';
require_once TEST_PATH . 'test/bootstrap-dist.php';
PHP

# keep in sync with debian/rules::override_dh_auto_test
# The argument list is built with "set --" rather than an unquoted variable, so
# the 32-bit exclusions are added as separate arguments only when they apply.
set -- \
  --do-not-record-test-run-history \
  --fail-on-empty-test-suite \
  --no-coverage \
  --exclude-group selenium \
  --exclude-group network \
  --exclude-group git-revision \
  --exclude-group ext-xdebug \
  --exclude-group with-trigger-error \
  --exclude-group extension-iconv

if [ "$(php -n -r "echo (PHP_INT_SIZE === 4 || php_uname('m') === 's390x') ? 'yes' : 'no';")" = "yes" ]; then
  set -- "$@" --exclude-group 32bit-incompatible
fi

echo "Running the unit tests ..."
cd "$WORK"
LC_ALL=C.UTF-8 phpunit -c phpunit.xml.dist --bootstrap bootstrap.php "$@"

dep8_pass "the unit test suite passed"
