forked from TypedDevs/bashunit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.sh
More file actions
executable file
·638 lines (551 loc) · 17.2 KB
/
helpers.sh
File metadata and controls
executable file
·638 lines (551 loc) · 17.2 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
#!/usr/bin/env bash
declare -r BASHUNIT_GIT_REPO="https://github.com/TypedDevs/bashunit"
#
# Walks up the call stack to find the first function that looks like a test function.
# A test function is one that starts with "test_" or "test" (camelCase).
# If no test function is found, falls back to the caller of the assertion function.
#
# @param $1 number Optional fallback depth (default: 2, i.e., the caller of the assertion)
#
# @return string The test function name, or fallback function name
#
function bashunit::helper::find_test_function_name() {
local fallback_depth="${1:-2}"
local i
for ((i = 0; i < ${#FUNCNAME[@]}; i++)); do
local fn="${FUNCNAME[$i]}"
# Check if function starts with "test_" or "test" followed by uppercase
local _re='^test[A-Z]'
local _is_test=false
case "$fn" in test_*) _is_test=true ;; esac
if [ "$_is_test" = true ] || [ "$(echo "$fn" | "$GREP" -cE "$_re" || true)" -gt 0 ]; then
echo "$fn"
return
fi
done
# No test function found, use fallback (caller of the assertion)
# FUNCNAME[0] = bashunit::helper::find_test_function_name
# FUNCNAME[1] = the assertion function (e.g., assert_same)
# FUNCNAME[2] = caller of the assertion
echo "${FUNCNAME[$fallback_depth]:-}"
}
#
# @param $1 string Eg: "test_some_logic_camelCase"
#
# @return string Eg: "Some logic camelCase"
#
function bashunit::helper::normalize_test_function_name() {
local original_fn_name="${1-}"
local interpolated_fn_name="${2-}"
local custom_title
custom_title="$(bashunit::state::get_test_title)"
if [ -n "$custom_title" ]; then
echo "$custom_title"
return
fi
if [ -z "${interpolated_fn_name-}" ]; then
case "${original_fn_name}" in
*"::"*)
local state_interpolated_fn_name
state_interpolated_fn_name="$(bashunit::state::get_current_test_interpolated_function_name)"
if [ -n "$state_interpolated_fn_name" ]; then
interpolated_fn_name="$state_interpolated_fn_name"
fi
;;
esac
fi
if [ -n "${interpolated_fn_name-}" ]; then
original_fn_name="$interpolated_fn_name"
fi
local result
# Remove the first "test_" prefix, if present
result="${original_fn_name#test_}"
# If no "test_" was removed (e.g., "testFoo"), remove the "test" prefix
if [ "$result" = "$original_fn_name" ]; then
result="${original_fn_name#test}"
fi
# Replace underscores with spaces
result="${result//_/ }"
# Capitalize the first letter (bash 3.0 compatible, no subprocess)
local first_char="${result:0:1}"
case "$first_char" in
a) first_char='A' ;; b) first_char='B' ;; c) first_char='C' ;; d) first_char='D' ;;
e) first_char='E' ;; f) first_char='F' ;; g) first_char='G' ;; h) first_char='H' ;;
i) first_char='I' ;; j) first_char='J' ;; k) first_char='K' ;; l) first_char='L' ;;
m) first_char='M' ;; n) first_char='N' ;; o) first_char='O' ;; p) first_char='P' ;;
q) first_char='Q' ;; r) first_char='R' ;; s) first_char='S' ;; t) first_char='T' ;;
u) first_char='U' ;; v) first_char='V' ;; w) first_char='W' ;; x) first_char='X' ;;
y) first_char='Y' ;; z) first_char='Z' ;;
esac
result="${first_char}${result:1}"
echo "$result"
}
function bashunit::helper::escape_single_quotes() {
local value="$1"
# shellcheck disable=SC1003
echo "${value//\'/'\'\\''\'}"
}
function bashunit::helper::interpolate_function_name() {
local function_name="$1"
shift
local -a args
local args_count=$#
args=("$@")
local result="$function_name"
local i
for ((i = 0; i < args_count; i++)); do
local placeholder="::$((i + 1))::"
# shellcheck disable=SC2155
local value="$(bashunit::helper::escape_single_quotes "${args[$i]}")"
value="'$value'"
result="${result//${placeholder}/${value}}"
done
echo "$result"
}
function bashunit::helper::encode_base64() {
local value="$1"
# Handle empty string specially - base64 of "" is "", which gets lost in line parsing
if [ -z "$value" ]; then
printf '%s' "_BASHUNIT_EMPTY_"
return
fi
if [ "$_BASHUNIT_BASE64_WRAP_FLAG" = true ]; then
printf '%s' "$value" | base64 -w 0
elif command -v base64 >/dev/null; then
printf '%s' "$value" | base64 | tr -d '\n'
else
printf '%s' "$value" | openssl enc -base64 -A
fi
}
function bashunit::helper::decode_base64() {
local value="$1"
# Handle empty string marker
if [ "$value" = "_BASHUNIT_EMPTY_" ]; then
printf ''
return
fi
if command -v base64 >/dev/null; then
printf '%s' "$value" | base64 -d
else
printf '%s' "$value" | openssl enc -d -base64
fi
}
function bashunit::helper::check_duplicate_functions() {
local script="$1"
# Handle directory changes in set_up_before_script (issue #529)
if [ ! -f "$script" ] && [ -n "${BASHUNIT_WORKING_DIR:-}" ]; then
script="$BASHUNIT_WORKING_DIR/$script"
fi
local filtered_lines
filtered_lines=$(grep -E '^[[:space:]]*(function[[:space:]]+)?test[a-zA-Z_][a-zA-Z0-9_]*\s*\(\)\s*\{' "$script")
local function_names
function_names=$(echo "$filtered_lines" | awk '{
for (i=1; i<=NF; i++) {
if ($i ~ /^test[a-zA-Z_][a-zA-Z0-9_]*\(\)$/) {
gsub(/\(\)/, "", $i)
print $i
break
}
}
}')
local duplicates
duplicates=$(echo "$function_names" | sort | uniq -d)
if [ -n "$duplicates" ]; then
bashunit::state::set_duplicated_functions_merged "$script" "$duplicates"
return 1
fi
return 0
}
#
# @param $1 string Eg: "prefix"
# @param $2 string Eg: "filter"
# @param $3 array Eg: "[fn1, fn2, prefix_filter_fn3, fn4, ...]"
#
# @return array Eg: "[prefix_filter_fn3, ...]" The filtered functions with prefix
#
function bashunit::helper::get_functions_to_run() {
local prefix=$1
local filter=${2/test_/}
local function_names=$3
local filtered_functions=""
local fn
for fn in $function_names; do
local _fn_match=false
case "$fn" in ${prefix}_*${filter}*) _fn_match=true ;; esac
if [ "$_fn_match" = true ]; then
local _dup=false
case "$filtered_functions" in *" $fn"*) _dup=true ;; esac
if [ "$_dup" = true ]; then
return 1
fi
filtered_functions="$filtered_functions $fn"
fi
done
echo "${filtered_functions# }"
}
#
# @param $1 string Eg: "do_something"
#
function bashunit::helper::execute_function_if_exists() {
local fn_name="$1"
if declare -F "$fn_name" >/dev/null 2>&1; then
"$fn_name"
return $?
fi
return 0
}
#
# @param $1 string Eg: "do_something"
#
function bashunit::helper::unset_if_exists() {
unset "$1" 2>/dev/null
}
function bashunit::helper::find_files_recursive() {
## Remove trailing slash using parameter expansion
local path="${1%%/}"
local pattern="${2:-*[tT]est.sh}"
local alt_pattern=""
local _re='\[tT\]est\.sh$'
local _pattern_match=false
case "$pattern" in *test.sh) _pattern_match=true ;; esac
if [ "$_pattern_match" = true ] || [ "$(echo "$pattern" | "$GREP" -cE "$_re" || true)" -gt 0 ]; then
alt_pattern="${pattern%.sh}.bash"
fi
local _has_glob=false
case "$path" in *"*"*) _has_glob=true ;; esac
if [ "$_has_glob" = true ]; then
if [ -n "$alt_pattern" ]; then
eval "find $path -type f \( -name \"$pattern\" -o -name \"$alt_pattern\" \)" | sort -u
else
eval "find $path -type f -name \"$pattern\"" | sort -u
fi
elif [ -d "$path" ]; then
if [ -n "$alt_pattern" ]; then
find "$path" -type f \( -name "$pattern" -o -name "$alt_pattern" \) | sort -u
else
find "$path" -type f -name "$pattern" | sort -u
fi
else
echo "$path"
fi
}
function bashunit::helper::normalize_variable_name() {
local input_string="$1"
local normalized_string
normalized_string="${input_string//[^a-zA-Z0-9_]/_}"
local _re='^[a-zA-Z_]'
if [ "$(builtin echo "$normalized_string" | "$GREP" -cE "$_re" || true)" -eq 0 ]; then
normalized_string="_$normalized_string"
fi
builtin echo "$normalized_string"
}
function bashunit::helper::get_provider_data() {
local function_name="$1"
local script="$2"
# Handle directory changes in set_up_before_script (issue #529)
# If relative path doesn't exist, try with BASHUNIT_WORKING_DIR
if [ ! -f "$script" ] && [ -n "${BASHUNIT_WORKING_DIR:-}" ]; then
script="$BASHUNIT_WORKING_DIR/$script"
fi
if [ ! -f "$script" ]; then
return
fi
local data_provider_function
data_provider_function=$(
# shellcheck disable=SC1087
grep -B 2 -E "(function[[:space:]]+)?$function_name[[:space:]]*\(\)" "$script" 2>/dev/null |
sed -nE 's/^[[:space:]]*# *@?data_provider[[:space:]]+//p'
)
if [ -n "$data_provider_function" ]; then
bashunit::helper::execute_function_if_exists "$data_provider_function"
fi
}
function bashunit::helper::trim() {
local input_string="$1"
local trimmed_string
trimmed_string="${input_string#"${input_string%%[![:space:]]*}"}"
trimmed_string="${trimmed_string%"${trimmed_string##*[![:space:]]}"}"
echo "$trimmed_string"
}
function bashunit::helper::get_latest_tag() {
if ! bashunit::dependencies::has_git; then
return 1
fi
git ls-remote --tags "$BASHUNIT_GIT_REPO" |
awk '{print $2}' |
sed 's|^refs/tags/||' |
grep -v '\^{}' |
sort -Vr |
head -n 1
}
function bashunit::helper::find_total_tests() {
local filter=${1:-}
shift || true
if [ $# -eq 0 ]; then
echo 0
return
fi
local total_count=0
local file
for file in "$@"; do
if [ ! -f "$file" ]; then
continue
fi
local file_count
file_count=$( (
# shellcheck source=/dev/null
source "$file"
local all_fn_names
all_fn_names=$(declare -F | awk '{print $3}')
local filtered_functions
filtered_functions=$(bashunit::helper::get_functions_to_run "test" "$filter" "$all_fn_names") || true
local count=0
local IFS=$' \t\n'
if [ -n "$filtered_functions" ]; then
local -a functions_to_run=()
# shellcheck disable=SC2206
functions_to_run=($filtered_functions)
# shellcheck disable=SC2034
local -a provider_data=()
local provider_data_count=0
local fn_name line
for fn_name in "${functions_to_run[@]+"${functions_to_run[@]}"}"; do
provider_data=()
provider_data_count=0
while IFS=" " read -r line; do
[ -z "$line" ] && continue
# shellcheck disable=SC2034
provider_data[provider_data_count]="$line"
provider_data_count=$((provider_data_count + 1))
done <<<"$(bashunit::helper::get_provider_data "$fn_name" "$file")"
if [ "$provider_data_count" -eq 0 ]; then
count=$((count + 1))
else
count=$((count + provider_data_count))
fi
done
fi
echo "$count"
))
total_count=$((total_count + file_count))
done
echo "$total_count"
}
function bashunit::helper::load_test_files() {
local filter="${1:-}"
shift || true
# Bash 3.0 compatible: use $# after shift to check for files
local has_files=$#
if [ "$has_files" -eq 0 ]; then
if [ -n "${BASHUNIT_DEFAULT_PATH:-}" ]; then
bashunit::helper::find_files_recursive "$BASHUNIT_DEFAULT_PATH"
fi
else
printf "%s\n" "$@"
fi
}
function bashunit::helper::load_bench_files() {
local filter="${1:-}"
shift || true
# Bash 3.0 compatible: use $# after shift to check for files
local has_files=$#
if [ "$has_files" -eq 0 ]; then
if [ -n "${BASHUNIT_DEFAULT_PATH:-}" ]; then
bashunit::helper::find_files_recursive "$BASHUNIT_DEFAULT_PATH" '*[bB]ench.sh'
fi
else
printf "%s\n" "$@"
fi
}
#
# @param $1 string function name
# @return number line number of the function in the source file
#
function bashunit::helper::get_function_line_number() {
local fn_name=$1
shopt -s extdebug
local line_number
line_number=$(declare -F "$fn_name" | awk '{print $2}')
shopt -u extdebug
echo "$line_number"
}
function bashunit::helper::generate_id() {
local basename="$1"
local sanitized_basename
sanitized_basename="$(bashunit::helper::normalize_variable_name "$basename")"
if bashunit::env::is_parallel_run_enabled; then
echo "${sanitized_basename}_$$_$(bashunit::random_str 6)"
else
echo "${sanitized_basename}_$$"
fi
}
#
# Parses a file path that may contain a filter suffix.
# Supports two syntaxes:
# - path::function_name (filter by function name)
# - path:line_number (filter by line number)
#
# @param $1 string Eg: "tests/test.sh::test_foo" or "tests/test.sh:123"
#
# @return string Two lines: first is file path, second is filter (or empty)
#
function bashunit::helper::parse_file_path_filter() {
local input="$1"
local file_path=""
local filter=""
# Check for :: syntax (function name filter)
case "$input" in *"::"*)
file_path="${input%%::*}"
filter="${input#*::}"
;;
*)
# Check for :number syntax (line number filter)
local _re='^(.+):([0-9]+)$'
if [ "$(echo "$input" | "$GREP" -cE "$_re" || true)" -gt 0 ]; then
file_path=$(echo "$input" | sed -nE 's/^(.+):([0-9]+)$/\1/p')
local line_number
line_number=$(echo "$input" | sed -nE 's/^(.+):([0-9]+)$/\2/p')
# Line number will be resolved to function name later
filter="__line__:${line_number}"
else
file_path="$input"
fi
;;
esac
echo "$file_path"
echo "$filter"
}
#
# Finds the test function that contains a given line number in a file.
#
# @param $1 string File path
# @param $2 number Line number
#
# @return string The function name, or empty if not found
#
function bashunit::helper::find_function_at_line() {
local file="$1"
local target_line="$2"
if [ ! -f "$file" ]; then
return 1
fi
# Find all test function definitions and their line numbers
local best_match=""
local best_line=0
local line_num content
while IFS=: read -r line_num content; do
# Extract function name from the line
local fn_name=""
local fn_pattern='^[[:space:]]*(function[[:space:]]+)?(test[a-zA-Z_][a-zA-Z0-9_]*)[[:space:]]*\(\).*'
fn_name=$(echo "$content" | sed -nE "s/$fn_pattern/\2/p")
if [ -n "$fn_name" ] && [ "$line_num" -le "$target_line" ] && [ "$line_num" -gt "$best_line" ]; then
best_match="$fn_name"
best_line="$line_num"
fi
done < <(grep -n -E '^[[:space:]]*(function[[:space:]]+)?test[a-zA-Z_][a-zA-Z0-9_]*[[:space:]]*\(\)' "$file")
echo "$best_match"
}
#
# Extracts @tag annotations for a specific function from a test file.
# Looks for comment lines `# @tag <name>` immediately above the function definition.
#
# @param $1 string Function name
# @param $2 string Script file path
#
# @return string Comma-separated list of tags, or empty if none
#
function bashunit::helper::get_tags_for_function() {
local function_name="$1"
local script="$2"
if [ ! -f "$script" ] && [ -n "${BASHUNIT_WORKING_DIR:-}" ]; then
script="$BASHUNIT_WORKING_DIR/$script"
fi
if [ ! -f "$script" ]; then
return
fi
# Find the line number of the function definition
local fn_line_num
fn_line_num=$(grep -n -E "(function[[:space:]]+)?${function_name}[[:space:]]*\(\)" "$script" 2>/dev/null | head -1)
if [ -z "$fn_line_num" ]; then
return
fi
fn_line_num="${fn_line_num%%:*}"
# Walk backwards from the line above the function, collecting @tag comments
local tags=""
local check_line=$((fn_line_num - 1))
while [ "$check_line" -ge 1 ]; do
local content
content=$(sed -n "${check_line}p" "$script")
local _re='^[[:space:]]*#[[:space:]]*@tag[[:space:]]'
if [ "$(echo "$content" | "$GREP" -cE "$_re" || true)" -gt 0 ]; then
local tag_name
tag_name=$(echo "$content" | sed -nE 's/^[[:space:]]*#[[:space:]]*@tag[[:space:]]+//p')
if [ -n "$tag_name" ]; then
if [ -z "$tags" ]; then
tags="$tag_name"
else
tags="$tags,$tag_name"
fi
fi
elif [ "$(echo "$content" | "$GREP" -cE '^[[:space:]]*#' || true)" -gt 0 ]; then
# Other comment line, keep walking
:
elif [ "$(echo "$content" | "$GREP" -cE '^[[:space:]]*$' || true)" -gt 0 ]; then
# Empty line, stop looking
break
else
# Non-comment, non-empty line, stop
break
fi
check_line=$((check_line - 1))
done
echo "$tags"
}
#
# Checks if a function's tags match the include/exclude filters.
# Include uses OR logic (any match passes).
# Exclude uses OR logic (any match fails).
# Exclude takes precedence over include.
#
# @param $1 string Comma-separated tags for the function
# @param $2 string Comma-separated include tags (empty = no filter)
# @param $3 string Comma-separated exclude tags (empty = no filter)
#
# @return 0 if function should run, 1 if it should be skipped
#
function bashunit::helper::function_matches_tags() {
local fn_tags="$1"
local include_tags="$2"
local exclude_tags="$3"
# Check exclude tags first (exclude wins over include)
if [ -n "$exclude_tags" ]; then
local IFS=','
local etag
for etag in $exclude_tags; do
local check_tag
for check_tag in $fn_tags; do
if [ "$check_tag" = "$etag" ]; then
return 1
fi
done
done
fi
# Check include tags (OR logic: any match passes)
if [ -n "$include_tags" ]; then
if [ -z "$fn_tags" ]; then
return 1
fi
local IFS=','
local itag
for itag in $include_tags; do
local check_tag
for check_tag in $fn_tags; do
if [ "$check_tag" = "$itag" ]; then
return 0
fi
done
done
return 1
fi
return 0
}