This commit is contained in:
2026-02-06 21:03:59 -03:00
commit 2b7ab5f570
267 changed files with 176026 additions and 0 deletions

354
scripts/coverage-kcov.sh Executable file
View File

@@ -0,0 +1,354 @@
#!/bin/bash
#
# Coverage Script for zig-p2p
# Runs all tests with kcov and generates merged coverage report
#
# Usage:
# ./scripts/coverage.sh # Run full coverage
# ./scripts/coverage.sh --quick # Run only source tests (faster)
# ./scripts/coverage.sh --single test-upload # Run single test module
#
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"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Test modules to run
SOURCE_TESTS=(
"test-core-src"
"test-network-src"
"test-protocol-src"
"test-files-src"
"test-p2p-src"
)
INTEGRATION_TESTS=(
"test-bridge"
"test-security"
"test-message-auth"
"test-encryption-integration"
"test-error-recovery"
"test-e2e"
"test-noise-connection"
"test-secure-connection"
"test-nat"
"test-replay-protection"
"test-transfer-protocol"
"test-upload"
"test-memory-leaks"
"test-memory-safety"
"test-thread-safety"
"test-disk-stubs"
"test-nonce-exhaustion"
"test-allocation-limits"
"test-download-retry"
"test-security-fixes"
"test-serializer"
"test-discovery"
"test-nat-extended"
"test-turn-integration"
"test-network-manager"
"test-manager"
"test-manager-integration"
"test-p2p-comprehensive"
"test-peer-metrics"
"test-piece-buffer-pool"
"test-verification-pool"
"test-piece-pipeline"
"test-p2p-coverage"
"test-connected-coverage"
"test-tier1-coverage"
"test-tier2-coverage"
"test-tier3-coverage"
"test-transfer-coverage"
"test-nat-coverage"
"test-turn-coverage"
"test-discovery-coverage"
"test-manager-coverage"
"test-manager-sessions"
"test-mockfs"
"test-full-integration"
)
print_header() {
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}$1${NC}"
echo -e "${BLUE}========================================${NC}"
}
print_status() {
echo -e "${GREEN}[✓]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[!]${NC} $1"
}
print_error() {
echo -e "${RED}[✗]${NC} $1"
}
check_kcov() {
if ! command -v kcov &> /dev/null; then
print_error "kcov not found. Please install kcov first."
echo " macOS: brew install kcov"
echo " Linux: apt-get install kcov"
exit 1
fi
}
build_test() {
local test_name=$1
echo -n " Building $test_name... "
if zig build "$test_name" -Doptimize=Debug 2>/dev/null; then
echo -e "${GREEN}OK${NC}"
return 0
else
echo -e "${RED}FAILED${NC}"
return 1
fi
}
find_test_binary() {
local test_name=$1
# Find the most recently modified test binary in .zig-cache
# The binary is usually in .zig-cache/o/*/test
local binary=$(find "$PROJECT_DIR/.zig-cache/o" -name 'test' -type f -perm +111 2>/dev/null | \
xargs ls -t 2>/dev/null | head -1)
# Fallback: check zig-out
if [ -z "$binary" ]; then
binary=$(find "$PROJECT_DIR/zig-out" -name 'test' -type f -perm +111 2>/dev/null | \
xargs ls -t 2>/dev/null | head -1)
fi
echo "$binary"
}
run_test_with_coverage() {
local test_name=$1
local output_dir="$COVERAGE_DIR/$test_name"
echo -n " Running $test_name with coverage... "
# Build and get binary path from verbose output
local build_output=$(zig build "$test_name" -Doptimize=Debug --verbose 2>&1)
local build_status=$?
if [ $build_status -ne 0 ]; then
echo -e "${RED}BUILD FAILED${NC}"
return 1
fi
# Parse the test binary path from verbose output
# Format: ./.zig-cache/o/HASH/test --cache-dir=...
local test_binary=$(echo "$build_output" | grep -oE '\./.zig-cache/o/[a-f0-9]+/test' | head -1)
if [ -z "$test_binary" ]; then
# Fallback: find most recently modified test binary
test_binary=$(find "$PROJECT_DIR/.zig-cache/o" -name 'test' -type f -perm +111 2>/dev/null | \
xargs ls -t 2>/dev/null | head -1)
fi
if [ -z "$test_binary" ]; then
echo -e "${RED}BINARY NOT FOUND${NC}"
return 1
fi
# Run with kcov
rm -rf "$output_dir"
if kcov --include-pattern="$PROJECT_DIR/src" "$output_dir" "$test_binary" 2>/dev/null; then
echo -e "${GREEN}OK${NC}"
return 0
else
echo -e "${YELLOW}TESTS FAILED (coverage still collected)${NC}"
return 0 # Still count coverage even if some tests fail
fi
}
merge_coverage() {
print_header "Merging Coverage Reports"
rm -rf "$MERGED_DIR"
mkdir -p "$MERGED_DIR"
# Find all coverage directories
local coverage_dirs=$(find "$COVERAGE_DIR" -maxdepth 1 -type d -name "test-*" 2>/dev/null | tr '\n' ' ')
if [ -z "$coverage_dirs" ]; then
print_error "No coverage data found"
return 1
fi
echo " Merging $(echo $coverage_dirs | wc -w | tr -d ' ') coverage reports..."
kcov --merge "$MERGED_DIR/kcov-merged" $coverage_dirs 2>/dev/null
print_status "Coverage merged to $MERGED_DIR/kcov-merged"
}
print_summary() {
print_header "Coverage Summary"
# kcov creates nested directory structure
local json_file="$MERGED_DIR/kcov-merged/kcov-merged/coverage.json"
# Fallback to other possible locations
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
print_error "Coverage report not found"
return 1
fi
# Parse and display coverage
echo ""
echo -e "${BLUE}Per-File Coverage:${NC}"
echo "----------------------------------------"
python3 << EOF
import json
import sys
with open("$json_file") as f:
data = json.load(f)
# Sort files by coverage percentage
files = sorted(data['files'], key=lambda x: float(x['percent_covered']))
# Print files with low coverage first
for f in files:
name = f['file'].replace('$PROJECT_DIR/', '')
name = name.replace('/Users/mdt./Projects/zig-p2p/', '')
pct = float(f['percent_covered'])
covered = f['covered_lines']
total = f['total_lines']
# Color based on coverage
if pct < 50:
color = '\033[0;31m' # Red
elif pct < 75:
color = '\033[1;33m' # Yellow
else:
color = '\033[0;32m' # Green
print(f" {color}{pct:6.2f}%\033[0m {covered:>4}/{total:<4} {name}")
print("")
print("========================================")
print(f" Overall: {data['percent_covered']}% ({data['covered_lines']}/{data['total_lines']} lines)")
print("========================================")
EOF
}
run_quick() {
print_header "Running Quick Coverage (Source Tests Only)"
for test in "${SOURCE_TESTS[@]}"; do
run_test_with_coverage "$test"
done
merge_coverage
print_summary
}
run_full() {
print_header "Running Full Coverage"
echo ""
echo -e "${BLUE}Source Tests:${NC}"
for test in "${SOURCE_TESTS[@]}"; do
run_test_with_coverage "$test"
done
echo ""
echo -e "${BLUE}Integration Tests:${NC}"
for test in "${INTEGRATION_TESTS[@]}"; do
run_test_with_coverage "$test"
done
merge_coverage
print_summary
}
run_single() {
local test_name=$1
print_header "Running Coverage for $test_name"
run_test_with_coverage "$test_name"
# Show single test coverage
local json_file="$COVERAGE_DIR/$test_name/test/coverage.json"
if [ -f "$json_file" ]; then
echo ""
echo -e "${BLUE}Coverage for $test_name:${NC}"
python3 << EOF
import json
with open("$json_file") as f:
data = json.load(f)
files = sorted(data['files'], key=lambda x: float(x['percent_covered']))
for f in files:
name = f['file'].replace('/Users/mdt./Projects/zig-p2p/', '')
pct = float(f['percent_covered'])
covered = f['covered_lines']
total = f['total_lines']
if pct < 50:
color = '\033[0;31m'
elif pct < 75:
color = '\033[1;33m'
else:
color = '\033[0;32m'
print(f" {color}{pct:6.2f}%\033[0m {covered:>4}/{total:<4} {name}")
print(f"\n Overall: {data['percent_covered']}%")
EOF
fi
}
# Main
cd "$PROJECT_DIR"
check_kcov
case "${1:-}" in
--quick|-q)
run_quick
;;
--single|-s)
if [ -z "${2:-}" ]; then
print_error "Please specify a test name"
echo " Example: $0 --single test-upload"
exit 1
fi
run_single "$2"
;;
--help|-h)
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " (none) Run full coverage (all tests)"
echo " --quick, -q Run quick coverage (source tests only)"
echo " --single, -s Run coverage for a single test module"
echo " --help, -h Show this help"
echo ""
echo "Examples:"
echo " $0 # Full coverage"
echo " $0 --quick # Quick coverage"
echo " $0 --single test-upload # Single module coverage"
;;
*)
run_full
;;
esac

305
scripts/coverage.sh Executable file
View File

@@ -0,0 +1,305 @@
#!/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 "$@"