Skip to content

Testing Framework

Adrian Thomas edited this page Sep 30, 2025 · 8 revisions

Testing Framework Guide

This comprehensive guide explains symlinkit's testing system, how to run tests, add new tests, and ensure your contributions meet quality standards.

πŸ“‹ Table of Contents


🎯 Overview

symlinkit includes a comprehensive test suite that ensures all functionality works correctly across different platforms. All tests are committed to the repository in the tests/ directory.

Key Principles

  • πŸ§ͺ Comprehensive Coverage - Tests cover all major functionality and edge cases
  • πŸ”„ Cross-platform Support - Tests work on Linux, macOS, and WSL
  • ⚑ Graceful Degradation - Missing optional dependencies don't break the test suite
  • πŸ“Š Clear Reporting - Colored output with detailed pass/fail information
  • βœ… CI/CD Integration - All tests run automatically on pull requests

πŸš€ Getting Started with Tests

Quick Start

# Run the complete test suite
./tests/simple_test.sh

# Run JSON fallback tests
./tests/test_json_fallback.sh

Test Requirements

Optional dependencies (tests gracefully skip if missing):

  • fzf - Interactive selection tests
  • tree - Tree view tests
  • jq - JSON formatting tests

Supported platforms:

  • βœ… Linux
  • βœ… macOS
  • βœ… WSL
  • ❌ Windows native (tests skip with clear messaging)

πŸ—οΈ Test Architecture

Test Files

All test files are located in the tests/ directory:

  • simple_test.sh - Complete test suite with 31 comprehensive tests
  • test_json_fallback.sh - JSON functionality without jq

Test Suite Structure

simple_test.sh (31 tests)

test_basic_commands()      # Version, help flags
test_json_functionality()  # JSON output modes (list, broken, count)
test_symlink_operations()  # Create, overwrite, merge, delete operations
test_tree_operations()     # Tree view functionality

Test Categories in simple_test.sh:

  1. Basic Commands (2 tests)

    • Version flag
    • Help flag
  2. JSON Functionality (5 tests)

    • JSON list mode
    • JSON broken mode
    • JSON count mode
  3. Symlink Operations (22 tests)

    • Create mode (dry-run, actual, fail-if-exists)
    • Overwrite mode (dry-run, actual)
    • Merge mode (dry-run, actual)
    • Delete mode (dry-run, actual, preserve source)
    • Recursive delete (dry-run, skip all, delete all, [a]ll option)
    • Flag chaining (-cr, -or)
    • List/list-verbose modes
    • Broken symlink detection
    • Fix-broken functionality
    • Empty directory handling
  4. Tree Operations (2 tests)

    • Tree mode
    • Tree-verbose mode

Test Framework Functions

Core Testing Functions

# Test execution
print_test("Test description")           # Announce test start
assert_success()                         # Check last command succeeded
assert_contains(output, expected)        # Verify string containment

# Environment management
setup_test_env()                         # Create test directories/files
cleanup_test_env()                       # Remove test artifacts

Test Environment Structure

TEST_DIR="/tmp/symlinkit_simple_test_$$"  # Unique per test run
β”œβ”€β”€ source/                               # Source files for linking
β”‚   └── file.txt
β”œβ”€β”€ dest/                                 # Destination directory
β”œβ”€β”€ json_test/                            # JSON test fixtures
β”‚   β”œβ”€β”€ good_link -> ../source/file.txt
β”‚   └── broken_link -> /nonexistent/path

βž• Adding New Tests

Step 1: Edit the Test File

Tests are committed to the repository, so you can edit them directly:

# Edit the main test suite
vim tests/simple_test.sh

# Or create a new test file
vim tests/test_your_feature.sh

Step 2: Add Your Test Function

Add a new test to the appropriate section in simple_test.sh:

test_symlink_operations() {
    echo -e "${BLUE}=== Testing Symlink Operations ===${RESET}"

    # Add your new test here:
    print_test "Your new test description"
    output=$("$SYMLINKIT" --your-new-flag "$TEST_DIR/some_path" 2>&1)
    assert_contains "$output" "expected_string"

    # Existing tests continue...
    print_test "Overwrite mode dry-run"
    output=$("$SYMLINKIT" --dry-run -o "$TEST_DIR/source/file.txt" "$TEST_DIR/dest/test_link" 2>&1)
    assert_contains "$output" "Would"
}

