Files
debianito-post-install/tests/test_helper.bash
T
stornic56 149fb56e8c Desktop environment support & QA expansion
- `.github/workflows/ci.yml` added as a new workflow: job `lint-and-test` on `runs-on: ubuntu-latest` with `container: debian:trixie`, checking out via `actions/checkout@v4`, installing `bats` and `shellcheck`, running `shellcheck --severity=error debianito.sh modules/**/*.sh` (with `shopt -s globstar`) and `bats tests/`.

- `debianito.sh` CLI parser: `AUTO_YES=0`, `ALLOW_DESTRUCTIVE=0` declared after `MODULES_DIR` and before `_boot_mark`; `_usage()` prints `Usage: debianito.sh [OPTIONS]` with `--yes`, `--allow-destructive` and `--help`; the `while [ $# -gt 0 ]` / `case` loop consumes `--yes` and `--allow-destructive`, prints `Unknown option: $1 (run with --help for usage)` to stderr and `exit 2` for unknown flags, and `--help|-h` runs `_usage` then `exit 0`.

- `modules/utils.sh`: new global `_SELECTION_CONFIRMED=0` and `_confirm_install_list()` (utils.sh:756-785), which renders items capped at 15 with `... and N more`, computes `height` capped at 24, calls `_confirm "$title" "$list" "$height" 65`, arms `_SELECTION_CONFIRMED=${#items[@]}` on yes, and returns 1 for an empty list or on decline. `_install_pkg()` (utils.sh:789-804) decrements the countdown instead of prompting, and only prompts via `elif ! _confirm "Install: ${pkg}" "Install ${pkg}\nVersion: ${ver}?"; then return 0`.

- Bulk retrofit in `modules/extras/**/*.sh` (18 sites): `_confirm_install_list "Título" "${array[@]}" || return` placed right after the `whiptail` selection is parsed, the install loop left intact, and `_SELECTION_CONFIRMED=0` after the loop. Files: office/office.sh:101, system/software_centers.sh:29, system/system.sh:133, communication/communication.sh:68, design/design.sh:42, download/download.sh:48+55, terminals/terminals.sh:31, security/security.sh:30, players/players.sh:20, themes/fonts/fonts.sh:32, dev/dev.sh:44, programming/programming.sh:57, themes/desktop-themes/desktop-themes.sh:30, fetch/fetch.sh:41, themes/icons/icons.sh:47, themes/cursors/cursors.sh:28, internet/internet.sh:197, java.

- `modules/bullseye/extras.sh` (13 sites) plus `modules/bullseye/legacy.sh` (1 site, `install_gaming_bullseye`, guarded with `if [ ${#_install_pkgs[@]} -gt 0 ]` so a i386-only selection does not blank the summary) plus `modules/desktop_display.sh` (1 site, XFCE Custom — a no-loop `_run_cmd` batch with the reset immediately after it). Special cases: download.sh and bullseye/download each have two checklists merged into one combined summary; legacy.sh gaming skips the reset when the list is empty; XFCE Custom resets before `_xfce_polkit_rules` so the counter cannot leak.

- `modules/desktops/desktop_gnome.sh` (new): `gnome_menu()` runs a `_radiolist` with "1" "GNOME (Full Desktop)", "2" "GNOME Core (Minimal Install)", "3" "Back", then `_install_gnome_full()` and `_install_gnome_core()`. Each arms `_confirm_install_list "GNOME Full Desktop" gnome gdm3 || return` (core: `gnome-core gdm3`), keeps an already-configured display manager via `_existing_display_manager` by setting `target_dm="$keep_dm"`, writes the preseed `echo "${target_dm} shared/default-x-display-manager select ${target_dm}" | sudo debconf-set-selections`, installs `sudo apt install -y gnome gdm3` / `gnome-core gdm3`, enables `gdm3` only when `target_dm = "gdm3"`, resets `_SELECTION_CONFIRMED=0` and calls `_offer_pipewire_after_desktop`.

