Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:23:39 +08:00
commit 3ea574364c
11 changed files with 415 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
---
name: managing-test-environments
description: |
This skill enables Claude to manage isolated test environments using Docker Compose, Testcontainers, and environment variables. It is used to create consistent, reproducible testing environments for software projects. Claude should use this skill when the user needs to set up a test environment with specific configurations, manage Docker Compose files for test infrastructure, set up programmatic container management with Testcontainers, manage environment variables for tests, or ensure cleanup after tests. Trigger terms include "test environment", "docker compose", "testcontainers", "environment variables", "isolated environment", "env-setup", and "test setup".
allowed-tools: Read, Write, Edit, Grep, Glob, Bash
version: 1.0.0
---
## Overview
This skill empowers Claude to orchestrate and manage isolated test environments, ensuring consistent and reproducible testing processes. It simplifies the setup and teardown of complex testing infrastructures by leveraging Docker Compose, Testcontainers, and environment variable management.
## How It Works
1. **Environment Creation**: Generates isolated test environments with databases, caches, message queues, and other dependencies.
2. **Docker Compose Management**: Creates and configures `docker-compose.yml` files to define the test infrastructure.
3. **Testcontainers Integration**: Sets up programmatic container management using Testcontainers for dynamic environment configuration.
## When to Use This Skill
This skill activates when you need to:
- Create an isolated test environment for a software project.
- Manage Docker Compose files for test infrastructure.
- Set up programmatic container management using Testcontainers.
## Examples
### Example 1: Setting up a Database Test Environment
User request: "Set up a test environment with a PostgreSQL database and a Redis cache using Docker Compose."
The skill will:
1. Generate a `docker-compose.yml` file defining PostgreSQL and Redis services.
2. Configure environment variables for database connection and cache access.
### Example 2: Creating a Test Environment with Message Queue
User request: "Create a test environment with RabbitMQ using Testcontainers."
The skill will:
1. Programmatically create a RabbitMQ container using Testcontainers.
2. Configure environment variables for message queue connection.
## Best Practices
- **Configuration**: Ensure that all necessary environment variables are properly configured for the test environment.
- **Cleanup**: Implement cleanup routines to remove test environments after use.
- **Isolation**: Verify that the test environment is properly isolated from other environments.
## Integration
This skill integrates with other Claude Code plugins to manage the deployment and execution of tests within the created environments. It can work with CI/CD tools to automate testing workflows.

View File

@@ -0,0 +1,7 @@
# Assets
Bundled resources for test-environment-manager skill
- [ ] docker-compose-template.yml: Template for creating Docker Compose files.
- [ ] test_environment_diagram.png: Diagram illustrating the architecture of a typical test environment.
- [ ] example_test_script.py: Example Python test script that uses the test environment.

View File

@@ -0,0 +1,53 @@
# docker-compose-template.yml
# Template for defining services and dependencies for test environments.
version: "3.9" # Specify the Docker Compose file version
services:
# Database service (e.g., PostgreSQL)
db:
image: postgres:14 # Use a specific PostgreSQL version
container_name: test-db # A descriptive container name
restart: always # Automatically restart the container if it fails
ports:
- "5432:5432" # Map host port 5432 to container port 5432
environment:
POSTGRES_USER: REPLACE_ME # Replace with your desired username
POSTGRES_PASSWORD: REPLACE_ME # Replace with a strong password
POSTGRES_DB: test_database # The database name
volumes:
- db_data:/var/lib/postgresql/data # Persist data even if the container is stopped
# Redis service (for caching or messaging)
redis:
image: redis:latest # Use the latest Redis image
container_name: test-redis
restart: always
ports:
- "6379:6379" # Map host port 6379 to container port 6379
# Application service (the service you are testing)
app:
build:
context: . # Path to the application's Dockerfile
dockerfile: Dockerfile # Name of the Dockerfile
container_name: test-app
restart: always
ports:
- "8080:8080" # Map host port 8080 to container port 8080
environment:
DATABASE_URL: "postgresql://REPLACE_ME:REPLACE_ME@db:5432/test_database" # Database connection string
REDIS_URL: "redis://redis:6379" # Redis connection string
YOUR_APP_CONFIG: YOUR_VALUE_HERE # Example: App-specific configuration
depends_on:
- db # Ensure the database is running before starting the application
- redis # Ensure redis is running before starting the application
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"] # Example: Health check endpoint
interval: 30s
timeout: 10s
retries: 3
# Define named volumes for data persistence
volumes:
db_data:

View File

