testmark-bash

lib.sh

#!/bin/bash
## Shared helpers for the testmark-bash tests.  Sourced, not executed.
## Sources the library, makes a scratch dir and cd's into it, and provides PASS/FAIL reporting.
## The helpers stay exact under the hostile settings test-hostile-env.sh turns on:
## comparisons use `[ = ]`, which `nocasematch` doesn't touch.
# shellcheck disable=SC2034 # RESULT is read by the test scripts

set -euo pipefail

TESTDATA=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/testdata
# shellcheck source=lib/testmark.bash
source "$TESTDATA/../../lib/testmark.bash"

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
cd "$work"

RESULT=0

_pass() {
	printf 'PASS  %s\n' "$1"
}

_fail() {
	printf 'FAIL  %s\n' "$1"
	RESULT=1
}

## - @param $1 description
## - @param $2 got
## - @param $3 want
## - @stdout one PASS or FAIL line
## - @state RESULT -- set to 1 on failure
expect_eq() {
	if [ "$2" = "$3" ]; then
		_pass "$1"
	else
		_fail "$1"$'\n'"--- got:"$'\n'"$2"$'\n'"--- want:"$'\n'"$3"
	fi
}

## Quotes bytes the way the conformance harnesses do: printable ASCII as is, escapes for the rest.
##
## - @param $1 bytes
## - @stdout the quoted string, without a newline
esc() {
	local LC_ALL=C s=$1 out='' c i
	for ((i = 0; i < ${#s}; i++)); do
		c=${s:i:1}
		case $c in
		'\') out+='\\' ;;
		'"') out+='\"' ;;
		$'\n') out+='\n' ;;
		$'\r') out+='\r' ;;
		$'\t') out+='\t' ;;
		[\ -~]) out+=$c ;;
		*)
			printf -v c '\\x%02x' "'$c"
			out+=$c
			;;
		esac
	done
	printf '"%s"' "$out"
}

## Prints every hunk of a parsed document: `hunk`, `info`, and `body` lines, values quoted by `esc`.
##
## - @param $1 handle
## - @stdout the dump
dump() {
	local names name body
	mapfile -t names < <(testmark_names "$1")
	for name in "${names[@]}"; do
		body=$(testmark_body "$1" "$name" && printf x) || return
		printf 'hunk %s\ninfo %s\nbody %s\n' "$(esc "$name")" "$(esc "$(testmark_info "$1" "$name")")" "$(esc "${body%x}")"
	done
}

## Parses FILE as handle "doc", and prints its dump, or "error: " and the error message.
## A successful parse that still wrote to stderr gets a "stderr: " line too.
##
## - @param $1 file
## - @stdout the dump or the error
dump_parse() {
	if testmark_parse doc "$1" 2>"$work/err"; then
		dump doc
		[[ ! -s $work/err ]] || printf 'stderr: %s\n' "$(<"$work/err")"
	else
		printf 'error: %s\n' "$(<"$work/err")"
	fi
}

tests/lib.sh · 2.3 KiB · 5bcf631fcb