Bash · 1562 bytes Raw Blame History
1 #!/bin/sh
2 TEST_PREFIX="[source]"
3 . "$(cd "$(dirname "$0")/.." && pwd)/test_harness.sh"
4
5 # Create test files
6 printf 'SOURCED_VAR=hello\n' > "$TEST_TMPDIR/source_var.sh"
7 printf 'greet() { echo "hi $1"; }\n' > "$TEST_TMPDIR/source_func.sh"
8 printf 'echo "arg1=$1 arg2=$2"\n' > "$TEST_TMPDIR/source_args.sh"
9 printf 'X=10\nY=20\necho $((X + Y))\n' > "$TEST_TMPDIR/source_multi.sh"
10 printf 'return 42\n' > "$TEST_TMPDIR/source_return.sh"
11
12 section "1. source basic"
13 compare_output "source file sets variable" "source $TEST_TMPDIR/source_var.sh; echo \$SOURCED_VAR"
14 compare_output "source file defines function" "source $TEST_TMPDIR/source_func.sh; greet world"
15 compare_exit "source nonexistent file fails" "source $TEST_TMPDIR/no_such_file.sh 2>/dev/null"
16 compare_output "source with arguments" "source $TEST_TMPDIR/source_args.sh foo bar"
17 compare_output "source multiple assignments" "source $TEST_TMPDIR/source_multi.sh"
18
19 section "2. dot command"
20 compare_output "dot command works like source" ". $TEST_TMPDIR/source_var.sh; echo \$SOURCED_VAR"
21 compare_output "dot with function def" ". $TEST_TMPDIR/source_func.sh; greet user"
22 compare_exit "dot nonexistent file fails" ". $TEST_TMPDIR/no_such_file.sh 2>/dev/null"
23
24 section "3. source edge cases"
25 compare_exit "source file with return" "source $TEST_TMPDIR/source_return.sh"
26 compare_output "source preserves env" "A=before; printf 'A=after\n' > $TEST_TMPDIR/s.sh; source $TEST_TMPDIR/s.sh; echo \$A"
27 compare_output "source in function" "f() { source $TEST_TMPDIR/source_var.sh; echo \$SOURCED_VAR; }; f"
28
29 print_summary