- `modules/desktops/desktop_kde.sh` (new): `kde_menu()` runs a `_radiolist` with "1" "KDE Plasma (Full Desktop)", "2" "KDE Plasma Desktop (Minimal)", "3" "Back"; `_install_kde_full()` and `_install_kde_minimal()` arm `_confirm_install_list "KDE Plasma Full" kde-standard sddm || return` (minimal: `kde-plasma-desktop sddm`), preseed `sddm shared/default-x-display-manager select sddm`, install `sudo apt install -y kde-standard sddm` / `kde-plasma-desktop sddm`, enable `sddm` only when it is the target DM, reset the counter and offer PipeWire.

- `modules/desktop_display.sh` `desktop_environment_menu()`: `env_items+=("3" "GNOME")`, `env_items+=("4" "KDE Plasma")`, `env_items+=("5" "Back")`; the case adds `3)` loading `gnome` via `_load_module gnome || continue` and calling `gnome_menu`, and `4)` loading `kde` via `_load_module kde || continue` and calling `kde_menu`; the dead TODO comment was removed.

- PipeWire retrofit in `modules/desktop_display.sh` (6 sites): `_install_lxde_full`, `_install_lxde_core`, `_install_xfce_full`, `_install_xfce_minimal`, `_install_xfce_wayland` and `_install_xfce_custom` each call `_offer_pipewire_after_desktop` after their install block.

- `_offer_pipewire_after_desktop()` and `_existing_display_manager()` added at the end of `modules/desktop_display.sh`: `_offer_pipewire_after_desktop` checks `pipewire-audio` (`pipewire` when `DEBIAN_VERSION = 11`), returns 0 via `is_installed`, otherwise `_confirm "PipeWire Audio" "No PipeWire audio server is installed.\n\nInstall the PipeWire audio stack (recommended)?"` calls `_install_pipewire_standard` and returns 0. `_existing_display_manager` reads `${DM_FILE:-/etc/X11/default-display-manager}`, reads the basename as the DM, and otherwise scans `gdm3 lightdm sddm greetd gdm` with `systemctl is-enabled`, printing nothing when none is found.

- `_ensure_apt_updated` added before the GNOME/KDE `apt install` transactions (4 sites, deduplicated per session); `gnome gdm3` and `kde-standard sddm` are installed alongside even when another display manager is kept as the default.

- Extraction to `modules/desktops/`: `desktop_lxde.sh` (38 lines) and `desktop_xfce.sh` (119 lines) created with the `lxde_menu` / `_install_lxde_full` / `_install_lxde_core` and `xfce_menu` / `_install_xfce_full` / `_install_xfce_minimal` / `_install_xfce_wayland` / `_install_xfce_custom` / `_xfce_polkit_rules` blocks moved verbatim; both carry `# License GPL v3` in their headers.

- `modules/desktop_display.sh` reduced from 542 to 394 lines (−154): lines 55-208 removed, the dispatch (desktop_display.sh:39-46) replaced with `_load_module xfce || continue` / `lxde_menu`, and the file left with `manage_desktop_display`, `desktop_environment_menu`, `display_manager_menu`, `lightdm_config_menu`, `configure_greetd`, `configure_gdm3`, `configure_sddm`, the two shared helpers.

- `modules/utils.sh` `_load_module` map: `xfce)` → `${MODULES_DIR}/desktops/desktop_xfce.sh`, `lxde)` → `${MODULES_DIR}/desktops/desktop_lxde.sh`, `gnome)` → `${MODULES_DIR}/desktops/desktop_gnome.sh`, `kde)` → `${MODULES_DIR}/desktops/desktop_kde.sh`; deps for `xfce`, `lxde`, `gnome` and `kde` are `(desktop_display audio)` and `desktop_display` is `(repos audio)`.

- `modules/desktops/desktop_xfce.sh` `_xfce_polkit_rules()` writes `/etc/polkit-1/rules.d/85-suspend.rules` and `89-backlight.rules` via `sudo tee`, adds the `backlight` group with `groupadd --system` fallback, adds the real login user from `/etc/passwd` to `backlight` and restarts `polkit.service`.