@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""
Example Python test script that uses the test environment.
This script demonstrates how to interact with services running in the test environment,
managed by the test-environment-manager plugin.
It assumes that services like a database or message queue are running within Docker containers.
"""
import os
import time
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def connect_to_database(host, port, user, password, database):
"""
Attempts to connect to the database.
Args:
host (str): Database host.
port (int): Database port.
user (str): Database user.
password (str): Database password.
database (str): Database name.
Returns:
bool: True if connection successful, False otherwise.
"""
try:
import psycopg2 # Example: PostgreSQL
conn = psycopg2.connect(host=host, port=port, user=user, password=password, database=database)
conn.close()
logging.info("Successfully connected to the database.")
return True
except ImportError:
logging.error("psycopg2 (PostgreSQL driver) is not installed. Please install it: pip install psycopg2-binary")
return False
except Exception as e:
logging.error(f"Failed to connect to the database: {e}")
return False
def send_message(queue_host, queue_port, message):
"""
Sends a message to a message queue.
Args:
queue_host (str): Message queue host.
queue_port (int): Message queue port.
message (str): Message to send.
Returns:
bool: True if message sent successfully, False otherwise.
"""
try:
import redis # Example: Redis
r = redis.Redis(host=queue_host, port=queue_port)
r.publish('test_channel', message)
logging.info(f"Successfully sent message to the queue: {message}")
return True
except ImportError:
logging.error("redis is not installed. Please install it: pip install redis")
return False
except Exception as e:
logging.error(f"Failed to send message to the queue: {e}")
return False
def main():
"""
Main function to demonstrate test environment interaction.
"""
database_host = os.environ.get("DATABASE_HOST", "localhost")
database_port = int(os.environ.get("DATABASE_PORT", "5432"))
database_user = os.environ.get("DATABASE_USER", "test_user")
database_password = os.environ.get("DATABASE_PASSWORD", "test_password")
database_name = os.environ.get("DATABASE_NAME", "test_db")
queue_host = os.environ.get("QUEUE_HOST", "localhost")
queue_port = int(os.environ.get("QUEUE_PORT", "6379"))
# Example usage:
if connect_to_database(database_host, database_port, database_user, database_password, database_name):
logging.info("Database connection test passed.")
else:
logging.error("Database connection test failed.")
if send_message(queue_host, queue_port, "Hello from the test environment!"):
logging.info("Message queue test passed.")
else:
logging.error("Message queue test failed.")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,35 @@
// This is a placeholder image. Replace it with a real diagram illustrating the architecture of a typical test environment.
//
// Consider including the following elements:
// - Client application
// - Test environment manager (the plugin)
// - Docker Compose
// - Testcontainers
// - Databases (e.g., PostgreSQL, MySQL)
// - Message queues (e.g., RabbitMQ, Kafka)
// - Other services (e.g., Redis, Memcached)
// - Environment variables
// - Network connections
//
// The diagram should illustrate how the test environment manager orchestrates these components to create isolated and reproducible test environments.
//
// Example (textual representation, to be visually diagrammed):
//
// [Client Application] --> [Test Environment Manager]
//
// [Test Environment Manager] --> [Docker Compose] --> [Containers (Database, Message Queue, Other Services)]
//
// [Test Environment Manager] --> [Testcontainers] --> [Containers (Database, Message Queue, Other Services)]
//
// [Test Environment Manager] <--> [Environment Variables]
//
// Consider using a diagramming tool like draw.io, Lucidchart, or similar to create the visual representation.
// Ensure the diagram is clear, concise, and easy to understand.
//
// When replacing this placeholder, ensure the filename is "test_environment_diagram.png".
//
// You can use a tool like ImageMagick to optimize the image for web use:
// `convert test_environment_diagram_original.png -strip -interlace Plane -gaussian-blur 0.05 -quality 85% test_environment_diagram.png`
//
// This placeholder image is a 1x1 transparent pixel. It is here to meet the requirement for a .png file.
iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=

View File

@@ -0,0 +1,9 @@
# References
Bundled resources for test-environment-manager skill
- [ ] docker_compose_best_practices.md: Documentation on best practices for writing Docker Compose files for test environments.
- [ ] testcontainers_integration_guide.md: Guide on integrating Testcontainers for programmatic container management.
- [ ] environment_variable_management.md: Documentation on managing environment variables for test environments.
- [ ] example_docker_compose.yml: Example Docker Compose file for a test environment.
- [ ] troubleshooting.md: Common troubleshooting steps for test environment issues.

View File

@@ -0,0 +1,8 @@
# Scripts
Bundled resources for test-environment-manager skill
- [ ] setup_environment.sh: Script to set up the test environment using Docker Compose and Testcontainers.
- [ ] teardown_environment.sh: Script to tear down the test environment, cleaning up containers and resources.
- [ ] health_check.sh: Script to perform health checks on the services running in the test environment.
- [ ] configure_env_vars.py: Python script to configure environment variables for the test environment.