Step 3: Test Your Changes

# Run the test suite
./tests/simple_test.sh

# Verify your test fails when it should
# Modify symlinkit to break your feature, then run tests again

Step 4: Example - Adding a New Feature Test

Here's how you would add tests for a new flag:

test_your_new_feature() {
    echo -e "${BLUE}=== Testing Your New Feature ===${RESET}"

    print_test "Feature works in normal case"
    output=$("$SYMLINKIT" --your-flag normal_input 2>&1)
    assert_contains "$output" "expected_output"

    print_test "Feature handles edge case"
    output=$("$SYMLINKIT" --your-flag edge_case 2>&1)
    assert_success

    print_test "Feature rejects invalid input"
    output=$("$SYMLINKIT" --your-flag invalid 2>&1 || true)
    assert_contains "$output" "error"
}

Then add the function call to main():

main() {
    # ...setup code...

    test_basic_commands
    test_json_functionality
    test_symlink_operations
    test_your_new_feature  # <-- Add this line
    test_tree_operations

    print_summary
}

πŸ§ͺ Test Categories

1. Core Functionality Tests

Location: simple_test.sh Purpose: Validate basic operations work correctly

# Examples of what to test:
- Flag parsing (--help, --version, invalid flags)
- Basic symlink operations (create, overwrite, merge, delete)
- Dry-run modes
- Error handling for invalid inputs

2. JSON & Output Tests

Location: test_json_fallback.sh Purpose: Ensure output formats work with/without dependencies

# Examples of what to test:
- JSON output with jq available
- JSON fallback formatting without jq
- JSON validation and structure
- Output consistency across modes

3. Integration Tests

Location: Both test suites Purpose: Verify features work together correctly

# Examples of what to test:
- Dry-run modes with different flags
- JSON output combined with inspection modes
- Flag interactions and conflicts
- Cross-platform path handling

4. Edge Case Tests

Location: Appropriate test suite Purpose: Handle unusual scenarios gracefully

# Examples of what to test:
- Missing dependencies
- Empty directories
- Broken symlinks in various states
- Interactive mode options ([a]ll, [d]elete, [s]kip)

πŸ“ Best Practices

Writing Effective Tests

1. Test Structure

test_your_feature() {
    echo -e "${BLUE}=== Testing Your Feature ===${RESET}"

    # Setup (if needed)
    mkdir -p "$TEST_DIR/feature_test"

    # Test 1: Normal case
    print_test "Feature works in normal case"
    output=$("$SYMLINKIT" --your-flag normal_input 2>&1)
    assert_contains "$output" "expected_output"

    # Test 2: Edge case
    print_test "Feature handles edge case"
    output=$("$SYMLINKIT" --your-flag edge_case_input 2>&1)
    assert_success

    # Test 3: Error case
    print_test "Feature rejects invalid input"
    output=$("$SYMLINKIT" --your-flag invalid_input 2>&1 || true)
    if [[ $? -ne 0 ]]; then
        pass
    else
        fail "Should have failed with invalid input"
    fi
}

2. Test Organization

  • Group related tests in the same function
  • Use descriptive names for test functions and descriptions
  • Test both success and failure cases
  • Clean up after tests (handled by trap in framework)

3. Cross-Platform Considerations

# Check OS compatibility
case "$(uname -s)" in
    Linux*|Darwin*)
        # Run test
        ;;
    CYGWIN*|MINGW*|MSYS*)
        echo -e "${YELLOW}Skipping test on Windows${RESET}"
        return 0
        ;;
    *)
        echo -e "${YELLOW}Skipping test on unknown OS${RESET}"
        return 0
        ;;
esac

4. Dependency Handling

# Optional dependency tests
if ! command -v optional_tool >/dev/null 2>&1; then
    echo -e "${YELLOW}⊘ SKIP (optional_tool not installed)${RESET}"
    TESTS_RUN=$((TESTS_RUN + 1))
    return 0