- ES→EN user-facing strings: 14 strings across 4 files — `desktop_display.sh` `lxdе_menu` ("LXDE (Full Desktop)", "LXDE Core (Minimal Install)"), `gpu/nvidia.sh` Kepler legacy-driver notice ("Kepler GPU detected (GKxxx)… Install the legacy driver for Kepler?"), `bullseye/legacy.sh` ("Install NVIDIA driver?", "Skipping NVIDIA driver.", "Installing NVIDIA driver ${gpu_gen}...") and `bullseye/extras.sh` ("firmware-linux-nonfree provides drivers for… Install?").

- ES→EN internal comments: ~35 comments across 9 files — section headers in `_install_nvidia_standard`, `gpu/_helpers.sh` (lines 5, 113), `gpu/nvidia.sh` (lines 8-12, 19-22, 68-70, 167-172, 196, 239-253, 262-263, 275, 291, 336-338, 376), `gpu.sh` (lines 15-17), `bullseye/repos.sh` (line 2), `firmware.sh` (line 235, "--- Load verification ---"), `utils.sh` (lines 129, 132, 153 — timezone Paso 1/2/4) and `utils.sh:546,548`.

- set -e abort fix: `debianito.sh:149` now reads `_system_preferences_menu || true`, consistent with the other dispatch chains (14 of the 15 chains already had the guard); a declined pre-apply summary now leaves the TUI alive instead of terminating the script.

- `docs/desktops_display.md`: 4 hunks — intro now lists GNOME/GNOME Core/KDE Plasma/KDE Plasma Desktop/XFCE/XFCE Wayland/XFCE Custom/LXDE, a new "Modular layout" paragraph describing `modules/desktops/` and lazy loading, Block 1 rewritten into four environments, five new bullets (pre-apply summary, existing-DM preservation, PipeWire offer, stale-lists guard) and a Desktop Environment Packages table.

- `docs/quickstart.md` line 284: Desktop Environment entry expanded to pick from XFCE (full / minimal / Wayland `labwc` on Trixie / custom checklist), LXDE (full / core), GNOME (full / core) or KDE Plasma (full / minimal).

- `_existing_display_manager` now takes the config path via `local dm_file="${DM_FILE:-/etc/X11/default-display-manager}"` so the offline test suite never reads the real system file.

- `tests/test_helper.bash`: added `_mock_systemctl()` for `is-enabled` (units in `MOCK_SYSTEMCTL_ENABLED` report `enabled`, everything else `disabled`), `MOCK_SYSTEMCTL_ENABLED=""`, `WHIPTAIL_CALLS`/`MOCK_WHIPTAIL_OUTPUT`/`MOCK_WHIPTAIL_RC`, `MOCK_DPKG_INSTALLED` and the `systemctl` entry in the mock list and in `mock_reset()`.

- `tests/desktops.bats` created with 16 tests: `_existing_display_manager` (file read, file-preferred over an enabled unit, enabled-unit fallback, candidate order, missing file, nothing configured), `_offer_pipewire_after_desktop` (5 tests: skip-installed, accept-installs, decline-returns-0, Bullseye package name, wrong package name on 11), `_load_module` (4 tests for xfce/lxde/gnome/kde) and an unknown-module case; 17→33 tests total.

- `.github/workflows/ci.yml` shellcheck severity raised from `--severity=error` to `--severity=warning`.

- `debianito.sh`: `RED`, `GREEN`, `YELLOW`, `CYAN` and `NC` plus `AUTO_YES`, `ALLOW_DESTRUCTIVE` and `DEBIAN_CODENAME` are now `export`ed as cross-file globals.

- `modules/utils.sh`: `HAS_NVIDIA`, `DESKTOP_ENV`, `AUDIO_SERVER`, `DEBIAN_VERSION` and the other cross-file globals are `export`ed.

- `modules/extras/system/software_centers.sh` gained a `#!/usr/bin/env bash` shebang.

