#!/bin/bash # # Coverage Script for zig-p2p # Uses parallel kcov execution for fast coverage collection # # Usage: # ./scripts/coverage.sh # Run source + files tests (~17s) # ./scripts/coverage.sh --full # Include integration tests (~74s) # # For the old sequential coverage script, use: ./scripts/coverage-kcov.sh # set -e SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PROJECT_DIR="$(dirname "$SCRIPT_DIR")" COVERAGE_DIR="$PROJECT_DIR/coverage" MERGED_DIR="$COVERAGE_DIR/merged" # Detect CPU cores if [[ "$OSTYPE" == "darwin"* ]]; then NPROC=$(sysctl -n hw.ncpu) else NPROC=$(nproc) fi # Colors RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' CYAN='\033[0;36m' NC='\033[0m' # Source tests (fast, high coverage) SOURCE_TESTS=( "test-core-src" "test-network-src" "test-protocol-src" "test-p2p-src" "test-noise-src" ) # Files module tests (individual files - parallelizes well with kcov) FILES_TESTS=( "test-download-src" "test-transfer-src" "test-file-src" "test-path-security-src" "test-piece-src" "test-hash-src" "test-mockfs-src" "test-filesystem-src" "test-peer-metrics" "test-piece-buffer-pool" "test-verification-pool" "test-piece-pipeline" "test-adaptive-src" "test-limits-src" "test-upload-src" "test-discovery-src" "test-nat-src" "test-routing-src" "test-serializer-src" "test-dht-src" # "test-manager-src" # 300 tests - kcov takes 2+ hours, impractical ) # Integration tests INTEGRATION_TESTS=( "test-manager" "test-transfer-protocol" "test-upload" "test-security" "test-bridge" "test-nat" "test-replay-protection" "test-network-manager" "test-error-recovery" "test-p2p-coverage" "test-p2p-comprehensive" "test-p2p-high-impact" "test-secure-connection" # "test-connected-coverage" # hangs under kcov ptrace "test-tier1-coverage" "test-tier2-coverage" "test-transfer-coverage" "test-discovery-coverage" # "test-turn-coverage" # hangs under kcov ptrace "test-full-integration" "test-address-coverage" "test-encryption-integration" "test-e2e" "test-manager-integration" "test-manager-sessions" "test-manager-coverage" "test-message-auth" "test-mockfs" "test-noise-connection" "test-real-file-io" "test-nat-coverage" "test-tier3-coverage" ) print_header() { echo -e "${BLUE}========================================${NC}" echo -e "${BLUE}$1${NC}" echo -e "${BLUE}========================================${NC}" } # Run coverage for a single test (called in parallel) run_coverage_job() { local test_name=$1 local project_dir=$2 local coverage_dir=$3 local output_dir="$coverage_dir/$test_name" cd "$project_dir" # Build and get binary path local build_output=$(zig build "$test_name" -Doptimize=Debug --verbose 2>&1) local binary=$(echo "$build_output" | grep -oE '\./.zig-cache/o/[a-f0-9]+/test' | head -1) if [ -z "$binary" ] || [ ! -f "$binary" ]; then echo "SKIP:$test_name:binary not found" return 1 fi # Run kcov rm -rf "$output_dir" 2>/dev/null if kcov --include-path="$project_dir/src" "$output_dir" "$binary" >/dev/null 2>&1; then echo "OK:$test_name" else # kcov might return non-zero if tests fail, but coverage is still collected if [ -d "$output_dir" ]; then echo "WARN:$test_name:tests failed but coverage collected" else echo "FAIL:$test_name" return 1 fi fi } export -f run_coverage_job # Run tests with parallel kcov run_parallel() { local tests=("$@") local pids=() local results=() echo -e "${CYAN}Running ${#tests[@]} tests with kcov ($NPROC cores)...${NC}" echo "" # Start all jobs in parallel (limited to NPROC) local running=0 for test_name in "${tests[@]}"; do ( result=$(run_coverage_job "$test_name" "$PROJECT_DIR" "$COVERAGE_DIR") status="${result%%:*}" if [ "$status" = "OK" ]; then echo -e " ${GREEN}[OK]${NC} $test_name" elif [ "$status" = "WARN" ]; then echo -e " ${YELLOW}[WARN]${NC} $test_name" elif [ "$status" = "SKIP" ]; then echo -e " ${YELLOW}[SKIP]${NC} $test_name" else echo -e " ${RED}[FAIL]${NC} $test_name" fi ) & pids+=($!) running=$((running + 1)) # Limit parallel jobs if [ $running -ge $NPROC ]; then wait "${pids[0]}" 2>/dev/null || true pids=("${pids[@]:1}") running=$((running - 1)) fi done # Wait for remaining for pid in "${pids[@]}"; do wait "$pid" 2>/dev/null || true done echo "" } # Merge coverage merge_coverage() { echo -e "${CYAN}Merging coverage reports...${NC}" rm -rf "$MERGED_DIR" 2>/dev/null mkdir -p "$MERGED_DIR" local dirs=$(find "$COVERAGE_DIR" -maxdepth 1 -type d -name "test-*" 2>/dev/null | tr '\n' ' ') if [ -z "$dirs" ]; then echo -e "${RED}No coverage data found${NC}" return 1 fi kcov --merge "$MERGED_DIR/kcov-merged" $dirs 2>/dev/null echo -e "${GREEN}[OK]${NC} Coverage merged" } # Print summary print_summary() { local json_file="$MERGED_DIR/kcov-merged/kcov-merged/coverage.json" if [ ! -f "$json_file" ]; then json_file=$(find "$MERGED_DIR" -name "coverage.json" -type f 2>/dev/null | head -1) fi if [ ! -f "$json_file" ]; then echo -e "${RED}Coverage report not found${NC}" return 1 fi echo "" print_header "Coverage Summary" python3 << EOF import json with open("$json_file") as f: data = json.load(f) modules = {} for f in data["files"]: path = f["file"].replace("$PROJECT_DIR/src/", "") parts = path.split("/") module = parts[0] if len(parts) > 1 else "root" if module not in modules: modules[module] = {"covered": 0, "total": 0} modules[module]["covered"] += int(f["covered_lines"]) modules[module]["total"] += int(f["total_lines"]) print("") for module in sorted(modules.keys(), key=lambda m: -modules[m]["covered"]/max(modules[m]["total"],1)): m = modules[module] pct = (m["covered"] / m["total"] * 100) if m["total"] > 0 else 0 status = "+" if pct >= 75 else "o" if pct >= 50 else "-" color = "\033[0;32m" if pct >= 75 else "\033[1;33m" if pct >= 50 else "\033[0;31m" print(f" {status} {color}{module:<15}\033[0m {pct:5.1f}% ({m['covered']}/{m['total']})") print("") print("=" * 50) print(f" OVERALL: {data['percent_covered']}% ({data['covered_lines']}/{data['total_lines']} lines)") print("=" * 50) EOF } # Main main() { cd "$PROJECT_DIR" local start_time=$(date +%s) local run_full=false case "${1:-}" in --full|-f) run_full=true ;; --help|-h) echo "Usage: $0 [--full]" echo " (default) Source + files tests (~17s)" echo " --full Include integration tests (~74s)" echo "" echo "For old sequential coverage: ./scripts/coverage-kcov.sh" exit 0 ;; esac # Check kcov if ! command -v kcov &>/dev/null; then echo -e "${RED}kcov not found. Install: brew install kcov${NC}" exit 1 fi rm -rf "$COVERAGE_DIR" 2>/dev/null mkdir -p "$COVERAGE_DIR" if $run_full; then print_header "Fast Coverage (Full)" run_parallel "${SOURCE_TESTS[@]}" run_parallel "${FILES_TESTS[@]}" run_parallel "${INTEGRATION_TESTS[@]}" else print_header "Fast Coverage (Source + Files)" run_parallel "${SOURCE_TESTS[@]}" run_parallel "${FILES_TESTS[@]}" fi merge_coverage print_summary local end_time=$(date +%s) local duration=$((end_time - start_time)) echo "" echo -e "${GREEN}Completed in ${duration} seconds${NC}" echo "Report: file://$MERGED_DIR/kcov-merged/index.html" } main "$@"