#!/usr/bin/env bash
## Description: Run the entity_gateway test suite with Xdebug disabled
## Usage: test [--unit|--kernel|--functional] [--serial] [phpunit args]
## Example: "ddev test", "ddev test --unit", "ddev test --kernel --serial", "ddev test --group entity_gateway_field_output", "ddev test --filter testMemoDoesNotReuseAcrossDifferentDepths"
## ExecRaw: true
## MutagenSync: true
#
# Xdebug is disabled unconditionally. The container tries to open a step-debug
# connection to host.docker.internal:9003 even with `xdebug_enabled: false`,
# and a refused connection fails tests outright: directly on larger batches,
# and as a `StatementWrapperIterator ... $clientConnection` fatal in Functional
# teardown. Neither is a module bug and neither is worth rediscovering.

set -euo pipefail

# Override if the module lives elsewhere in your site (e.g. modules/contrib).
MODULE="${EG_MODULE_PATH:-web/modules/custom/entity_gateway}"

cd /var/www/html

export XDEBUG_MODE=off
# phpunit.xml's HtmlOutputLogger resolves outputDirectory against the CWD,
# which is the site root rather than web/. Empty disables the writer instead
# of warning on every run.
export BROWSERTEST_OUTPUT_DIRECTORY=''

suite="all"
serial=0
args=()

while [[ $# -gt 0 ]]; do
  case "$1" in
    --unit|--kernel|--functional) suite="${1#--}" ;;
    --serial) serial=1 ;;
    *) args+=("$1") ;;
  esac
  shift
done

# paratest takes a single path, so suites are selected by filtering the module
# root on the test namespace. That also picks up the submodules' tests, which
# live under $MODULE/modules/*/tests and would otherwise need a second path.
case "$suite" in
  unit)       filter='/\\Unit\\/' ;;
  kernel)     filter='/\\Kernel\\/' ;;
  functional) filter='/\\Functional\\/' ;;
  all)        filter='' ;;
esac

# Unit is a sub-second suite; a worker pool costs more than it saves. Every
# other suite installs a Drupal site per test class, which is what parallelism
# is for.
if [[ "$suite" == "unit" || "$serial" == 1 ]] || [[ ! -x vendor/bin/paratest ]]; then
  runner=(vendor/bin/phpunit -c web/core)
else
  runner=(vendor/bin/paratest -c web/core --runner=WrapperRunner -p "$(nproc)")
fi

if [[ -n "$filter" ]]; then
  runner+=(--filter "$filter")
fi

exec "${runner[@]}" "${args[@]}" "$MODULE"