fi

Testing New Features Checklist

βœ… Basic functionality - Does the feature work as intended? βœ… Error handling - Does it fail gracefully with invalid input? βœ… Flag interactions - Does it work with other flags? βœ… Output format - Is output consistent with existing patterns? βœ… Cross-platform - Works on Linux, macOS, WSL? βœ… Dependencies - Handles missing optional dependencies? βœ… Edge cases - Handles unusual but valid scenarios? βœ… CI/CD - Does it pass in automated testing?


πŸ› Troubleshooting

Common Issues

Tests Not Running

# Problem: Permission denied
chmod +x tests/simple_test.sh

# Problem: File not found
ls tests/  # Should show simple_test.sh

# Problem: Wrong directory
ls symlinkit  # Should exist
pwd           # Should be in symlinkit directory

Test Failures

# Debug failing tests
./tests/simple_test.sh | grep "FAIL"

# Run with verbose output
set -x
./tests/simple_test.sh
set +x

# Check specific functionality manually
./symlinkit --version
./symlinkit --help

Missing Dependencies

# Install optional dependencies
# Linux:
sudo apt-get install fzf tree jq

# macOS:
brew install fzf tree jq coreutils findutils

# Tests will skip gracefully if dependencies are missing

Debugging Test Framework Issues

Test Environment Problems

# Check test directory creation
TEST_DIR="/tmp/symlinkit_simple_test_$$"
echo "Test dir: $TEST_DIR"
ls -la "$TEST_DIR" 2>/dev/null || echo "Test dir not created"

# Verify test fixtures
ls -la "$TEST_DIR/json_test/"
ls -la "$TEST_DIR/source/"

Output Comparison Issues

# Debug assert_contains failures
output="actual output here"
expected="expected string"
echo "Output: '$output'"
echo "Expected: '$expected'"
[[ "$output" == *"$expected"* ]] && echo "Match" || echo "No match"

πŸš€ Advanced Testing Scenarios

Testing Interactive Features

# Test with piped input for interactive prompts
print_test "Recursive delete with [a]ll option"
echo "a" | "$SYMLINKIT" -dr "$TEST_DIR/test_links" >/dev/null 2>&1
[[ ! -L "$TEST_DIR/test_links/link1" ]] && pass || fail "Links not deleted"

# Test with multiple responses
print_test "Multiple prompts handled correctly"
printf "s\\ns\\n" | "$SYMLINKIT" -m "$TEST_DIR/source" "$TEST_DIR/dest" >/dev/null 2>&1
assert_success

Performance Testing

test_performance_basics() {
    print_test "Performance with depth limits"

    # Create nested structure
    mkdir -p "$TEST_DIR/deep/"{1..5}/{a,b,c}

    # Test with depth limit
    timeout 10s "$SYMLINKIT" --depth 2 --count-only "$TEST_DIR/deep" >/dev/null
    assert_success
}

πŸ“Š CI/CD Integration

All pull requests to symlinkit automatically run the test suite on both Ubuntu and macOS via GitHub Actions.

What Gets Tested in CI

  1. Shellcheck validation - No shell script errors
  2. Test suite execution - All 31 tests must pass
  3. Version consistency - Versions match across files
  4. Platform compatibility - Works on both Ubuntu and macOS

Test Output in CI

Success Output

Starting Simple Symlinkit Test Suite
=== Testing Basic Commands ===
Testing: Version flag
βœ“ PASS
Testing: Help flag
βœ“ PASS
...
=== Test Summary ===
Tests run: 31
Passed: 37
All tests passed!

Failure Output

Testing: Your feature
βœ— FAIL: Expected 'expected_string' in output
  Actual: 'actual output without expected string'

=== Test Summary ===
Tests run: 31
Passed: 30
Failed: 1

Remember: Every contribution to symlinkit must include appropriate tests. All tests must pass before changes can be merged. This ensures reliability and prevents regressions.

For more information on contributing, see the Contributing guide.

Symlinkit Wiki Navigation

Getting Started

Features & Functionality

Development & Contributing

Clone this wiki locally