-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathrunner.sh
More file actions
executable file
·1196 lines (1031 loc) · 39.8 KB
/
runner.sh
File metadata and controls
executable file
·1196 lines (1031 loc) · 39.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# shellcheck disable=SC2155
# Pre-compiled regex pattern for parsing test result assertions
if [[ -z ${_BASHUNIT_RUNNER_PARSE_RESULT_REGEX+x} ]]; then
declare -r _BASHUNIT_RUNNER_PARSE_RESULT_REGEX='ASSERTIONS_FAILED=([0-9]*)##'\
'ASSERTIONS_PASSED=([0-9]*)##ASSERTIONS_SKIPPED=([0-9]*)##'\
'ASSERTIONS_INCOMPLETE=([0-9]*)##ASSERTIONS_SNAPSHOT=([0-9]*)##TEST_EXIT_CODE=([0-9]*)'
fi
function bashunit::runner::restore_workdir() {
cd "$BASHUNIT_WORKING_DIR" 2>/dev/null || true
}
function bashunit::runner::load_test_files() {
local filter=$1
local tag_filter="${2:-}"
local exclude_tag_filter="${3:-}"
shift 3
local IFS=$' \t\n'
local -a files
files=("$@")
local -a scripts_ids=()
local scripts_ids_count=0
# Initialize coverage tracking if enabled
if bashunit::env::is_coverage_enabled; then
# Auto-discover coverage paths if not explicitly set
if [[ -z "$BASHUNIT_COVERAGE_PATHS" ]]; then
BASHUNIT_COVERAGE_PATHS=$(bashunit::coverage::auto_discover_paths "${files[@]}")
fi
bashunit::coverage::init
fi
local test_file
for test_file in "${files[@]+"${files[@]}"}"; do
if [[ ! -f $test_file ]]; then
continue
fi
unset BASHUNIT_CURRENT_TEST_ID
export BASHUNIT_CURRENT_SCRIPT_ID="$(bashunit::helper::generate_id "${test_file}")"
scripts_ids[scripts_ids_count]="${BASHUNIT_CURRENT_SCRIPT_ID}"
scripts_ids_count=$((scripts_ids_count + 1))
bashunit::internal_log "Loading file" "$test_file"
# shellcheck source=/dev/null
source "$test_file"
# Update function cache after sourcing new test file
_BASHUNIT_CACHED_ALL_FUNCTIONS=$(declare -F | awk '{print $3}')
# Check if any tests match the filter before rendering header or running hooks
local filtered_functions
filtered_functions=$(bashunit::helper::get_functions_to_run "test" "$filter" "$_BASHUNIT_CACHED_ALL_FUNCTIONS")
local functions_for_script
functions_for_script=$(bashunit::runner::functions_for_script "$test_file" "$filtered_functions")
# Apply tag filtering to the early check as well
if [ -n "$tag_filter" ] || [ -n "$exclude_tag_filter" ]; then
local _early_filtered=""
local _early_fn
for _early_fn in $functions_for_script; do
local _early_tags
_early_tags=$(bashunit::helper::get_tags_for_function "$_early_fn" "$test_file")
if bashunit::helper::function_matches_tags "$_early_tags" "$tag_filter" "$exclude_tag_filter"; then
_early_filtered="$_early_filtered $_early_fn"
fi
done
functions_for_script="${_early_filtered# }"
fi
if [[ -z "$functions_for_script" ]]; then
bashunit::runner::clean_set_up_and_tear_down_after_script
bashunit::runner::restore_workdir
continue
fi
# Render header BEFORE set_up_before_script so user sees activity immediately
bashunit::runner::render_running_file_header "$test_file"
# Call hook directly (not with `if !`) to preserve errexit behavior inside the hook
bashunit::runner::run_set_up_before_script "$test_file"
local setup_before_script_status=$?
if [[ $setup_before_script_status -ne 0 ]]; then
# Count the test functions that couldn't run due to set_up_before_script failure
# and add them as failed (minus 1 since the hook failure already counts as 1)
local filtered_functions
filtered_functions=$(bashunit::helper::get_functions_to_run "test" "$filter" "$_BASHUNIT_CACHED_ALL_FUNCTIONS")
if [[ -n "$filtered_functions" ]]; then
# Bash 3.0 compatible: separate declaration and assignment for arrays
local functions_to_run
# shellcheck disable=SC2206
functions_to_run=($filtered_functions)
local additional_failures=$((${#functions_to_run[@]} - 1))
local i
for ((i = 0; i < additional_failures; i++)); do
bashunit::state::add_tests_failed
done
fi
bashunit::runner::clean_set_up_and_tear_down_after_script
if ! bashunit::parallel::is_enabled; then
bashunit::cleanup_script_temp_files
fi
bashunit::runner::restore_workdir
continue
fi
if bashunit::parallel::is_enabled; then
bashunit::runner::call_test_functions "$test_file" "$filter" "$tag_filter" "$exclude_tag_filter" 2>/dev/null &
else
bashunit::runner::call_test_functions "$test_file" "$filter" "$tag_filter" "$exclude_tag_filter"
fi
bashunit::runner::run_tear_down_after_script "$test_file"
bashunit::runner::clean_set_up_and_tear_down_after_script
if ! bashunit::parallel::is_enabled; then
bashunit::cleanup_script_temp_files
fi
bashunit::internal_log "Finished file" "$test_file"
bashunit::runner::restore_workdir
done
if bashunit::parallel::is_enabled; then
wait
bashunit::runner::spinner &
local spinner_pid=$!
bashunit::parallel::aggregate_test_results "$TEMP_DIR_PARALLEL_TEST_SUITE"
# Kill the spinner once the aggregation finishes
disown "$spinner_pid" 2>/dev/null || true
kill "$spinner_pid" 2>/dev/null || true
printf "\r \r" # Clear the spinner output
local script_id
for script_id in "${scripts_ids[@]+"${scripts_ids[@]}"}"; do
export BASHUNIT_CURRENT_SCRIPT_ID="${script_id}"
bashunit::cleanup_script_temp_files
done
fi
}
function bashunit::runner::load_bench_files() {
local filter=$1
shift
local IFS=$' \t\n'
local -a files
files=("$@")
local bench_file
for bench_file in "${files[@]+"${files[@]}"}"; do
[[ -f $bench_file ]] || continue
unset BASHUNIT_CURRENT_TEST_ID
export BASHUNIT_CURRENT_SCRIPT_ID="$(bashunit::helper::generate_id "${bench_file}")"
# shellcheck source=/dev/null
source "$bench_file"
# Update function cache after sourcing new bench file
_BASHUNIT_CACHED_ALL_FUNCTIONS=$(declare -F | awk '{print $3}')
# Call hook directly (not with `if !`) to preserve errexit behavior inside the hook
bashunit::runner::run_set_up_before_script "$bench_file"
local setup_before_script_status=$?
if [[ $setup_before_script_status -ne 0 ]]; then
# Count the bench functions that couldn't run due to set_up_before_script failure
# and add them as failed (minus 1 since the hook failure already counts as 1)
local filtered_functions
filtered_functions=$(bashunit::helper::get_functions_to_run "bench" "$filter" "$_BASHUNIT_CACHED_ALL_FUNCTIONS")
if [[ -n "$filtered_functions" ]]; then
# Bash 3.0 compatible: separate declaration and assignment for arrays
local functions_to_run
# shellcheck disable=SC2206
functions_to_run=($filtered_functions)
local additional_failures=$((${#functions_to_run[@]} - 1))
local i
for ((i = 0; i < additional_failures; i++)); do
bashunit::state::add_tests_failed
done
fi
bashunit::runner::clean_set_up_and_tear_down_after_script
bashunit::cleanup_script_temp_files
bashunit::runner::restore_workdir
continue
fi
bashunit::runner::call_bench_functions "$bench_file" "$filter"
bashunit::runner::run_tear_down_after_script "$bench_file"
bashunit::runner::clean_set_up_and_tear_down_after_script
bashunit::cleanup_script_temp_files
bashunit::runner::restore_workdir
done
}
function bashunit::runner::spinner() {
# Only show spinner when output is to a terminal
if [[ ! -t 1 ]]; then
# Not a terminal, just wait silently
while true; do sleep 1; done
return
fi
# Don't show spinner in no-progress mode
if bashunit::env::is_no_progress_enabled; then
while true; do sleep 1; done
return
fi
if bashunit::env::is_simple_output_enabled; then
printf "\n"
fi
local delay=0.1
local spin_chars="|/-\\"
while true; do
local i
for ((i = 0; i < ${#spin_chars}; i++)); do
printf "\r%s" "${spin_chars:$i:1}"
sleep "$delay"
done
done
}
function bashunit::runner::functions_for_script() {
local script="$1"
local all_fn_names="$2"
# Filter the names down to the ones defined in the script, sort them by line number
shopt -s extdebug
# shellcheck disable=SC2086
declare -F $all_fn_names |
awk -v s="$script" '$3 == s {print $1" " $2}' |
sort -k2 -n |
awk '{print $1}'
shopt -u extdebug
}
function bashunit::runner::parse_data_provider_args() {
local input="$1"
local current_arg=""
local in_quotes=false
local had_quotes=false # Track if arg was quoted (to preserve empty quoted strings)
local quote_char=""
local escaped=false
local IFS=$' \t\n'
local i=0
local arg=""
local encoded_arg
local -a args=()
local args_count=0
# Check for shell metacharacters that would break eval or cause globbing
local has_metachar=false
local _re1='[^\\][\|\&\;\*]'
local _re2='^[\|\&\;\*]'
if [[ "$input" =~ $_re1 ]] || [[ "$input" =~ $_re2 ]]; then
has_metachar=true
fi
# Try eval first (needed for $'...' from printf '%q'), unless metacharacters present
if [[ "$has_metachar" == false ]] && eval "args=($input)" 2>/dev/null; then
# Check if args has elements after eval
args_count=0
local _tmp arg
for _tmp in ${args+"${args[@]}"}; do args_count=$((args_count + 1)); done
if [[ "$args_count" -gt 0 ]]; then
# Successfully parsed - remove sentinel if present
local last_idx=$((args_count - 1))
if [[ -z "${args[$last_idx]}" ]]; then
unset 'args[$last_idx]'
fi
# Print args and return early
for arg in "${args[@]+"${args[@]}"}"; do
encoded_arg="$(bashunit::helper::encode_base64 "${arg}")"
printf '%s\n' "$encoded_arg"
done
return
fi
fi
# Fallback: parse args from the input string into an array, respecting quotes and escapes
local i
for ((i = 0; i < ${#input}; i++)); do
local char="${input:$i:1}"
if [ "$escaped" = true ]; then
case "$char" in
t) current_arg="$current_arg"$'\t' ;;
n) current_arg="$current_arg"$'\n' ;;
*) current_arg="$current_arg$char" ;;
esac
escaped=false
elif [ "$char" = "\\" ]; then
escaped=true
elif [ "$in_quotes" = false ]; then
case "$char" in
"$")
# Handle $'...' syntax
if [[ "${input:$i:2}" == "$'" ]]; then
in_quotes=true
had_quotes=true
quote_char="'"
# Skip the $
i=$((i + 1))
else
current_arg="$current_arg$char"
fi
;;
"'" | '"')
in_quotes=true
had_quotes=true
quote_char="$char"
;;
" " | $'\t')
# Add if non-empty OR if was quoted (to preserve empty quoted strings like '')
if [[ -n "$current_arg" || "$had_quotes" == true ]]; then
args[args_count]="$current_arg"
args_count=$((args_count + 1))
fi
current_arg=""
had_quotes=false
;;
*)
current_arg="$current_arg$char"
;;
esac
elif [ "$char" = "$quote_char" ]; then
in_quotes=false
quote_char=""
else
current_arg="$current_arg$char"
fi
done
args[args_count]="$current_arg"
args_count=$((args_count + 1))
# Remove all trailing empty strings
while [[ "$args_count" -gt 0 ]]; do
local last_idx=$((args_count - 1))
if [[ -z "${args[$last_idx]}" ]]; then
unset 'args[$last_idx]'
args_count=$((args_count - 1))
else
break
fi
done
# Print one arg per line to stdout, base64-encoded to preserve newlines in the data
local arg
for arg in ${args+"${args[@]}"}; do
encoded_arg="$(bashunit::helper::encode_base64 "${arg}")"
printf '%s\n' "$encoded_arg"
done
}
function bashunit::runner::call_test_functions() {
local script="$1"
local filter="$2"
local tag_filter="${3:-}"
local exclude_tag_filter="${4:-}"
local IFS=$' \t\n'
local prefix="test"
# Use cached function names for better performance
local filtered_functions
filtered_functions=$(bashunit::helper::get_functions_to_run \
"$prefix" "$filter" "$_BASHUNIT_CACHED_ALL_FUNCTIONS")
local -a functions_to_run=()
local functions_to_run_count=0
local _fn
while IFS= read -r _fn; do
[[ -z "$_fn" ]] && continue
functions_to_run[functions_to_run_count]="$_fn"
functions_to_run_count=$((functions_to_run_count + 1))
done < <(bashunit::runner::functions_for_script "$script" "$filtered_functions")
# Apply tag filtering if --tag or --exclude-tag was specified
if [ -n "$tag_filter" ] || [ -n "$exclude_tag_filter" ]; then
local -a tag_filtered=()
local tag_filtered_count=0
local _tf_fn
for _tf_fn in "${functions_to_run[@]+"${functions_to_run[@]}"}"; do
local fn_tags
fn_tags=$(bashunit::helper::get_tags_for_function "$_tf_fn" "$script")
if bashunit::helper::function_matches_tags "$fn_tags" "$tag_filter" "$exclude_tag_filter"; then
tag_filtered[tag_filtered_count]="$_tf_fn"
tag_filtered_count=$((tag_filtered_count + 1))
fi
done
functions_to_run=("${tag_filtered[@]+"${tag_filtered[@]}"}")
functions_to_run_count=$tag_filtered_count
fi
if [[ "$functions_to_run_count" -le 0 ]]; then
return
fi
bashunit::helper::check_duplicate_functions "$script" || true
# Check if test file opts out of test-level parallelism
local allow_test_parallel=true
if grep -q "^# bashunit: no-parallel-tests" "$script" 2>/dev/null; then
allow_test_parallel=false
fi
local -a provider_data=()
local provider_data_count=0
local -a parsed_data=()
local parsed_data_count=0
for fn_name in "${functions_to_run[@]+"${functions_to_run[@]}"}"; do
if bashunit::parallel::is_enabled && bashunit::parallel::must_stop_on_failure; then
break
fi
provider_data=()
provider_data_count=0
local line
while IFS=" " read -r line; do
[[ -z "$line" ]] && continue
provider_data[provider_data_count]="$line"
provider_data_count=$((provider_data_count + 1))
done <<<"$(bashunit::helper::get_provider_data "$fn_name" "$script")"
# No data provider found
if [ "$provider_data_count" -eq 0 ]; then
if bashunit::parallel::is_enabled && [ "$allow_test_parallel" = true ]; then
bashunit::runner::run_test "$script" "$fn_name" &
else
bashunit::runner::run_test "$script" "$fn_name"
fi
unset -v fn_name
continue
fi
# Execute the test function for each line of data
local data
for data in "${provider_data[@]+"${provider_data[@]}"}"; do
parsed_data=()
parsed_data_count=0
local line
while IFS= read -r line; do
[ -z "$line" ] && continue
parsed_data[parsed_data_count]="$(bashunit::helper::decode_base64 "${line}")"
parsed_data_count=$((parsed_data_count + 1))
done <<<"$(bashunit::runner::parse_data_provider_args "$data")"
if bashunit::parallel::is_enabled && [ "$allow_test_parallel" = true ]; then
bashunit::runner::run_test "$script" "$fn_name" ${parsed_data+"${parsed_data[@]}"} &
else
bashunit::runner::run_test "$script" "$fn_name" ${parsed_data+"${parsed_data[@]}"}
fi
done
unset -v fn_name
done
# Wait for all parallel tests within this file to complete
if bashunit::parallel::is_enabled && [ "$allow_test_parallel" = true ]; then
wait
fi
}
function bashunit::runner::call_bench_functions() {
local script="$1"
local filter="$2"
local IFS=$' \t\n'
local prefix="bench"
# Use cached function names for better performance
local filtered_functions
filtered_functions=$(bashunit::helper::get_functions_to_run \
"$prefix" "$filter" "$_BASHUNIT_CACHED_ALL_FUNCTIONS")
local -a functions_to_run=()
local functions_to_run_count=0
local _fn
while IFS= read -r _fn; do
[[ -z "$_fn" ]] && continue
functions_to_run[functions_to_run_count]="$_fn"
functions_to_run_count=$((functions_to_run_count + 1))
done < <(bashunit::runner::functions_for_script "$script" "$filtered_functions")
if [[ "$functions_to_run_count" -le 0 ]]; then
return
fi
if bashunit::env::is_bench_mode_enabled; then
bashunit::runner::render_running_file_header "$script"
fi
local fn_name
for fn_name in "${functions_to_run[@]+"${functions_to_run[@]}"}"; do
read -r revs its max_ms <<<"$(bashunit::benchmark::parse_annotations "$fn_name" "$script")"
bashunit::benchmark::run_function "$fn_name" "$revs" "$its" "$max_ms"
unset -v fn_name
done
if ! bashunit::env::is_simple_output_enabled; then
echo ""
fi
}
function bashunit::runner::render_running_file_header() {
local script="$1"
local force="${2:-false}"
bashunit::internal_log "Running file" "$script"
if [[ "$force" != true ]] && bashunit::parallel::is_enabled; then
return
fi
# Suppress file headers in failures-only mode
if bashunit::env::is_failures_only_enabled; then
return
fi
# Suppress file headers in no-progress mode
if bashunit::env::is_no_progress_enabled; then
return
fi
if ! bashunit::env::is_simple_output_enabled; then
if bashunit::env::is_verbose_enabled; then
printf "\n${_BASHUNIT_COLOR_BOLD}%s${_BASHUNIT_COLOR_DEFAULT}\n" "Running $script"
else
printf "${_BASHUNIT_COLOR_BOLD}%s${_BASHUNIT_COLOR_DEFAULT}\n" "Running $script"
fi
elif bashunit::env::is_verbose_enabled; then
printf "\n\n${_BASHUNIT_COLOR_BOLD}%s${_BASHUNIT_COLOR_DEFAULT}" "Running $script"
fi
}
function bashunit::runner::run_test() {
local start_time
start_time=$(bashunit::clock::now)
local test_file="$1"
shift
local fn_name="$1"
shift
bashunit::internal_log "Running test" "$fn_name" "$*"
# Export a unique test identifier so that test doubles can
# create temporary files scoped per test run. This prevents
# race conditions when running tests in parallel.
export BASHUNIT_CURRENT_TEST_ID="$(bashunit::helper::generate_id "$fn_name")"
# Export current test file and function for coverage tracking (only when coverage enabled)
if bashunit::env::is_coverage_enabled; then
export _BASHUNIT_COVERAGE_CURRENT_TEST_FILE="$test_file"
export _BASHUNIT_COVERAGE_CURRENT_TEST_FN="$fn_name"
fi
bashunit::state::reset_test_title
local interpolated_fn_name="$(bashunit::helper::interpolate_function_name "$fn_name" "$@")"
if [[ "$interpolated_fn_name" != "$fn_name" ]]; then
bashunit::state::set_current_test_interpolated_function_name "$interpolated_fn_name"
else
bashunit::state::reset_current_test_interpolated_function_name
fi
local current_assertions_failed="$(bashunit::state::get_assertions_failed)"
local current_assertions_snapshot="$(bashunit::state::get_assertions_snapshot)"
local current_assertions_incomplete="$(bashunit::state::get_assertions_incomplete)"
local current_assertions_skipped="$(bashunit::state::get_assertions_skipped)"
# (FD = File Descriptor)
# Duplicate the current std-output (FD 1) and assigns it to FD 3.
# This means that FD 3 now points to wherever the std-output was pointing.
exec 3>&1
local test_execution_result=$(
# shellcheck disable=SC2064
trap "exit_code=\$?; bashunit::runner::cleanup_on_exit \"$test_file\" \"\$exit_code\"" EXIT
bashunit::state::initialize_assertions_count
# Source login shell profiles if enabled
if bashunit::env::is_login_shell_enabled; then
# shellcheck disable=SC1091
[[ -f /etc/profile ]] && source /etc/profile 2>/dev/null || true
# shellcheck disable=SC1090
[[ -f ~/.bash_profile ]] && source ~/.bash_profile 2>/dev/null || true
# shellcheck disable=SC1090
[[ -f ~/.bash_login ]] && source ~/.bash_login 2>/dev/null || true
# shellcheck disable=SC1090
[[ -f ~/.profile ]] && source ~/.profile 2>/dev/null || true
fi
# Run set_up and capture exit code without || to preserve errexit behavior
local setup_exit_code=0
bashunit::runner::run_set_up "$test_file"
setup_exit_code=$?
if [[ $setup_exit_code -ne 0 ]]; then
exit $setup_exit_code
fi
# Apply shell mode setting for test execution
if bashunit::env::is_strict_mode_enabled; then
set -euo pipefail
else
set +euo pipefail
fi
# Enable coverage tracking if enabled
if bashunit::env::is_coverage_enabled; then
bashunit::coverage::enable_trap
fi
# 2>&1: Redirects the std-error (FD 2) to the std-output (FD 1).
# points to the original std-output.
"$fn_name" "$@" 2>&1
)
# Closes FD 3, which was used temporarily to hold the original stdout.
exec 3>&-
local end_time=$(bashunit::clock::now)
local duration_ns=$((end_time - start_time))
local duration=$((duration_ns / 1000000))
if bashunit::env::is_verbose_enabled; then
if bashunit::env::is_simple_output_enabled; then
echo ""
fi
printf '%*s\n' "$TERMINAL_WIDTH" '' | tr ' ' '='
printf "%s\n" "File: $test_file"
printf "%s\n" "Function: $fn_name"
printf "%s\n" "Duration: $duration ms"
local raw_text=${test_execution_result%%##ASSERTIONS_*}
[[ -n $raw_text ]] && printf "%s" "Raw text: ${test_execution_result%%##ASSERTIONS_*}"
printf "%s\n" "##ASSERTIONS_${test_execution_result#*##ASSERTIONS_}"
printf '%*s\n' "$TERMINAL_WIDTH" '' | tr ' ' '-'
fi
local subshell_output=$(bashunit::runner::decode_subshell_output "$test_execution_result")
if [[ -n "$subshell_output" ]]; then
# Formatted as "[type]line" @see `bashunit::state::print_line()`
local type="${subshell_output%%]*}" # Remove everything after "]"
type="${type#[}" # Remove the leading "["
local line="${subshell_output#*]}" # Remove everything before and including "]"
# Replace [type] with a newline to split the messages
line=${line//\[failed\]/$'\n'} # Replace [failed] with newline
line=${line//\[skipped\]/$'\n'} # Replace [skipped] with newline
line=${line//\[incomplete\]/$'\n'} # Replace [incomplete] with newline
if ! bashunit::env::is_failures_only_enabled; then
bashunit::state::print_line "$type" "$line"
fi
subshell_output=$line
fi
local runtime_output="${test_execution_result%%##ASSERTIONS_*}"
local runtime_error=""
local error=""
for error in "command not found" "unbound variable" "permission denied" \
"no such file or directory" "syntax error" "bad substitution" \
"division by 0" "cannot allocate memory" "bad file descriptor" \
"segmentation fault" "illegal option" "argument list too long" \
"readonly variable" "missing keyword" "killed" \
"cannot execute binary file" "invalid arithmetic operator"; do
if [[ "$runtime_output" == *"$error"* ]]; then
runtime_error="${runtime_output#*: }" # Remove everything up to and including ": "
runtime_error=${runtime_error//$'\n'/} # Remove all newlines using parameter expansion
break
fi
done
bashunit::runner::parse_result "$fn_name" "$test_execution_result" "$@"
local total_assertions="$(bashunit::state::calculate_total_assertions "$test_execution_result")"
local test_exit_code="$(bashunit::state::get_test_exit_code)"
local encoded_test_title
encoded_test_title="${test_execution_result##*##TEST_TITLE=}"
encoded_test_title="${encoded_test_title%%##*}"
local test_title=""
[[ -n "$encoded_test_title" ]] && test_title="$(bashunit::helper::decode_base64 "$encoded_test_title")"
local encoded_hook_failure
encoded_hook_failure="${test_execution_result##*##TEST_HOOK_FAILURE=}"
encoded_hook_failure="${encoded_hook_failure%%##*}"
local hook_failure=""
if [[ "$encoded_hook_failure" != "$test_execution_result" ]]; then
hook_failure="$encoded_hook_failure"
fi
local encoded_hook_message
encoded_hook_message="${test_execution_result##*##TEST_HOOK_MESSAGE=}"
encoded_hook_message="${encoded_hook_message%%##*}"
local hook_message=""
if [[ -n "$encoded_hook_message" ]]; then
hook_message="$(bashunit::helper::decode_base64 "$encoded_hook_message")"
fi
bashunit::set_test_title "$test_title"
local label
label="$(bashunit::helper::normalize_test_function_name "$fn_name" "$interpolated_fn_name")"
bashunit::state::reset_test_title
bashunit::state::reset_current_test_interpolated_function_name
local failure_label="$label"
local failure_function="$fn_name"
if [[ -n "$hook_failure" ]]; then
failure_label="$(bashunit::helper::normalize_test_function_name "$hook_failure")"
failure_function="$hook_failure"
fi
if [[ -n $runtime_error || $test_exit_code -ne 0 ]]; then
bashunit::state::add_tests_failed
local error_message="$runtime_error"
if [[ -n "$hook_failure" && -n "$hook_message" ]]; then
error_message="$hook_message"
elif [[ -z "$error_message" && -n "$hook_message" ]]; then
error_message="$hook_message"
fi
bashunit::console_results::print_error_test "$failure_function" "$error_message" "$runtime_output"
bashunit::reports::add_test_failed "$test_file" "$failure_label" "$duration" "$total_assertions"
bashunit::runner::write_failure_result_output "$test_file" "$failure_function" "$error_message" "$runtime_output"
bashunit::internal_log "Test error" "$failure_label" "$error_message"
return
fi
if [[ "$current_assertions_failed" != "$(bashunit::state::get_assertions_failed)" ]]; then
bashunit::state::add_tests_failed
bashunit::reports::add_test_failed "$test_file" "$label" "$duration" "$total_assertions"
bashunit::runner::write_failure_result_output "$test_file" "$fn_name" "$subshell_output"
bashunit::internal_log "Test failed" "$label"
if bashunit::env::is_stop_on_failure_enabled; then
if bashunit::parallel::is_enabled; then
bashunit::parallel::mark_stop_on_failure
else
exit "$EXIT_CODE_STOP_ON_FAILURE"
fi
fi
return
fi
if [[ "$current_assertions_snapshot" != "$(bashunit::state::get_assertions_snapshot)" ]]; then
bashunit::state::add_tests_snapshot
# In failures-only mode, suppress snapshot test output
if ! bashunit::env::is_failures_only_enabled; then
bashunit::console_results::print_snapshot_test "$label"
fi
bashunit::reports::add_test_snapshot "$test_file" "$label" "$duration" "$total_assertions"
bashunit::internal_log "Test snapshot" "$label"
return
fi
if [[ "$current_assertions_incomplete" != "$(bashunit::state::get_assertions_incomplete)" ]]; then
bashunit::state::add_tests_incomplete
bashunit::reports::add_test_incomplete "$test_file" "$label" "$duration" "$total_assertions"
bashunit::runner::write_incomplete_result_output "$test_file" "$fn_name" "$subshell_output"
bashunit::internal_log "Test incomplete" "$label"
return
fi
if [[ "$current_assertions_skipped" != "$(bashunit::state::get_assertions_skipped)" ]]; then
bashunit::state::add_tests_skipped
bashunit::reports::add_test_skipped "$test_file" "$label" "$duration" "$total_assertions"
bashunit::runner::write_skipped_result_output "$test_file" "$fn_name" "$subshell_output"
bashunit::internal_log "Test skipped" "$label"
return
fi
# In failures-only mode, suppress successful test output
if ! bashunit::env::is_failures_only_enabled; then
if [[ "$fn_name" == "$interpolated_fn_name" ]]; then
bashunit::console_results::print_successful_test "${label}" "$duration" "$@"
else
bashunit::console_results::print_successful_test "${label}" "$duration"
fi
fi
bashunit::state::add_tests_passed
bashunit::reports::add_test_passed "$test_file" "$label" "$duration" "$total_assertions"
bashunit::internal_log "Test passed" "$label"
}
function bashunit::runner::cleanup_on_exit() {
local test_file="$1"
local exit_code="$2"
# Disable coverage trap before cleanup to avoid interference
if bashunit::env::is_coverage_enabled; then
bashunit::coverage::disable_trap
fi
set +e
# Don't use || here - it disables ERR trap in the entire call chain
bashunit::runner::run_tear_down "$test_file"
local teardown_status=$?
bashunit::runner::clear_mocks
bashunit::cleanup_testcase_temp_files
if [[ $teardown_status -ne 0 ]]; then
bashunit::state::set_test_exit_code "$teardown_status"
else
bashunit::state::set_test_exit_code "$exit_code"
fi
bashunit::state::export_subshell_context
}
function bashunit::runner::decode_subshell_output() {
local test_execution_result="$1"
local test_output_base64="${test_execution_result##*##TEST_OUTPUT=}"
test_output_base64="${test_output_base64%%##*}"
bashunit::helper::decode_base64 "$test_output_base64"
}
function bashunit::runner::parse_result() {
local fn_name=$1
shift
local execution_result=$1
shift
local IFS=$' \t\n'
local -a args
args=("$@")
if bashunit::parallel::is_enabled; then
bashunit::runner::parse_result_parallel "$fn_name" "$execution_result" ${args+"${args[@]}"}
else
bashunit::runner::parse_result_sync "$fn_name" "$execution_result"
fi
}
function bashunit::runner::parse_result_parallel() {
local fn_name=$1
shift
local execution_result=$1
shift
local IFS=$' \t\n'
local -a args
args=("$@")
local test_suite_dir="${TEMP_DIR_PARALLEL_TEST_SUITE}/$(basename "$test_file" .sh)"
mkdir -p "$test_suite_dir"
local sanitized_args
sanitized_args=$(echo "${args[*]+"${args[*]}"}" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-|-$//')
local template
if [[ -z "$sanitized_args" ]]; then
template="${fn_name}.XXXXXX"
else
template="${fn_name}-${sanitized_args}.XXXXXX"
fi
local unique_test_result_file
if unique_test_result_file=$(mktemp -p "$test_suite_dir" "$template" 2>/dev/null); then
true
else
unique_test_result_file=$(mktemp "$test_suite_dir/$template")
fi
mv "$unique_test_result_file" "${unique_test_result_file}.result"
unique_test_result_file="${unique_test_result_file}.result"
bashunit::internal_log "[PARA]" "fn_name:$fn_name" "execution_result:$execution_result"
bashunit::runner::parse_result_sync "$fn_name" "$execution_result"
echo "$execution_result" >"$unique_test_result_file"
}
# shellcheck disable=SC2295
function bashunit::runner::parse_result_sync() {
local fn_name=$1
local execution_result=$2
local result_line
result_line="${execution_result##*$'\n'}"
local assertions_failed=0
local assertions_passed=0
local assertions_skipped=0
local assertions_incomplete=0
local assertions_snapshot=0
local test_exit_code=0
# Use pre-compiled regex constant
if [[ "$result_line" =~ $_BASHUNIT_RUNNER_PARSE_RESULT_REGEX ]]; then
assertions_failed="${BASH_REMATCH[1]}"
assertions_passed="${BASH_REMATCH[2]}"
assertions_skipped="${BASH_REMATCH[3]}"
assertions_incomplete="${BASH_REMATCH[4]}"
assertions_snapshot="${BASH_REMATCH[5]}"
test_exit_code="${BASH_REMATCH[6]}"
fi
bashunit::internal_log "[SYNC]" "fn_name:$fn_name" "execution_result:$execution_result"
_BASHUNIT_ASSERTIONS_PASSED=$((_BASHUNIT_ASSERTIONS_PASSED + assertions_passed))
_BASHUNIT_ASSERTIONS_FAILED=$((_BASHUNIT_ASSERTIONS_FAILED + assertions_failed))
_BASHUNIT_ASSERTIONS_SKIPPED=$((_BASHUNIT_ASSERTIONS_SKIPPED + assertions_skipped))
_BASHUNIT_ASSERTIONS_INCOMPLETE=$((_BASHUNIT_ASSERTIONS_INCOMPLETE + assertions_incomplete))
_BASHUNIT_ASSERTIONS_SNAPSHOT=$((_BASHUNIT_ASSERTIONS_SNAPSHOT + assertions_snapshot))
_BASHUNIT_TEST_EXIT_CODE=$((_BASHUNIT_TEST_EXIT_CODE + test_exit_code))
bashunit::internal_log "result_summary" \
"failed:$assertions_failed" \
"passed:$assertions_passed" \
"skipped:$assertions_skipped" \
"incomplete:$assertions_incomplete" \
"snapshot:$assertions_snapshot" \
"exit_code:$test_exit_code"
}
function bashunit::runner::write_failure_result_output() {
local test_file=$1
local fn_name=$2
local error_msg=$3
local raw_output="${4:-}"
local line_number
line_number=$(bashunit::helper::get_function_line_number "$fn_name")
local test_nr="*"
if ! bashunit::parallel::is_enabled; then
test_nr=$(bashunit::state::get_tests_failed)
fi
local output_section=""
if [[ -n "$raw_output" ]] && bashunit::env::is_show_output_on_failure_enabled; then
output_section="\n Output:\n$raw_output"
fi
echo -e "$test_nr) $test_file:$line_number\n$error_msg$output_section" >>"$FAILURES_OUTPUT_PATH"
}
function bashunit::runner::write_skipped_result_output() {
local test_file=$1
local fn_name=$2
local output_msg=$3
local line_number
line_number=$(bashunit::helper::get_function_line_number "$fn_name")
local test_nr="*"
if ! bashunit::parallel::is_enabled; then
test_nr=$(bashunit::state::get_tests_skipped)
fi
echo -e "$test_nr) $test_file:$line_number\n$output_msg" >>"$SKIPPED_OUTPUT_PATH"
}
function bashunit::runner::write_incomplete_result_output() {
local test_file=$1
local fn_name=$2
local output_msg=$3
local line_number
line_number=$(bashunit::helper::get_function_line_number "$fn_name")
local test_nr="*"
if ! bashunit::parallel::is_enabled; then
test_nr=$(bashunit::state::get_tests_incomplete)
fi
echo -e "$test_nr) $test_file:$line_number\n$output_msg" >>"$INCOMPLETE_OUTPUT_PATH"
}
function bashunit::runner::record_file_hook_failure() {
local hook_name="$1"
local test_file="$2"
local hook_output="$3"
local status="$4"
local render_header="${5:-false}"
if [[ "$render_header" == true ]]; then
bashunit::runner::render_running_file_header "$test_file" true
fi
if [[ -z "$hook_output" ]]; then
hook_output="Hook '$hook_name' failed with exit code $status"
fi
bashunit::state::add_tests_failed
bashunit::console_results::print_error_test "$hook_name" "$hook_output"
bashunit::reports::add_test_failed "$test_file" "$(bashunit::helper::normalize_test_function_name "$hook_name")" 0 0
bashunit::runner::write_failure_result_output "$test_file" "$hook_name" "$hook_output"
return "$status"
}
function bashunit::runner::execute_file_hook() {
local hook_name="$1"
local test_file="$2"
local render_header="${3:-false}"
declare -F "$hook_name" >/dev/null 2>&1 || return 0
local hook_output=""
local status=0
local hook_output_file
hook_output_file=$(bashunit::temp_file "${hook_name}_output")
# Enable errexit and errtrace to catch any failing command in the hook.
# The ERR trap saves the exit status to a global variable (since return value
# from trap doesn't propagate properly), disables errexit (to prevent caller
# from exiting) and returns from the hook function, preventing subsequent
# commands from executing.
# Variables set before the failure are preserved since we don't use a subshell.
_BASHUNIT_HOOK_ERR_STATUS=0
set -eE
trap '_BASHUNIT_HOOK_ERR_STATUS=$?; set +eE; trap - ERR; return $_BASHUNIT_HOOK_ERR_STATUS' ERR
{
"$hook_name"
} >"$hook_output_file" 2>&1
# Capture exit status from global variable and clean up
status=$_BASHUNIT_HOOK_ERR_STATUS
trap - ERR
set +eE