- `shellcheck` triage (v0.11.0, baseline `--severity=warning` 25 findings → 0): removed two dead-code lines (`headless` in `extras/dev/dev.sh`, orphan `dev_id` in `firmware.sh`); `SC2206` in `extras/dev/essential.sh` fixed by expanding `$comp_pkgs` to `"${comp_pkgs[@]}"`; `SC2010`/`SC2046` (3 sites) replaced `ls … | grep` with `compgen -G "…"`; `SC2155` (2 sites, `gpu.sh` and `rescue.sh`) split command substitutions into separate lines; `SC2166` in `repos.sh` replaced `-o` with `{ … || … }`; `SC2221`/`SC2222` (2 sites, `sysinfo.sh` and `utils.sh`) collapsed the `wl*|wlp*|wlo*|wlan*` alternation to `wl*`; `SC1090` in `extras.sh` gained a justification comment on the disable directive.

- Final verification: `bash -n` on all 15 modified `.sh` files and `set -euo pipefail` at `debianito.sh:3` both intact; `bats tests/` reports 33 ok / 0 failed; invariants `offers 11`, `confirm_install_list 39` and `_SELECTION_CONFIRMED=0 40` hold.
2026-10-05 23:17:38 -05:00

373 lines
15 KiB
Bash

#!/usr/bin/env bash
# test_helper.bash — Setup and offline system mocks for the
# debianito BATS test suite.
#
# Layout
# ------
# load_utils() Safe loading of the modules under test.
# _mock_*() Mock implementations (one per command).
# _install_mocks() Serializes the _mock_* functions into
# standalone executables under $MOCK_BIN_DIR.
# mock_reset() Per-test fixture reset + PATH setup.
#
# Why PATH-based mock scripts instead of plain shell functions?
# ------------------------------------------------------------
# _init_lspci_cache() runs `timeout 2 lspci -nn` and
# detect_network() runs `timeout 2 ip -o link show`,
# `timeout 2 ip -4 -o addr show <iface>` and
# `timeout 2 iwgetid -r <iface>`. timeout(1) execs its
# target as a CHILD PROCESS, and a child process cannot see
# the shell functions of its parent. The _mock_* functions
# are therefore written to disk as real executables
# (self-contained: shebang + `declare -f` output + dispatch
# line) and $MOCK_BIN_DIR is prepended to PATH, so both
# direct calls and timeout-wrapped calls hit the mocks.
#
# Everything here is 100% offline: no network, no apt
# update, and no real package is installed or removed.
#
# shellcheck disable=SC2148
# ── Locations ──────────────────────────────────────────────────
[ -n "${BATS_TEST_DIRNAME:-}" ] || {
echo "test_helper.bash must be loaded from a BATS test file" >&2
return 1 2>/dev/null || exit 1
}
TEST_PROJECT_ROOT="$(cd "${BATS_TEST_DIRNAME}/.." && pwd)"
export TEST_PROJECT_ROOT
# Holds the generated mock executables (created once per
# load; the OS cleans /tmp, so no per-test cleanup needed).
MOCK_BIN_DIR="$(mktemp -d "${TMPDIR:-/tmp}/debianito-mocks.XXXXXX")"
export MOCK_BIN_DIR
# ── Safe module loading ────────────────────────────────────────
# Contract (verified against the current sources):
# * modules/utils.sh and modules/repos/repo_detect.sh
# contain ONLY function definitions and variable
# assignments — no top-level command execution — so
# sourcing them is side-effect free.
# * debianito.sh itself must NEVER be sourced from tests:
# it executes the module chain and the menu at top
# level.
load_utils() {
local f
for f in modules/utils.sh modules/repos/repo_detect.sh; do
if [ ! -f "${TEST_PROJECT_ROOT}/${f}" ]; then
echo "load_utils: missing ${TEST_PROJECT_ROOT}/${f}" >&2
return 1
fi
done
# shellcheck source=modules/utils.sh
source "${TEST_PROJECT_ROOT}/modules/utils.sh"
# shellcheck source=modules/repos/repo_detect.sh
source "${TEST_PROJECT_ROOT}/modules/repos/repo_detect.sh"
# Note: sourcing from inside a function makes the
# top-level `declare -a ETH_NAMES=()` & co. of utils.sh
# function-local; they vanish when load_utils() returns.
# That is harmless — the functions under test assign
# those arrays as globals at call time (e.g. the BH-013
# reset at the top of detect_network()), so their
# behaviour is unchanged.
:
}
# ── Globals that debianito.sh normally defines ───────────────
# The modules consume them at call time only. Colour codes
# are kept EMPTY on purpose so output assertions stay clean.
export RED="" GREEN="" YELLOW="" CYAN="" NC=""
export DEBIAN_CODENAME="bookworm"
export DEBIAN_VERSION="12"
export MODULES_DIR="${TEST_PROJECT_ROOT}/modules"
# ════════════════════════════════════════════════════════════
# Mock implementations
#
# Each mock reads its canned data from MOCK_* environment
# variables, so a test injects predictable output with a
# plain assignment (the vars are exported by mock_reset, and
# assigning to an exported var keeps the export attribute):
#
# MOCK_DPKG_INSTALLED space-separated "installed" packages
# MOCK_DPKG_VERSION version reported for installed pkgs
# MOCK_APT_CACHE_POLICY_OUTPUT `apt-cache policy <pkg>` output
# MOCK_APT_CACHE_MADISON_OUTPUT `apt-cache madison <pkg>` output
# MOCK_APT_CACHE_SEARCH_OUTPUT `apt-cache search <re>` output
# MOCK_LSPCI_OUTPUT `lspci -nn` output
# MOCK_LSUSB_OUTPUT `lsusb` output
# MOCK_IP_LINK_OUTPUT `ip -o link show` output
# MOCK_IP_ADDR_OUTPUT "iface cidr" lines for
# `ip -4 -o addr show <iface>`
# MOCK_SSID_OUTPUT `iwgetid -r <iface>` output
# MOCK_TIMEZONE_OUTPUT `timedatectl show -p Timezone --value`
# MOCK_NTP_SYNC_OUTPUT `timedatectl show --property=NTPSynchronized --value`
# MOCK_SYSTEMCTL_ENABLED space-separated units that report "enabled"
# MOCK_WHIPTAIL_OUTPUT / _RC whiptail stdout / exit code
# MOCK_SUDO_DRY_RUN 1 = log-only sudo (see _mock_sudo)
# MOCK_SUDO_LOG log file for dry-run sudo
# MOCK_APT_ROOT per-test fixture mirror of /etc/apt,
# exported to the code under test as
# APT_DIR (see the APT_DIR
# indirection in utils.sh and
# repos/repo_detect.sh)
# ════════════════════════════════════════════════════════════
# ── dpkg(1) ───────────────────────────────────────────────────
# `dpkg -l <pkg>` prints an "ii" status line and exits 0
# when <pkg> is listed in $MOCK_DPKG_INSTALLED; prints
# nothing and exits 1 otherwise (real dpkg -l reports
# "no packages found" with status 1). is_installed()
# greps for a leading "ii", so the line prefix is what
# matters — both are implemented faithfully anyway.
_mock_dpkg() {
local pkg="${@: -1}" # last argument
local installed
for installed in ${MOCK_DPKG_INSTALLED:-}; do
if [ "$installed" = "$pkg" ]; then
printf 'ii %s %s all mock package\n' \
"$pkg" "${MOCK_DPKG_VERSION:-1.0.0-mock}"
return 0
fi
done
return 1
}
# ── apt-cache(8) ──────────────────────────────────────────────
# Canned output per subcommand. The policy fixture needs at
# least 3 lines: _get_pkg_version() parses field 2 of line
# 3 (the "Candidate:" line in real output).
_mock_apt_cache() {
local sub="${1:-}"
[ $# -gt 0 ] && shift
case "$sub" in
policy)
[ -n "${MOCK_APT_CACHE_POLICY_OUTPUT:-}" ] &&
printf '%s\n' "${MOCK_APT_CACHE_POLICY_OUTPUT}"
;;
madison)
[ -n "${MOCK_APT_CACHE_MADISON_OUTPUT:-}" ] &&
printf '%s\n' "${MOCK_APT_CACHE_MADISON_OUTPUT}"
;;
search)
[ -n "${MOCK_APT_CACHE_SEARCH_OUTPUT:-}" ] &&
printf '%s\n' "${MOCK_APT_CACHE_SEARCH_OUTPUT}"
;;
esac
return 0
}
# ── lspci(8) ──────────────────────────────────────────────────
# Prints $MOCK_LSPCI_OUTPUT verbatim; arguments (-nn) are
# ignored. Served through the PATH wrapper because
# _init_lspci_cache() captures `timeout 2 lspci -nn`.
_mock_lspci() {
printf '%s' "${MOCK_LSPCI_OUTPUT:-}"
return 0
}
# ── lsusb(8) ──────────────────────────────────────────────────
# Prints $MOCK_LSUSB_OUTPUT verbatim. detect_network()
# uses it as the USB-WiFi fallback (layer 4) when no PCI
# wireless device exists.
_mock_lsusb() {
printf '%s' "${MOCK_LSUSB_OUTPUT:-}"
return 0
}
# ── ip(8) ─────────────────────────────────────────────────────
# Just enough for detect_network():
# ip -o link show → one line per interface
# ($MOCK_IP_LINK_OUTPUT)
# ip -4 -o addr show <iface> → a full "ip -o" line whose
# 4th whitespace field is
# the IPv4 CIDR of <iface>,
# looked up from the
# "iface cidr" lines of
# $MOCK_IP_ADDR_OUTPUT
_mock_ip() {
case "$1 $2" in
"-o link")
# Real `ip` terminates its output with a newline;
# `while read` loops (detect_network) drop the last
# line of an unterminated stream, so the mock must
# terminate it too.
if [ -n "${MOCK_IP_LINK_OUTPUT:-}" ]; then
printf '%s\n' "${MOCK_IP_LINK_OUTPUT:-}"
fi
;;
"-4 -o")
local iface="${5:-}" name cidr
[ -z "$iface" ] && return 0
while IFS=' ' read -r name cidr; do
if [ "$name" = "$iface" ]; then
printf '2: %s inet %s brd 192.168.1.255 scope global dynamic %s\n' \
"$iface" "$cidr" "$iface"
return 0
fi
done <<EOF
${MOCK_IP_ADDR_OUTPUT:-}
EOF
;;
esac
return 0
}
# ── iwgetid(1) ────────────────────────────────────────────────
# Prints $MOCK_SSID_OUTPUT. detect_network() calls it only
# for interfaces whose link state is UP.
_mock_iwgetid() {
printf '%s' "${MOCK_SSID_OUTPUT:-}"
return 0
}
# ── timedatectl(1) ────────────────────────────────────────────
# Just enough for _ensure_time_synced():
# show -p Timezone --value → $MOCK_TIMEZONE_OUTPUT
# show --property=NTPSynchronized --value → $MOCK_NTP_SYNC_OUTPUT
_mock_timedatectl() {
case "$1 $2" in
"show -p")
printf '%s\n' "${MOCK_TIMEZONE_OUTPUT:-UTC}"
;;
"show --property="*)
printf '%s\n' "${MOCK_NTP_SYNC_OUTPUT:-no}"
;;
esac
return 0
}
# ── sudo(8) ───────────────────────────────────────────────────
# Spec behaviour: execute the command it receives, without
# asking for a password. sudo's own flags (-v, -n, -H, …)
# are stripped; the rest runs through env(1) so that
# `sudo VAR=val cmd` prefixes work too.
#
# ⚠ WARNING: the command executes FOR REAL. Only exercise
# sudo code paths with benign commands (file copies, echo,
# true, …). Set MOCK_SUDO_DRY_RUN=1 to switch to
# logging-only mode: the invocation is appended to
# $MOCK_SUDO_LOG and the mock exits 0 without executing
# anything — the safe choice for tests that touch
# privileged code paths.
_mock_sudo() {
if [ "${MOCK_SUDO_DRY_RUN:-0}" = "1" ]; then
printf '%s\n' "$*" >>"${MOCK_SUDO_LOG:-/tmp/debianito-sudo-mock.log}"
return 0
fi
while [ $# -gt 0 ]; do
case "$1" in
-*) shift ;;
*) break ;;
esac
done
[ $# -eq 0 ] && return 0 # e.g. `sudo -v`
env "$@"
}
# ── systemctl(8) ──────────────────────────────────────────────
# Just enough for _existing_display_manager(): only the
# `is-enabled <unit>` verb is exercised. Units listed in
# $MOCK_SYSTEMCTL_ENABLED report "enabled" (exit 0); every
# other unit reports "disabled" (exit 1), matching systemd.
_mock_systemctl() {
case "${1:-}" in
is-enabled)
local unit="${2:-}" cand
for cand in ${MOCK_SYSTEMCTL_ENABLED:-}; do
if [ "$cand" = "$unit" ]; then
printf 'enabled\n'
return 0
fi
done
printf 'disabled\n'
return 1
;;
esac
return 0
}
# ── whiptail(1) ───────────────────────────────────────────────
# Prints $MOCK_WHIPTAIL_OUTPUT on stdout and exits with
# $MOCK_WHIPTAIL_RC (default 0 = "Yes" for confirm
# dialogs). Not used by the current tests; future-proofs
# the _confirm / _menu / _checklist helpers.
_mock_whiptail() {
printf '%s' "${MOCK_WHIPTAIL_OUTPUT:-}"
return "${MOCK_WHIPTAIL_RC:-0}"
}
# ── Mock installation ─────────────────────────────────────────
# Serializes every _mock_* function into a standalone
# executable under $MOCK_BIN_DIR (shebang + `declare -f`
# output + dispatch line). See the header comment for why
# PATH scripts are required.
_install_mocks() {
local name func
for name in dpkg apt-cache lspci lsusb ip iwgetid timedatectl sudo whiptail systemctl; do
func="_mock_${name//-/_}" # apt-cache → _mock_apt_cache
if ! declare -f "$func" >/dev/null; then
echo "test_helper.bash: mock function ${func} is not defined" >&2
return 1
fi
{
printf '#!/usr/bin/env bash\n'
declare -f "$func"
printf '%s "$@"\n' "$func"
} >"${MOCK_BIN_DIR}/${name}"
chmod +x "${MOCK_BIN_DIR}/${name}"
done
}
# ── Per-test reset ────────────────────────────────────────────
# Restores every fixture to a predictable empty state and
# puts the mock bin dir first on PATH. Call from setup() in
# each .bats file: BATS runs every test in a fresh subshell,
# so PATH changes never leak between tests.
mock_reset() {
# dpkg(1)
export MOCK_DPKG_INSTALLED=""
export MOCK_DPKG_VERSION="1.0.0-mock"
# apt-cache(8)
export MOCK_APT_CACHE_POLICY_OUTPUT=""
export MOCK_APT_CACHE_MADISON_OUTPUT=""
export MOCK_APT_CACHE_SEARCH_OUTPUT=""
# hardware
export MOCK_LSPCI_OUTPUT=""
export MOCK_LSUSB_OUTPUT=""
export MOCK_IP_LINK_OUTPUT=""
export MOCK_IP_ADDR_OUTPUT=""
export MOCK_SSID_OUTPUT=""
# systemd
export MOCK_TIMEZONE_OUTPUT="UTC"
export MOCK_NTP_SYNC_OUTPUT="no"
export MOCK_SYSTEMCTL_ENABLED=""
# dialogs
export MOCK_WHIPTAIL_OUTPUT=""
export MOCK_WHIPTAIL_RC="0"
# sudo(8)
export MOCK_SUDO_DRY_RUN="0"
export MOCK_SUDO_LOG="$(mktemp)"
# /etc/apt(5) fixture mirror. The modules under test read
# ${APT_DIR:-/etc/apt} (APT_DIR indirection added for
# testability), so tests build fixture trees inside
# $MOCK_APT_ROOT instead of touching the real /etc/apt.
# Fresh per test: fixtures never leak between tests.
export MOCK_APT_ROOT="$(mktemp -d)"
export APT_DIR="${MOCK_APT_ROOT}"
export PATH="${MOCK_BIN_DIR}:${PATH}"
}
# Generate the mock executables once, when this helper is
# loaded.
_install_mocks