Comprehensive guide to the bash-logger test suite, including how to run tests, write new tests, and understand the test framework.
- Overview
- Running Tests
- Code Coverage and Static Analysis
- Test Suite Structure
- Writing Tests
- Adding New Tests
- Debugging Failed Tests
- Continuous Integration
- Performance Benchmarks
- zsh Signal Handler Stress Check
- Related Documentation
The bash-logger project includes a comprehensive Bash-based test suite. To see the current
number of test suites and individual tests, run bash tests/run_tests.sh and check the
summary output. The test framework is built in pure Bash and designed to be:
- Self-contained: No external test frameworks required
- CI-friendly: Clear exit codes and non-interactive
- Developer-friendly: Colored output and detailed error messages
- Maintainable: Simple structure that's easy to extend
From the project root:
cd tests
./run_tests.shOr from anywhere in the project:
./tests/run_tests.shRun the tests as a normal user, not as root. Several security tests check that the logger handles a file it cannot write or read. Root can write and read any file, so those tests fail when run as root, including in containers where root is the default user.
On bash-logger 3.0.3, a run as root with the default TEST_SHELLS reported 751 results: 713 passed, 11 failed and 27 skipped. The 11 failures are in:
| Suite | Failures |
|---|---|
test_path_traversal |
3 |
test_toctou_protection |
3 |
test_error_conditions |
2 |
test_config |
1 |
test_config_security |
1 |
test_environment_security |
1 |
The same checkout run as a normal user had no failures. If you see these failures on a clean checkout, check id -u before looking for a bug.
In a container, create a user and run the suite as that user, as the container jobs in
.github/workflows/tests.yml do:
# Debian, Ubuntu and Fedora images. On Alpine and busybox images use: adduser -D tester
useradd --create-home tester
chown -R tester /path/to/bash-logger
su tester -c 'cd /path/to/bash-logger/tests && ./run_tests.sh'The test runner automatically detects available CPU cores and runs tests in parallel (capped at 8 jobs). You can override this with the -j or --parallel option:
# Auto-detected parallelism (default behavior)
./run_tests.sh
# Run with 4 parallel jobs (explicit)
./run_tests.sh -j 4
# Run with 8 parallel jobs (explicit)
./run_tests.sh -j 8
# Combine with other options
./run_tests.sh -j 8 --junitEnvironment Variable Override:
Set TEST_PARALLEL_JOBS to control parallelism without command-line flags:
# Useful for CI/CD pipelines
export TEST_PARALLEL_JOBS=4
./run_tests.sh
# Or inline
TEST_PARALLEL_JOBS=4 ./run_tests.shFailing when too many tests are skipped:
Set TEST_MAX_SKIPPED to a non-negative integer without leading zeros (except 0) to fail
the run when it skips more tests than that. A future environment change then cannot silently
reduce coverage:
# At most 10 skipped tests are allowed
TEST_MAX_SKIPPED=10 ./tests/run_tests.shThe guard runs after the summary. It exits 1 with the skip count when the threshold is
exceeded, and also exits 1 when the value is not a non-negative integer. CI uses it in the
test-alpine job (see Continuous Integration).
Stopping at the first failure:
Use --fail-fast (or -x) to stop the runner immediately after the first suite that
contains failures. This is the fastest way to isolate a broken test during development
or when diagnosing make sonar-analysis failures:
# Stop at first failing suite
./tests/run_tests.sh --fail-fast
# Or via Make
make test-fail-fastIn sequential mode the runner stops right after the failing suite and prints the "Failed Tests"
summary immediately. --fail-fast always runs sequentially: if parallel jobs are configured
(via -j N or TEST_PARALLEL_JOBS), the flag overrides them to ensure the run truly stops
at the first failure.
Crashed and empty suites:
Every dispatched suite is isolated in a subshell in both parallel and sequential modes.
The runner waits for each suite's PID and checks its exit status and result file.
A nonzero exit, an early exit before completion (even exit 0), missing or incomplete
results, or a completed suite reporting zero tests makes the runner exit with status 1.
The final summary names the suite and its exit status; empty suites report reported 0 tests.
The last 20 lines of a crashed or empty suite's combined stdout/stderr are printed for diagnosis.
Completed passes, assertion failures and skips are preserved when the worker can write its
exit snapshot. A suite error adds one failed test to those completed results; an interrupted
test is represented by that error rather than counted twice. If the worker cannot write a complete
result snapshot (for example, its exit trap was replaced), the suite contributes one error; partial results are discarded.
A suite that skips every test has a nonzero test count and continues to pass.
Sequential mode continues with the next suite after a crash unless --fail-fast is enabled.
Performance Impact:
- Sequential (
-j 1): ~5+ minutes for full suite - 4 parallel jobs: ~2-3 minutes
- 8 parallel jobs: ~1-2 minutes
Recommendations:
- Local development: Auto-detection works well (runs up to 8 parallel jobs)
- CI/CD: Set
TEST_PARALLEL_JOBS=4for GitHub Actions or similar (2-4 core runners) - Pre-commit hooks: Configured to use
-j 8explicitly for faster commits - Systems with many cores (16+) benefit from the 8-job cap to avoid I/O contention
The make test target and pre-commit hooks take advantage of the auto-detected parallelism for optimal local performance.
Run one or more specific test suites:
cd tests
./run_tests.sh test_log_levels
./run_tests.sh test_initialization test_formatAvailable test suites:
test_ansi_injection- ANSI escape sanitization and related security teststest_bench_script- The per-message benchmark script: verdict logic, failure paths and a slow-library canarytest_concurrent_access- Concurrency and parallel logging behaviortest_config- Configuration file parsing and behaviortest_config_security- Security hardening for configuration inputtest_edge_cases- Boundary and unusual input handlingtest_environment_security- Environment-based security checkstest_error_conditions- Error handling and defensive behaviortest_format- Message format templates and formatting behaviortest_fuzzing- Fuzz-style robustness checkstest_initialization- Logger initialization behaviortest_install- Installation and setup scriptstest_journal_logging- Journal-specific behavior and forced journal loggingtest_junit_output- JUnit XML report generationtest_license_year- Copyright year update script for the LICENSE filetest_log_levels- Log level functionalitytest_mixed_sanitization_modes- Combined sanitization mode behaviortest_output- Output routing and stream behaviortest_path_traversal- Path traversal protectionstest_resource_limits- Resource and size limit behaviortest_runner- Crash containment, suite accounting, empty suites and runner diagnosticstest_runtime_config- Runtime configuration changestest_script_name_sanitization- Script and tag name sanitizationtest_sensitive_data- Sensitive data handling protectionstest_toctou_protection- TOCTOU/race-condition protectionstest_unsafe_newlines- Unsafe newline mode behavior
The test runner provides colored, hierarchical output:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Bash Logger Test Suite
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Running test_log_levels...
✓ Log level constants are defined
✓ FATAL is alias for EMERGENCY
✓ get_log_level_value converts names to numbers
...
✓ test_log_levels: 12 passed
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Test Summary
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Total Tests: 466
Passed: 461
Failed: 0
Skipped: 5
All tests passed!
Symbols:
- ✓ (green) - Test passed
- ✗ (red) - Test failed
- ⊘ (yellow) - Test skipped
Exit Codes:
0- All tests passed1- One or more tests failed
The project supports code coverage reporting and static analysis via SonarQube. These tools are available through Makefile targets but require additional setup as they depend on external tools and services.
Note: These features are primarily used by the maintainer for local analysis against a private SonarQube instance. They are documented here for completeness and for contributors who wish to run similar analysis.
The coverage and SonarQube targets require the following tools:
| Tool | Purpose | Installation |
|---|---|---|
| kcov | Code coverage for Bash scripts | sudo dnf install kcov (Fedora) or sudo apt install kcov (Debian/Ubuntu) |
| sonar-scanner | SonarQube CLI scanner | Download from SonarQube docs or use package manager |
| secret-tool | GNOME Keyring CLI for secure token storage | sudo dnf install libsecret (Fedora) or sudo apt install libsecret-tools (Debian/Ubuntu) |
Additionally, you need:
- Access to a SonarQube server - The project's
sonar-project.propertiesis configured for the maintainer's private instance. You'll need to modify this file for your own server. - SonarQube authentication token - Stored securely in the GNOME Keyring (see below).
kcov provides code coverage for Bash scripts by instrumenting the script execution and tracking which lines are executed.
kcov follows bash only. Lines that run only in zsh, dash or busybox ash are reported as not covered. These include the _LOGGER_SHELL_FAMILY branches, the zsh re-entrancy guard and the
byte-counting paths. Those paths are tested by test_posix_compat, test_zsh_compat and test_shell_compat with TEST_SHELLS set. The coverage figure therefore understates real
coverage, and a bash test cannot reach those lines, so do not add bash tests to raise it.
# Run tests with coverage
make coverageThis executes:
kcov --include-path=./logging.sh coverage-report ./tests/run_tests.shOutput:
- Coverage report is generated in
coverage-report/ - HTML report:
coverage-report/run_tests.sh/index.html - SonarQube-compatible XML:
coverage-report/run_tests.sh/sonarqube.xml
The test runner can generate JUnit XML reports for CI systems and SonarQube:
# Run tests with JUnit XML output
make test-junitOr directly:
./tests/run_tests.sh --junitOutput:
- JUnit XML report:
test-reports/junit.xml - The report follows the SonarQube Generic Test Execution format
- Crashed or empty suites add a synthetic
<testCase>with an<error>element, including the suite name, exit status and output tail. Completed assertion failures retain their<failure>elements, and skipped tests retain<skipped>elements.
SonarQube provides static analysis, code quality metrics, and aggregates coverage data.
The project uses secret-tool (GNOME Keyring) to securely store the SonarQube authentication
token rather than embedding it in files or environment variables.
Store your token:
secret-tool store --label='SonarQube Token' service sonarqube account scannerYou'll be prompted to enter your token. This stores it securely in the GNOME Keyring.
Verify the token is stored:
secret-tool lookup service sonarqube account scannerThe project includes a sonar-project.properties file configured for the maintainer's
private SonarQube instance. To use your own server, update:
# Update the host URL (add this line if using a different server)
sonar.host.url=https://your-sonarqube-server.example.com
# Optionally update project key if needed
sonar.projectKey=bash-logger# Run SonarQube scanner
make sonarBefore running the scanner, this target automatically syncs the version number from
logging.sh (BASH_LOGGER_VERSION) to sonar-project.properties (sonar.projectVersion),
ensuring the version reported to SonarQube always matches the source code.
The scanner reads configuration from sonar-project.properties and uploads:
- Source code for analysis
- Coverage report from
coverage-report/run_tests.sh/sonarqube.xml - Test execution report from
test-reports/junit.xml
To run coverage, tests with JUnit output, and SonarQube scan in sequence:
make sonar-analysisThis runs the following targets in order:
coverage- Generates coverage report via kcovtest-junit- Generates JUnit XML test reportsonar- Uploads everything to SonarQube
Debugging a failing sonar-analysis:
When make sonar-analysis fails it can be hard to spot the failing test in 500+ lines.
Use make coverage-debug to run the kcov pass in fail-fast mode — it stops at the first
failure and prints the test name immediately:
make coverage-debugOnce the failing test is identified, run that suite alone without kcov to confirm whether
the failure is kcov-specific (e.g. due to kcov setting BASH_ENV or the DEBUG trap
slowing execution):
./tests/run_tests.sh <suite_name>Cleaning up reports:
make cleanThis removes coverage-report/ and test-reports/ directories along with other temporary files.
The test suite is organized into the following files:
Core Infrastructure (tests/):
run_tests.sh- Main test runnertest_helpers.sh- Assertion functions and utilities
Test Suites (tests/):
run_tests.sh discovers test suites automatically using test_*.sh
(excluding test_helpers.sh and test_example.sh).
Current runnable suite files include:
test_ansi_injection.shtest_bench_script.shtest_concurrent_access.shtest_config.shtest_config_security.shtest_edge_cases.shtest_environment_security.shtest_error_conditions.shtest_format.shtest_fuzzing.shtest_initialization.shtest_install.shtest_journal_logging.shtest_junit_output.shtest_license_year.shtest_log_levels.shtest_mixed_sanitization_modes.shtest_output.shtest_path_traversal.shtest_posix_compat.shtest_resource_limits.shtest_runtime_config.shtest_sanitize_equivalence.shtest_script_name_sanitization.shtest_sensitive_data.shtest_shell_compat.shtest_source_guard.shtest_toctou_protection.shtest_unsafe_newlines.shtest_unsupported_shells.shtest_validator_equivalence.shtest_zsh_compat.sh
Current test coverage includes:
- Core logging behavior: ✅ Extensive Notes: levels, output streams, formatting, initialization.
- Configuration handling: ✅ Extensive Notes: parsing, validation, and security-focused config tests.
- Journal logging: ✅ Extensive Notes: initialization, runtime toggles, and forced per-call journal writes.
- Security hardening: ✅ Extensive Notes: sensitive data, path traversal, ANSI/newline handling, and TOCTOU.
- Reliability and robustness: ✅ Extensive Notes: concurrency, fuzzing, edge cases, and resource limits.
- CI/reporting integrations: ✅ Covered Notes: JUnit XML output and SonarQube-related flow.
Use ./tests/run_tests.sh to get the authoritative, current totals on your machine.
Every test follows this pattern:
test_feature_name() {
start_test "Human-readable test description"
# Setup
init_logger --options
local log_file="$TEST_DIR/test.log"
LOG_FILE="$log_file"
# Execute
log_info "Test message"
# Assert
assert_file_contains "$log_file" "Test message" || return
# Mark as passed
pass_test
}Key Points:
- Function name should start with
test_ - Always call
start_testwith a descriptive message - Use
$TEST_DIRfor temporary files - Return early on assertion failure with
|| return - Call
pass_testat the end
All assertion functions are defined in test_helpers.sh.
# Assert two values are equal
assert_equals "expected" "actual" "optional message"
# Assert two values are different
assert_not_equals "unexpected" "actual" "optional message"Example:
assert_equals "$LOG_LEVEL_INFO" "$CURRENT_LOG_LEVEL" || return# Assert string contains substring
assert_contains "haystack" "needle" "optional message"
# Assert string doesn't contain substring
assert_not_contains "haystack" "needle" "optional message"
# Assert string matches regex pattern
assert_matches "string" "pattern" "optional message"Example:
local output="[INFO] Test message"
assert_contains "$output" "[INFO]" || return
assert_matches "$output" "\[INFO\].*Test" || return# File existence
assert_file_exists "path/to/file" "optional message"
assert_file_not_exists "path/to/file" "optional message"
# File content
assert_file_contains "path/to/file" "text" "optional message"
assert_file_not_contains "path/to/file" "text" "optional message"
# File size
assert_file_empty "path/to/file" "optional message"
assert_file_not_empty "path/to/file" "optional message"Example:
local log_file="$TEST_DIR/test.log"
log_info "Test"
assert_file_exists "$log_file" || return
assert_file_contains "$log_file" "Test" || return# Assert command succeeds (exit code 0)
assert_success command arg1 arg2
# Assert command fails (non-zero exit code)
assert_failure command arg1 arg2Example:
assert_success check_logger_availableAdditional helper functions available:
# Capture combined stdout/stderr
capture_output OUTPUT_VAR command args
# Capture streams separately
capture_streams STDOUT_VAR STDERR_VAR command args
# Run command with logger sourced
run_with_logger "init_logger && log_info 'test'"
# Run command with logger sourced under a named shell (may include flags)
run_with_logger_in_shell "bash --posix" "init_logger && log_info 'test'"
run_with_logger_in_shell "zsh" "init_logger && log_info 'test'"
# Skip the test if a shell is not installed (fail instead if it is listed
# in TEST_REQUIRE_SHELLS)
require_shell zsh || return 0
# Skip a test with reason
skip_test "logger command not available"
# Print the shells in TEST_SHELLS, one per line (default: bash)
test_shell_list
# Return 0 for shells whose string operations count characters (bash, zsh)
shell_counts_characters "busybox sh"
# Run a command and stop it after a number of seconds (works on macOS)
run_with_timeout 30 some_command argsSuites run in bash. To check behaviour under another shell, run the library in
a child shell with run_with_logger_in_shell, and guard the test with
require_shell:
test_example_cross_shell() {
start_test "Message is logged in bash, bash --posix and zsh"
require_shell zsh || return 0
local shell_command
for shell_command in "bash" "bash --posix" "zsh"; do
output=$(run_with_logger_in_shell "$shell_command" "init_logger --no-color; log_info hi" 2>&1)
assert_contains "$output" "hi" "shell: $shell_command" || return
done
pass_test
}Use || return 0 after require_shell: the skip or failure is already
recorded, and a non-zero status from the last test in a suite is reported by
the runner as a suite crash.
When zsh is not installed, these tests skip. Set TEST_REQUIRE_SHELLS to a
space-separated list of shells that must be present, so the tests fail instead
of silently skipping. CI sets TEST_REQUIRE_SHELLS="zsh dash busybox":
TEST_REQUIRE_SHELLS=zsh ./tests/run_tests.shSet TEST_MAX_SKIPPED to bound the number of tests a run may skip; exceeding it fails the
run (see Run All Tests).
test_shell_compat.sh, test_validator_equivalence.sh, test_sanitize_equivalence.sh,
test_posix_compat.sh and test_source_guard.sh run the library under every shell in
TEST_SHELLS (default bash).
Separate commands with commas when a command has flags:
TEST_SHELLS="bash,bash --posix,zsh,dash,busybox sh,mksh" \
./tests/run_tests.sh test_shell_compat test_validator_equivalence \
test_sanitize_equivalence test_posix_compat test_source_guardtest_shell_compat.shruns each script intests/compat/scenarios/under bash and under each other shell, and compares stdout, stderr, the log file and the exit status (timestamps masked). To cover new behaviour, add a scenario: a short POSIX sh script that sources"$LOGGER_ROOT/logging.sh"and writes any log file to"$SCENARIO_DIR/test.log". A# compat-locale: C.UTF-8header line runs it in that locale (defaultC). Shell/scenario pairs that are expected to differ for now are listed intests/compat/known_failures.txt.long_multiline.shcovers line control characters in messages of every size, either side of the lengths where the sanitizer switches totr.test_validator_equivalence.shruns the validators over the corpus intests/compat/golden/and compares with golden results recorded from the bash regular expressions the validators used before the POSIX conversion. Do not regenerate the golden files from current code; seetests/compat/generate_validator_golden.sh.test_sanitize_equivalence.shlogs a fixed corpus of messages (line control characters, ANSI sequences, UTF-8, token-like text, and sizes around thetrlimits) in three modes and compares the log output with golden results recorded from bash at 2.7.0, before the POSIX conversion. Seetests/compat/generate_sanitize_golden.sh; it leaves out the messages-n,-eand-E, which 2.7.0 logged as empty lines.test_posix_compat.shchecks the behaviour documented in Shell Compatibility.test_source_guard.shsources the library twice in each shell and checks that the readonly constants survive, that the environment cannot bypass initialisation and that_is_readonlyanswers correctly. The pipefail test is skipped in a shell that has nopipefailoption, such as dash.
Example:
if ! check_logger_available; then
skip_test "logger command not available"
return
fiJournal tests use a stub script in place of the system logger. The library runs a logger only when LOGGER_PATH has been validated and made readonly, so a stub needs the following.
tests/test_journal_logging.sh has the pattern (_create_stub_logger writes the stub and a capture file in $TEST_DIR):
result=$(bash -c "
source '$PROJECT_ROOT/logging.sh'
# Assign after sourcing, because sourcing sets LOGGER_PATH to '' unless it is already readonly.
# Make the value readonly: the library refuses a LOGGER_PATH that is not.
LOGGER_PATH='$STUB_LOGGER'; readonly LOGGER_PATH
# Stop the library from looking for the real logger. Without this, journal logging is disabled
# when a real logger is installed, because its path differs from the locked one.
_find_and_validate_logger() { return 0; }
check_logger_available() { return 0; }
init_logger --no-color --quiet
log_to_journal INFO 'message for the stub'
" 2>&1)
assert_file_contains "$STUB_CAPTURE" "message for the stub" || return- A stub that is assigned to
LOGGER_PATHbut not made readonly is never run. This is the usual reason a test that worked on 2.x stops capturing journal calls. - Do the assignment in the same shell that runs the library, inside the
bash -cscript. A test function that sets the variable does not affect the child shell. - The two function overrides are internal. If they change, update every suite that uses them. See Journal Logging.
-
Descriptive Names: Use clear, specific test names
# Good test_error_messages_go_to_stderr() # Bad test_stderr()
-
Isolated Tests: Each test should be independent
# Each test gets fresh logger state via setup_test test_feature_one() { start_test "..." init_logger --level INFO # Test specific to INFO level } test_feature_two() { start_test "..." init_logger --level DEBUG # Independent - doesn't affect other tests }
-
Use Temporary Files: Always use
$TEST_DIRfor test fileslocal log_file="$TEST_DIR/my_test.log" LOG_FILE="$log_file"
-
Clear Assertions: Add descriptive messages for complex assertions
assert_equals "$expected" "$actual" "Level should be INFO after init" || return
-
Test Edge Cases: Include boundary conditions and error cases
test_empty_message() test_very_long_message() test_invalid_log_level()
To add a completely new test suite:
- Create the test file:
tests/test_feature.sh
#!/usr/bin/env bash
#
# test_feature.sh - Tests for new feature
#
# Tests:
# - Brief description of what's tested
# Individual test functions
test_feature_works() {
start_test "Feature works as expected"
init_logger --quiet
local log_file="$TEST_DIR/test.log"
LOG_FILE="$log_file"
# Your test logic here
log_info "Test"
assert_file_contains "$log_file" "Test" || return
pass_test
}
test_feature_edge_case() {
start_test "Feature handles edge case"
# Your test logic
pass_test
}
# Call all test functions
test_feature_works
test_feature_edge_case- Make it executable:
chmod +x tests/test_feature.sh-
No test runner edit required:
tests/run_tests.shauto-discoverstest_*.shfiles intests/(excludingtest_helpers.shandtest_example.sh). -
Run your new tests:
cd tests
./run_tests.sh test_featureTo add tests to an existing suite:
- Add test function to the appropriate file
- Call the function at the bottom of the file
- Run the suite to verify
Example - adding to test_log_levels.sh:
# Add this function
test_custom_log_level() {
start_test "Custom log level works"
# Your test implementation
pass_test
}
# Add this call at the bottom
test_log_level_constants
test_fatal_alias
# ... existing calls ...
test_custom_log_level # Add your new testWhen a test fails:
-
Use fail-fast to isolate the suite - re-run with
--fail-fastso the runner stops immediately after the first failure, keeping it at the top of the output:make test-fail-fast # or ./tests/run_tests.sh --fail-fast -
Review the failure message - includes test name and reason:
✗ test_feature Reason: Expected 'value1' but got 'value2' -
Check test artifacts - failed tests preserve temporary directories:
Test artifacts in: /tmp/bash-logger-tests.XXXXXX/timestamp -
Run specific test for faster iteration:
./run_tests.sh test_specific_suite
-
Add debug output temporarily:
test_feature() { start_test "..." # Add debug output echo "DEBUG: variable=$variable" >&2 echo "DEBUG: log_file contents:" >&2 cat "$log_file" >&2 assert_equals "expected" "$variable" || return pass_test }
-
Check the logging module - source it interactively:
source logging.sh init_logger --level DEBUG log_info "Test"
The test suite is designed to work seamlessly in CI environments:
GitHub Actions Example:
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install zsh, dash, busybox and mksh
run: sudo apt-get update && sudo apt-get install -y zsh dash busybox mksh
- name: Run tests
env:
TEST_SHELLS: bash,bash --posix,zsh,dash,busybox sh,mksh
TEST_REQUIRE_SHELLS: zsh dash busybox mksh
run: |
cd tests
./run_tests.shRequirements:
- Bash 3.2 or later (the Bash 3.2 that macOS ships as
/bin/bashis supported) - Standard Unix utilities (cat, grep, wc, date, mkdir, touch)
- Optional:
loggercommand for journal logging tests - Optional:
zsh,dashandbusyboxfor cross-shell tests (required when listed inTEST_REQUIRE_SHELLS) - Optional:
bcfor accurate test timing in JUnit XML output (durations show as 0 if unavailable)
The CI workflow also runs the full suite on macOS under /bin/bash 3.2 with the BSD userland
(test-macos-bash32 in .github/workflows/tests.yml). Write tests so they run on both: avoid
Bash 4+ syntax, and avoid GNU-only options such as date +%s%N or sed -i without a suffix.
Other jobs in the same workflow:
test-bash-versionsruns the suite in thebash:4.2,bash:4.4andbash:5.1Docker images (the RHEL 7, RHEL 8 and Ubuntu 22.04 era versions). The images are Alpine based, so the tests run with musl and BusyBox tools, and the stub scripts they write must not assume/bin/bashor GNUsed.test-alpineruns the suite on a pinned Alpine release with every supported shell, using the real BusyBox and musl of a default Alpine system. It setsTEST_MAX_SKIPPED=10, so a change that silently skips the UTF-8 tests again fails the job instead of shrinking coverage.compare-with-releaserunsscripts/compare-with-release.py, described below.benchmarkrunsscripts/bench-logging.shagainst the base branch, described under Performance Benchmarks.
scripts/compare-with-release.py runs consumer-style scripts against logging.sh from the
last release of the previous major version and against the working copy. It covers 45 bash
option and locale modes, 38 zsh modes, and 59 API scenarios under bash, bash --posix
and zsh, and compares stdout, stderr, log files and exit status.
python3 -I scripts/compare-with-release.pyThe release to compare with, and the differences that are allowed, are in
scripts/compare-with-release.json. Each allowed difference names its section of the upgrade
guide. When a change alters behaviour on purpose, document it in the upgrade guide, then add a
narrow scenario for it and allow only that scenario. Do not allow a whole shell mode.
The script enforces this: it exits with status 2 before running anything when an entry in
allowed_differences names a mode instead of an x: scenario, unless that mode is in
baseline_unusable. It also checks that each baseline_unusable entry names a real case and a
test that exists in tests/test_posix_compat.sh.
When one output line differs in a whole mode, rewrite that line instead of allowing the mode.
baseline_rewrites change the 2.x output and candidate_rewrites the 3.x output before the
comparison. Give each rewrite the narrowest scope that works: cases lists the only cases it
applies to, and outputs the only outputs, and the pattern should match the exact line. A
candidate_rewrites entry hides a difference in the current code, so use it only for a known
bug, say so in its reason, and remove it when the bug is fixed.
A mode in which the previous release cannot run at all, such as zsh under set -u, is listed in
baseline_unusable with a reason and the test_posix_compat.sh test that covers it. The script
does not run these cases and reports them as NOT COMPARED. They do not count as skipped, so
--strict ignores them.
Options: --filter TEXT runs only cases whose shell/case name contains TEXT,
--json-out FILE writes both outputs of every difference, and --strict fails when zsh or a
locale is missing. Full coverage needs the en_GB.UTF-8, tr_TR.UTF-8 and
de_DE.ISO-8859-1 locales; on Fedora, install glibc-langpack-en, glibc-langpack-tr and
glibc-langpack-de.
CI Characteristics:
- Non-interactive
- Clean exit codes (0=pass, 1=fail)
- Temporary files in system temp directory
- Skips tests when dependencies unavailable
- No pager usage or interactive prompts
scripts/bench-logging.sh measures how long logging.sh takes per message. It exists to catch a
change that adds a process, a loop or a quadratic step to the logging path. The Per-message Benchmark job in .github/workflows/tests.yml runs it on every pull request and compares the
branch with main.
Each run starts a shell, sources logging.sh, calls init_logger and logs one message in a loop.
The script times a run with no messages and a run with the scenario's messages, and divides the
difference by the message count. Shell start-up, sourcing and init_logger are therefore not part
of the per-message cost. That start-up cost is printed once per shell as an information row.
| Scenario | Messages per run | What it logs |
|---|---|---|
plain |
300 | 60 ASCII characters with log_info |
filtered |
10000 | log_debug below the log level, so every call is filtered out |
console |
300 | 60 ASCII characters to the console with colour |
format |
300 | 60 ASCII characters with a custom --format |
ansi |
200 | 60 characters containing escape sequences that are sanitized |
long-line |
200 | 4 KB, no control characters |
utf8 |
100 | 4,000 two-byte characters |
huge-line |
100 | 100 KB, no control characters |
lines-4k |
100 | 4 KB with a newline every 64 bytes |
lines-16k |
50 | 16 KB with a newline every 64 bytes |
lines-64k |
100 | 64 KB with a newline every 64 bytes |
lines-256k |
50 | 256 KB with a newline every 64 bytes |
The counts of the large scenarios are chosen so that one run takes about a second. A shorter run is dominated by timer resolution and scheduling noise on a shared runner.
The script runs every scenario in bash, bash --posix, zsh, dash and busybox sh in CI.
On Fedora, install the extra shells with sudo dnf install zsh dash busybox.
git fetch origin main
make benchmake bench compares the working tree's logging.sh with origin/main:logging.sh. Two
variables change what it runs:
# Other shells, one scenario
make bench BENCH_ARGS='--scenario plain bash dash "busybox sh"'
# Compare with a different file instead of origin/main
make bench BENCH_BASELINE=/path/to/other/logging.shThe script can be called directly. Run scripts/bench-logging.sh --help for every option. Without
--baseline it only prints the per-message cost of the current file.
A laptop under load gives noisy numbers. Close other work first, and run it twice before believing a result close to a limit.
A comparison with the baseline fails when both of these hold:
- The ratio of the branch to the baseline is above
--max-ratio(default 1.15). - The branch is at least 100 microseconds per message slower (
--min-difference). A smaller difference is timing noise whatever the ratio. Thefilteredscenario costs only 7 to 25 microseconds per message, so it uses a floor of 2 microseconds instead: with 100 it could never fail.
The scaling check compares lines-256k with lines-16k. A message 16 times longer should cost
about 16 times more. The check fails when the growth is above --max-scaling (default 32), which
points to a step that is quadratic in the message length.
To keep noise from failing a pull request, a result over a limit is not final:
- Each round times the branch and the baseline one after the other, and swaps which goes first every round, so a change in machine load during the run affects both.
- The median of 5 rounds is compared with the limit.
- If it is over, the script says
SLOWERorTOO STEEPand measures again with 10 rounds. The job fails only if the second measurement is over the limit as well. Both values are printed in the failure message.
A baseline that cannot run in a shell (for example a release that only supports bash) is
reported as baseline unavailable once per row and does not fail the job. A run that exits with
an error, or whose log file has the wrong number of lines, always fails.
Read the failure message first. FAIL <shell> <scenario>: ratio A, then B with 10 rounds means
the scenario was slower than main in both measurements, so it is a real slowdown. Run
make bench BENCH_ARGS='--scenario <scenario> <shell>' locally to reproduce it, and look for an
added subshell, command substitution or external command on that path. A message that names an
exit status or a line count is a broken run, not a slow one, and the message says which shell
and scenario.
A failure that appears once and does not repeat on a re-run of the job is a sign that a limit is too tight. Run the calibration below before raising it.
The job writes a markdown table to the run's summary page: every result, the limits, the shell
versions and the number of CPUs. The full text output is the benchmark-results artifact. The
summary is written when the job fails too.
The limits have to sit above the spread that two identical files show on a CI runner, or the job
fails on noise. The calibration mode measures that spread. It compares logging.sh with a copy of
itself many times, so any ratio above 1 is noise.
gh workflow run tests.yml --ref <branch> -f calibrate=true -f calibration_runs=20calibrate replaces the benchmark job with one job per shell and scenario group, followed by a
job that merges their results into one table on the run's summary page. For every shell and
scenario the table shows the number of comparisons, the minimum, median and maximum ratio, the
largest slowdown in microseconds per message, the number of comparisons over the limit, and the
number still over it after measuring again. The last number is what would fail a pull request.
The maximum ratio should be well under the limit, the largest slowdown well under the floor, and
the last number should be zero.
The same mode runs locally: scripts/bench-logging.sh --calibrate 20 --scenario plain bash.
Add --calibration-file FILE to keep the rows as tab-separated values.
Change --max-ratio, --max-scaling or the 100 microsecond floor only with calibration data
that shows the current value is too tight. The pull request that changes a limit should include
the table.
tests/test_bench_script.sh tests the script itself and takes a few seconds. It covers the
verdict functions at their boundaries, the failure paths, the decision to measure again, the
summary and the calibration output. A canary test runs the real script against a copy of
logging.sh that starts an extra process per message, and checks that the script reports it as
SLOWER and fails. If that test fails, the benchmark has stopped detecting a slowdown.
zsh 5.9 can crash when a trap handler logs while the main code is logging (see
Known limitation: zsh signal handlers).
tests/test_zsh_compat.sh checks that the guard in _log_message is installed, and that a call made
while the busy flag is set runs in another process, in zsh and in zsh --emulate sh. Those tests
are fast and deterministic, and run with the suite.
Whether the guard prevents the crash is checked by a stress run, which is not part of the suite:
make stress-zsh
make stress-zsh STRESS_ARGS='--runs 5 --duration 8'scripts/stress-zsh-signals.sh logs from a USR1 handler about 50 times a second while the main
loop logs, in plain zsh and in zsh --emulate sh. Each run lasts the full duration (8 seconds by
default), and the script exits 1 if a run ends with a signal such as the crash status 139.
It is separate from the suite for two reasons. Each run costs 16 seconds, and a test that skips
unless it is enabled would add skipped tests to a job that has no room: the Alpine job fails above
TEST_MAX_SKIPPED=10 and skips 10 today. A pass is not proof: on the main branch without the
guard, about half of the runs crash within 1 second and all within 5 seconds, so a run of 8 seconds
is long enough to show the crash, but a pass of 0 in 30 runs is consistent with a true rate of up
to about 10 percent.
- Test Suite Reference - How the suite is put together: the runner, the helper library, every suite and the cross-shell machinery (describes version 3.0.3)
- logging.sh Architecture Reference - How
logging.shis structured (describes version 3.0.3) - Writing Tests - Contributor guide: how to write and structure tests, with annotated examples and common pitfalls
- Getting Started - Basic usage of the logging module
- Initialization - Initialization options and configuration
- Examples - Comprehensive usage examples
- Troubleshooting - Common issues and solutions