sharenet/backend/crates/postgres/run_tests.sh

123 lines
No EOL
3.4 KiB
Bash

#!/bin/bash
# Postgres Crate Test Runner
# This script helps set up and run the postgres crate tests
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${GREEN}Postgres Crate Test Runner${NC}"
echo "================================"
# Check if DATABASE_URL is set
if [ -z "$DATABASE_URL" ]; then
echo -e "${YELLOW}DATABASE_URL not set, using default test database${NC}"
export DATABASE_URL="postgres://postgres:password@localhost:5432/sharenet_test"
fi
echo -e "${GREEN}Using database: $DATABASE_URL${NC}"
# Check if we're in the right directory
if [ ! -f "Cargo.toml" ] || [ ! -f "src/lib.rs" ]; then
echo -e "${RED}Error: Must run this script from the postgres crate directory${NC}"
echo "Current directory: $(pwd)"
echo "Expected files: Cargo.toml, src/lib.rs"
exit 1
fi
# Function to check if PostgreSQL is running
check_postgres() {
echo -e "${YELLOW}Checking PostgreSQL connection...${NC}"
# Try to connect to the database
if command -v psql &> /dev/null; then
if psql "$DATABASE_URL" -c "SELECT 1;" &> /dev/null; then
echo -e "${GREEN}PostgreSQL connection successful${NC}"
return 0
else
echo -e "${RED}PostgreSQL connection failed${NC}"
return 1
fi
else
echo -e "${YELLOW}psql not found, skipping connection check${NC}"
return 0
fi
}
# Function to run migrations
run_migrations() {
echo -e "${YELLOW}Running database migrations...${NC}"
if command -v sqlx &> /dev/null; then
sqlx migrate run --database-url "$DATABASE_URL" || {
echo -e "${RED}Migration failed${NC}"
return 1
}
echo -e "${GREEN}Migrations completed successfully${NC}"
else
echo -e "${YELLOW}sqlx CLI not found, migrations will be run by tests${NC}"
fi
}
# Function to run tests
run_tests() {
echo -e "${GREEN}Running tests...${NC}"
# Check if specific test pattern was provided
if [ $# -eq 0 ]; then
echo "Running all tests..."
cargo test
else
echo "Running tests matching: $1"
cargo test "$1"
fi
}
# Main execution
main() {
# Check PostgreSQL connection
if ! check_postgres; then
echo -e "${RED}Please ensure PostgreSQL is running and accessible${NC}"
echo "You can start PostgreSQL with:"
echo " sudo systemctl start postgresql"
echo " or"
echo " docker run --name postgres-test -e POSTGRES_PASSWORD=password -e POSTGRES_DB=sharenet_test -p 5432:5432 -d postgres:15"
exit 1
fi
# Run migrations
run_migrations
# Run tests
run_tests "$@"
echo -e "${GREEN}Tests completed!${NC}"
}
# Handle command line arguments
case "${1:-}" in
--help|-h)
echo "Usage: $0 [test_pattern]"
echo ""
echo "Options:"
echo " test_pattern Run only tests matching this pattern"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " $0 # Run all tests"
echo " $0 user_repository # Run user repository tests"
echo " $0 create # Run tests with 'create' in the name"
echo ""
echo "Environment:"
echo " DATABASE_URL Database connection string (optional)"
exit 0
;;
*)
main "$@"
;;
esac