#!/bin/bash ################################################################################ # test-framework.sh # Simple Bash Unit Testing Framework for ROM Organizer # # Usage: # source test-framework.sh # test_function_name() { ... } # run_tests ################################################################################ # Test framework variables TESTS_RUN=0 TESTS_PASSED=0 TESTS_FAILED=0 CURRENT_TEST="" TEST_TEMP_DIR="" # Colors for output RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' # No Color # Initialize test framework init_test_framework() { TESTS_RUN=0 TESTS_PASSED=0 TESTS_FAILED=0 # Ensure EMUBASEDIR is set, fallback to default if not if [ -z "${EMUBASEDIR:-}" ]; then EMUBASEDIR='/data/emu' fi # Create temporary directory for tests within EMUBASEDIR for safety # This ensures all path validations work correctly while still providing isolation TEST_TEMP_DIR="${EMUBASEDIR}/temp/rom-groomer-tests-$(date +%s)-$$" mkdir -p "$TEST_TEMP_DIR" echo -e "${BLUE}Test temp directory: $TEST_TEMP_DIR${NC}" } # Cleanup test framework cleanup_test_framework() { if [ -n "$TEST_TEMP_DIR" ] && [ -d "$TEST_TEMP_DIR" ]; then # Double-check we're within EMUBASEDIR for safety if [[ "$TEST_TEMP_DIR" == "$EMUBASEDIR"* ]]; then rm -rf "$TEST_TEMP_DIR" else echo -e "${YELLOW}Warning: Skipping cleanup of $TEST_TEMP_DIR (outside EMUBASEDIR)${NC}" fi fi } # Test assertion functions assert_equals() { local expected="$1" local actual="$2" local message="${3:-}" if [ "$expected" = "$actual" ]; then test_pass "$message" else test_fail "$message - Expected: '$expected', Got: '$actual'" fi } assert_not_equals() { local expected="$1" local actual="$2" local message="${3:-}" if [ "$expected" != "$actual" ]; then test_pass "$message" else test_fail "$message - Expected NOT: '$expected', but got: '$actual'" fi } assert_file_exists() { local file="$1" local message="${2:-File should exist: $file}" if [ -f "$file" ]; then test_pass "$message" else test_fail "$message" fi } assert_file_not_exists() { local file="$1" local message="${2:-File should not exist: $file}" if [ ! -f "$file" ]; then test_pass "$message" else test_fail "$message" fi } assert_dir_exists() { local dir="$1" local message="${2:-Directory should exist: $dir}" if [ -d "$dir" ]; then test_pass "$message" else test_fail "$message" fi } assert_contains() { local haystack="$1" local needle="$2" local message="${3:-Should contain '$needle'}" if [[ "$haystack" == *"$needle"* ]]; then test_pass "$message" else test_fail "$message - '$haystack' does not contain '$needle'" fi } assert_not_contains() { local string="$1" local substring="$2" local message="${3:-String should not contain substring}" if [[ "$string" != *"$substring"* ]]; then test_pass "$message" else test_fail "$message - '$string' should not contain '$substring'" fi } assert_true() { local condition="$1" local message="${2:-Condition should be true}" if eval "$condition"; then test_pass "$message" else test_fail "$message - Condition '$condition' failed" fi } assert_false() { local condition="$1" local message="${2:-Condition should be false}" if ! eval "$condition"; then test_pass "$message" else test_fail "$message - Condition '$condition' should have failed" fi } assert_exit_code() { local expected_code="$1" local command="$2" local message="${3:-Command should exit with code $expected_code}" eval "$command" >/dev/null 2>&1 local actual_code=$? if [ "$expected_code" -eq "$actual_code" ]; then test_pass "$message" else test_fail "$message - Expected exit code: $expected_code, Got: $actual_code" fi } assert_greater_than() { local expected="$1" local actual="$2" local message="${3:-Expected '$actual' to be greater than '$expected'}" if [ "$actual" -gt "$expected" ]; then test_pass "$message" else test_fail "$message - Expected: > $expected, but got: $actual" fi } assert_less_than() { local expected="$1" local actual="$2" local message="${3:-Expected '$actual' to be less than '$expected'}" if [ "$actual" -lt "$expected" ]; then test_pass "$message" else test_fail "$message - Expected: < $expected, but got: $actual" fi } assert_less_than_or_equal() { local expected="$1" local actual="$2" local message="${3:-Expected '$actual' to be less than or equal to '$expected'}" if [ "$actual" -le "$expected" ]; then test_pass "$message" else test_fail "$message - Expected: <= $expected, but got: $actual" fi } # Enhanced assertion functions for comprehensive testing # Assert that a string contains a substring assert_contains() { local string="$1" local substring="$2" local message="${3:-String should contain substring}" if [[ "$string" == *"$substring"* ]]; then test_pass "$message" else test_fail "$message - '$string' does not contain '$substring'" fi } # Assert that a string does not contain a substring assert_not_contains() { local string="$1" local substring="$2" local message="${3:-String should not contain substring}" if [[ "$string" != *"$substring"* ]]; then test_pass "$message" else test_fail "$message - '$string' should not contain '$substring'" fi } # Assert that a string matches a regex pattern assert_matches() { local string="$1" local pattern="$2" local message="${3:-String should match pattern}" if [[ "$string" =~ $pattern ]]; then test_pass "$message" else test_fail "$message - '$string' does not match pattern '$pattern'" fi } # Assert that a string is empty assert_empty() { local string="$1" local message="${2:-String should be empty}" if [ -z "$string" ]; then test_pass "$message" else test_fail "$message - String is not empty: '$string'" fi } # Assert that a string is not empty assert_not_empty() { local string="$1" local message="${2:-String should not be empty}" if [ -n "$string" ]; then test_pass "$message" else test_fail "$message - String is empty" fi } # Assert that a file has specific permissions assert_file_permissions() { local file_path="$1" local expected_perms="$2" local message="${3:-File should have correct permissions}" if [ -f "$file_path" ]; then local actual_perms=$(stat -c "%a" "$file_path" 2>/dev/null) if [ "$actual_perms" = "$expected_perms" ]; then test_pass "$message" else test_fail "$message - Expected: $expected_perms, Got: $actual_perms" fi else test_fail "$message - File not found: $file_path" fi } # Assert that a file is larger than a specified size assert_file_size_greater() { local file_path="$1" local min_size="$2" local message="${3:-File should be larger than specified size}" if [ -f "$file_path" ]; then local actual_size=$(stat -c "%s" "$file_path" 2>/dev/null) if [ "$actual_size" -gt "$min_size" ]; then test_pass "$message" else test_fail "$message - File size $actual_size is not greater than $min_size" fi else test_fail "$message - File not found: $file_path" fi } # Assert that a directory is not empty assert_dir_not_empty() { local dir_path="$1" local message="${2:-Directory should not be empty}" if [ -d "$dir_path" ]; then local file_count=$(find "$dir_path" -type f | wc -l) if [ "$file_count" -gt 0 ]; then test_pass "$message" else test_fail "$message - Directory is empty: $dir_path" fi else test_fail "$message - Directory not found: $dir_path" fi } # Assert that a command completes within a time limit assert_timeout() { local timeout_seconds="$1" local command="$2" local message="${3:-Command should complete within timeout}" local start_time=$(date +%s) timeout "${timeout_seconds}s" bash -c "$command" >/dev/null 2>&1 local exit_code=$? local end_time=$(date +%s) local duration=$((end_time - start_time)) if [ $exit_code -eq 124 ]; then test_fail "$message - Command timed out after ${timeout_seconds}s" elif [ $duration -le $timeout_seconds ]; then test_pass "$message - Completed in ${duration}s" else test_fail "$message - Took too long: ${duration}s" fi } # Assert that two files have the same content assert_files_equal() { local file1="$1" local file2="$2" local message="${3:-Files should have identical content}" if [ -f "$file1" ] && [ -f "$file2" ]; then if cmp -s "$file1" "$file2"; then test_pass "$message" else test_fail "$message - Files differ: $file1 vs $file2" fi else test_fail "$message - One or both files not found" fi } # Assert that a number is within a range assert_in_range() { local value="$1" local min="$2" local max="$3" local message="${4:-Value should be in range}" if [ "$value" -ge "$min" ] && [ "$value" -le "$max" ]; then test_pass "$message" else test_fail "$message - Value $value not in range [$min, $max]" fi } # Enhanced assertion for file content matching assert_file_contains() { local filepath="$1" local expected_content="$2" local message="${3:-File should contain expected content}" if [ ! -f "$filepath" ]; then test_fail "$message - File does not exist: $filepath" return fi if grep -q "$expected_content" "$filepath"; then test_pass "$message" else test_fail "$message - File '$filepath' does not contain '$expected_content'" fi } # Assert file size within range assert_file_size_between() { local filepath="$1" local min_size="$2" local max_size="$3" local message="${4:-File size should be between $min_size and $max_size bytes}" if [ ! -f "$filepath" ]; then test_fail "$message - File does not exist: $filepath" return fi local file_size=$(stat -c%s "$filepath" 2>/dev/null || echo 0) if [ "$file_size" -ge "$min_size" ] && [ "$file_size" -le "$max_size" ]; then test_pass "$message" else test_fail "$message - File size $file_size is not between $min_size and $max_size" fi } # Assert command output contains pattern assert_output_contains() { local command="$1" local expected_pattern="$2" local message="${3:-Command output should contain pattern}" local output output=$(eval "$command" 2>&1) if echo "$output" | grep -q "$expected_pattern"; then test_pass "$message" else test_fail "$message - Output does not contain '$expected_pattern'. Got: $output" fi } # Assert command runs within time limit assert_command_duration() { local max_seconds="$1" local command="$2" local message="${3:-Command should complete within $max_seconds seconds}" local start_time=$(date +%s) eval "$command" >/dev/null 2>&1 local duration=$(($(date +%s) - start_time)) if [ "$duration" -le "$max_seconds" ]; then test_pass "$message" else test_fail "$message - Command took $duration seconds, expected <= $max_seconds" fi } # Test result functions test_pass() { local message="$1" echo -e " ${GREEN}✓${NC} $message" TESTS_PASSED=$((TESTS_PASSED + 1)) } test_fail() { local message="$1" echo -e " ${RED}✗${NC} $message" TESTS_FAILED=$((TESTS_FAILED + 1)) } # Start a test start_test() { CURRENT_TEST="$1" echo -e "\n${BLUE}Testing:${NC} $CURRENT_TEST" TESTS_RUN=$((TESTS_RUN + 1)) } # Mock functions for external dependencies mock_command() { local command="$1" local mock_output="$2" local mock_exit_code="${3:-0}" # Create a mock script in temp directory local mock_script="$TEST_TEMP_DIR/mock_$command" cat > "$mock_script" << EOF #!/bin/bash echo "$mock_output" exit $mock_exit_code EOF chmod +x "$mock_script" # Add to PATH export PATH="$TEST_TEMP_DIR:$PATH" } # Create test files/directories create_test_file() { local file="$1" local content="${2:-test content}" mkdir -p "$(dirname "$file")" echo "$content" > "$file" } create_test_dir() { local dir="$1" mkdir -p "$dir" } # Run all test functions run_tests() { echo -e "${YELLOW}ROM Organizer Unit Tests${NC}" echo "===============================" init_test_framework # Find and run all functions that start with "test_" but exclude framework functions local test_functions=$(declare -F | grep "test_" | awk '{print $3}' | grep -v "^test_pass$\|^test_fail$\|^cleanup_test_framework$\|^create_test_dir$\|^create_test_file$\|^init_test_framework$") for test_func in $test_functions; do run_test "$test_func" done print_test_summary cleanup_test_framework # Exit with failure code if any tests failed [ $TESTS_FAILED -eq 0 ] } # Run a single test function run_test() { local test_func="$1" start_test "$test_func" # Setup test environment setup_test 2>/dev/null || true # Run the test function $test_func # Cleanup test environment teardown_test 2>/dev/null || true } # Print test summary print_test_summary() { echo "" echo "===============================" if [ $TESTS_FAILED -eq 0 ]; then echo -e "${GREEN}All tests passed!${NC} Assertions: $TESTS_PASSED, Test Functions: $TESTS_RUN" else echo -e "${RED}Some tests failed.${NC} Assertions Passed: $TESTS_PASSED, Failed: $TESTS_FAILED, Test Functions: $TESTS_RUN" fi } # Print a test header print_test_header() { local header="$1" echo -e "\n${BLUE}$header${NC}" } # Print a test suite header print_test_suite_header() { local header="$1" echo "" echo "===============================================" echo " $header" echo "===============================================" echo "" } # Check if file exists assert_file_exists() { local file_path="$1" local message="$2" if [[ -f "$file_path" ]]; then test_pass "$message" else test_fail "$message (file not found: $file_path)" fi } # Check if file is executable assert_file_executable() { local file_path="$1" local message="$2" if [[ -x "$file_path" ]]; then test_pass "$message" else test_fail "$message (file not executable: $file_path)" fi } # Optional setup/teardown functions (can be overridden by test files) setup_test() { # Override this function in your test files if needed return 0 } teardown_test() { # Override this function in your test files if needed return 0 }