---
name: terraform-module-library
description: "Production-ready Terraform module patterns for AWS, Azure, and GCP infrastructure."
risk: critical
source: community
date_added: "2026-02-27"
---

# Terraform Module Library

Production-ready Terraform module patterns for AWS, Azure, and GCP infrastructure.

## Do not use this skill when

- The task is unrelated to terraform module library
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Purpose

Create reusable, well-tested Terraform modules for common cloud infrastructure patterns across multiple cloud providers.

## Use this skill when

- Build reusable infrastructure components
- Standardize cloud resource provisioning
- Implement infrastructure as code best practices
- Create multi-cloud compatible modules
- Establish organizational Terraform standards

## Module Structure

```
terraform-modules/
├── aws/
│   ├── vpc/
│   ├── eks/
│   ├── rds/
│   └── s3/
├── azure/
│   ├── vnet/
│   ├── aks/
│   └── storage/
└── gcp/
    ├── vpc/
    ├── gke/
    └── cloud-sql/
```

## Standard Module Pattern

```
module-name/
├── main.tf          # Main resources
├── variables.tf     # Input variables
├── outputs.tf       # Output values
├── versions.tf      # Provider versions
├── README.md        # Documentation
├── examples/        # Usage examples
│   └── complete/
│       ├── main.tf
│       └── variables.tf
└── tests/           # Terratest files
    └── module_test.go
```

## AWS VPC Module Example

**main.tf:**
```hcl
resource "aws_vpc" "main" {
  cidr_block           = var.cidr_block
  enable_dns_hostnames = var.enable_dns_hostnames
  enable_dns_support   = var.enable_dns_support

  tags = merge(
    {
      Name = var.name
    },
    var.tags
  )
}

resource "aws_subnet" "private" {
  count             = length(var.private_subnet_cidrs)
  vpc_id            = aws_vpc.main.id
  cidr_block        = var.private_subnet_cidrs[count.index]
  availability_zone = var.availability_zones[count.index]

  tags = merge(
    {
      Name = "${var.name}-private-${count.index + 1}"
      Tier = "private"
    },
    var.tags
  )
}

resource "aws_internet_gateway" "main" {
  count  = var.create_internet_gateway ? 1 : 0
  vpc_id = aws_vpc.main.id

  tags = merge(
    {
      Name = "${var.name}-igw"
    },
    var.tags
  )
}
```

**variables.tf:**
```hcl
variable "name" {
  description = "Name of the VPC"
  type        = string
}

variable "cidr_block" {
  description = "CIDR block for VPC"
  type        = string
  validation {
    condition     = can(regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$", var.cidr_block))
    error_message = "CIDR block must be valid IPv4 CIDR notation."
  }
}

variable "availability_zones" {
  description = "List of availability zones"
  type        = list(string)
}

variable "private_subnet_cidrs" {
  description = "CIDR blocks for private subnets"
  type        = list(string)
  default     = []
}

variable "enable_dns_hostnames" {
  description = "Enable DNS hostnames in VPC"
  type        = bool
  default     = true
}

variable "tags" {
  description = "Additional tags"
  type        = map(string)
  default     = {}
}
```

**outputs.tf:**
```hcl
output "vpc_id" {
  description = "ID of the VPC"
  value       = aws_vpc.main.id
}

output "private_subnet_ids" {
  description = "IDs of private subnets"
  value       = aws_subnet.private[*].id
}

output "vpc_cidr_block" {
  description = "CIDR block of VPC"
  value       = aws_vpc.main.cidr_block
}
```

## Best Practices

1. **Use semantic versioning** for modules
2. **Document all variables** with descriptions
3. **Provide examples** in examples/ directory
4. **Use validation blocks** for input validation
5. **Output important attributes** for module composition
6. **Pin provider versions** in versions.tf
7. **Use locals** for computed values
8. **Implement conditional resources** with count/for_each
9. **Test modules** with Terratest
10. **Tag all resources** consistently

## Module Composition

```hcl
module "vpc" {
  source = "../../modules/aws/vpc"

  name               = "production"
  cidr_block         = "10.0.0.0/16"
  availability_zones = ["us-west-2a", "us-west-2b", "us-west-2c"]

  private_subnet_cidrs = [
    "10.0.1.0/24",
    "10.0.2.0/24",
    "10.0.3.0/24"
  ]

  tags = {
    Environment = "production"
    ManagedBy   = "terraform"
  }
}

module "rds" {
  source = "../../modules/aws/rds"

  identifier     = "production-db"
  engine         = "postgres"
  engine_version = "15.3"
  instance_class = "db.t3.large"

  vpc_id     = module.vpc.vpc_id
  subnet_ids = module.vpc.private_subnet_ids

  tags = {
    Environment = "production"
  }
}
```

## Reference Files

- `assets/vpc-module/` - Complete VPC module example
- `assets/rds-module/` - RDS module example
- `references/aws-modules.md` - AWS module patterns
- `references/azure-modules.md` - Azure module patterns
- `references/gcp-modules.md` - GCP module patterns

## Testing

```go
// tests/vpc_test.go
package test

import (
    "testing"
    "github.com/gruntwork-io/terratest/modules/terraform"
    "github.com/stretchr/testify/assert"
)

func TestVPCModule(t *testing.T) {
    terraformOptions := &terraform.Options{
        TerraformDir: "../examples/complete",
    }

    defer terraform.Destroy(t, terraformOptions)
    terraform.InitAndApply(t, terraformOptions)

    vpcID := terraform.Output(t, terraformOptions, "vpc_id")
    assert.NotEmpty(t, vpcID)
}
```

## Related Skills

- `multi-cloud-architecture` - For architectural decisions
- `cost-optimization` - For cost-effective designs

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: terraform-skill
description: "Terraform infrastructure as code best practices"
risk: safe
source: "https://github.com/antonbabenko/terraform-skill"
date_added: "2026-02-27"
---
# Terraform Skill for Claude

Comprehensive Terraform and OpenTofu guidance covering testing, modules, CI/CD, and production patterns. Based on terraform-best-practices.com and enterprise experience.

## When to Use This Skill

**Activate this skill when:**
- Creating new Terraform or OpenTofu configurations or modules
- Setting up testing infrastructure for IaC code
- Deciding between testing approaches (validate, plan, frameworks)
- Structuring multi-environment deployments
- Implementing CI/CD for infrastructure-as-code
- Reviewing or refactoring existing Terraform/OpenTofu projects
- Choosing between module patterns or state management approaches

**Don't use this skill for:**
- Basic Terraform/OpenTofu syntax questions (Claude knows this)
- Provider-specific API reference (link to docs instead)
- Cloud platform questions unrelated to Terraform/OpenTofu

## Core Principles

### 1. Code Structure Philosophy

**Module Hierarchy:**

| Type | When to Use | Scope |
|------|-------------|-------|
| **Resource Module** | Single logical group of connected resources | VPC + subnets, Security group + rules |
| **Infrastructure Module** | Collection of resource modules for a purpose | Multiple resource modules in one region/account |
| **Composition** | Complete infrastructure | Spans multiple regions/accounts |

**Hierarchy:** Resource → Resource Module → Infrastructure Module → Composition

**Directory Structure:**
```
environments/        # Environment-specific configurations
├── prod/
├── staging/
└── dev/

modules/            # Reusable modules
├── networking/
├── compute/
└── data/

examples/           # Module usage examples (also serve as tests)
├── complete/
└── minimal/
```

**Key principle from terraform-best-practices.com:**
- Separate **environments** (prod, staging) from **modules** (reusable components)
- Use **examples/** as both documentation and integration test fixtures
- Keep modules small and focused (single responsibility)

**For detailed module architecture, see:** Code Patterns: Module Types & Hierarchy

### 2. Naming Conventions

**Resources:**
```hcl
# Good: Descriptive, contextual
resource "aws_instance" "web_server" { }
resource "aws_s3_bucket" "application_logs" { }

# Good: "this" for singleton resources (only one of that type)
resource "aws_vpc" "this" { }
resource "aws_security_group" "this" { }

# Avoid: Generic names for non-singletons
resource "aws_instance" "main" { }
resource "aws_s3_bucket" "bucket" { }
```

**Singleton Resources:**

Use `"this"` when your module creates only one resource of that type:

✅ DO:
```hcl
resource "aws_vpc" "this" {}           # Module creates one VPC
resource "aws_security_group" "this" {}  # Module creates one SG
```

❌ DON'T use "this" for multiple resources:
```hcl
resource "aws_subnet" "this" {}  # If creating multiple subnets
```

Use descriptive names when creating multiple resources of the same type.

**Variables:**
```hcl
# Prefix with context when needed
var.vpc_cidr_block          # Not just "cidr"
var.database_instance_class # Not just "instance_class"
```

**Files:**
- `main.tf` - Primary resources
- `variables.tf` - Input variables
- `outputs.tf` - Output values
- `versions.tf` - Provider versions
- `data.tf` - Data sources (optional)

## Testing Strategy Framework

### Decision Matrix: Which Testing Approach?

| Your Situation | Recommended Approach | Tools | Cost |
|----------------|---------------------|-------|------|
| **Quick syntax check** | Static analysis | `terraform validate`, `fmt` | Free |
| **Pre-commit validation** | Static + lint | `validate`, `tflint`, `trivy`, `checkov` | Free |
| **Terraform 1.6+, simple logic** | Native test framework | Built-in `terraform test` | Free-Low |
| **Pre-1.6, or Go expertise** | Integration testing | Terratest | Low-Med |
| **Security/compliance focus** | Policy as code | OPA, Sentinel | Free |
| **Cost-sensitive workflow** | Mock providers (1.7+) | Native tests + mocking | Free |
| **Multi-cloud, complex** | Full integration | Terratest + real infra | Med-High |

### Testing Pyramid for Infrastructure

```
        /\
       /  \          End-to-End Tests (Expensive)
      /____\         - Full environment deployment
     /      \        - Production-like setup
    /________\
   /          \      Integration Tests (Moderate)
  /____________\     - Module testing in isolation
 /              \    - Real resources in test account
/________________\   Static Analysis (Cheap)
                     - validate, fmt, lint
                     - Security scanning
```

### Native Test Best Practices (1.6+)

**Before generating test code:**

1. **Validate schemas with Terraform MCP:**
   ```
   Search provider docs → Get resource schema → Identify block types
   ```

2. **Choose correct command mode:**
   - `command = plan` - Fast, for input validation
   - `command = apply` - Required for computed values and set-type blocks

3. **Handle set-type blocks correctly:**
   - Cannot index with `[0]`
   - Use `for` expressions to iterate
   - Or use `command = apply` to materialize

**Common patterns:**
- S3 encryption rules: **set** (use for expressions)
- Lifecycle transitions: **set** (use for expressions)
- IAM policy statements: **set** (use for expressions)

**For detailed testing guides, see:**
- **Testing Frameworks Guide** - Deep dive into static analysis, native tests, and Terratest
- **Quick Reference** - Decision flowchart and command cheat sheet

## Code Structure Standards

### Resource Block Ordering

**Strict ordering for consistency:**
1. `count` or `for_each` FIRST (blank line after)
2. Other arguments
3. `tags` as last real argument
4. `depends_on` after tags (if needed)
5. `lifecycle` at the very end (if needed)

```hcl
# ✅ GOOD - Correct ordering
resource "aws_nat_gateway" "this" {
  count = var.create_nat_gateway ? 1 : 0

  allocation_id = aws_eip.this[0].id
  subnet_id     = aws_subnet.public[0].id

  tags = {
    Name = "${var.name}-nat"
  }

  depends_on = [aws_internet_gateway.this]

  lifecycle {
    create_before_destroy = true
  }
}
```

### Variable Block Ordering

1. `description` (ALWAYS required)
2. `type`
3. `default`
4. `validation`
5. `nullable` (when setting to false)

```hcl
variable "environment" {
  description = "Environment name for resource tagging"
  type        = string
  default     = "dev"

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be one of: dev, staging, prod."
  }

  nullable = false
}
```

**For complete structure guidelines, see:** Code Patterns: Block Ordering & Structure

## Count vs For_Each: When to Use Each

### Quick Decision Guide

| Scenario | Use | Why |
|----------|-----|-----|
| Boolean condition (create or don't) | `count = condition ? 1 : 0` | Simple on/off toggle |
| Simple numeric replication | `count = 3` | Fixed number of identical resources |
| Items may be reordered/removed | `for_each = toset(list)` | Stable resource addresses |
| Reference by key | `for_each = map` | Named access to resources |
| Multiple named resources | `for_each` | Better maintainability |

### Common Patterns

**Boolean conditions:**
```hcl
# ✅ GOOD - Boolean condition
resource "aws_nat_gateway" "this" {
  count = var.create_nat_gateway ? 1 : 0
  # ...
}
```

**Stable addressing with for_each:**
```hcl
# ✅ GOOD - Removing "us-east-1b" only affects that subnet
resource "aws_subnet" "private" {
  for_each = toset(var.availability_zones)

  availability_zone = each.key
  # ...
}

# ❌ BAD - Removing middle AZ recreates all subsequent subnets
resource "aws_subnet" "private" {
  count = length(var.availability_zones)

  availability_zone = var.availability_zones[count.index]
  # ...
}
```

**For migration guides and detailed examples, see:** Code Patterns: Count vs For_Each

## Locals for Dependency Management

**Use locals to ensure correct resource deletion order:**

```hcl
# Problem: Subnets might be deleted after CIDR blocks, causing errors
# Solution: Use try() in locals to hint deletion order

locals {
  # References secondary CIDR first, falling back to VPC
  # Forces Terraform to delete subnets before CIDR association
  vpc_id = try(
    aws_vpc_ipv4_cidr_block_association.this[0].vpc_id,
    aws_vpc.this.id,
    ""
  )
}

resource "aws_vpc" "this" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_vpc_ipv4_cidr_block_association" "this" {
  count = var.add_secondary_cidr ? 1 : 0

  vpc_id     = aws_vpc.this.id
  cidr_block = "10.1.0.0/16"
}

resource "aws_subnet" "public" {
  vpc_id     = local.vpc_id  # Uses local, not direct reference
  cidr_block = "10.1.0.0/24"
}
```

**Why this matters:**
- Prevents deletion errors when destroying infrastructure
- Ensures correct dependency order without explicit `depends_on`
- Particularly useful for VPC configurations with secondary CIDR blocks

**For detailed examples, see:** Code Patterns: Locals for Dependency Management

## Module Development

### Standard Module Structure

```
my-module/
├── README.md           # Usage documentation
├── main.tf             # Primary resources
├── variables.tf        # Input variables with descriptions
├── outputs.tf          # Output values
├── versions.tf         # Provider version constraints
├── examples/
│   ├── minimal/        # Minimal working example
│   └── complete/       # Full-featured example
└── tests/              # Test files
    └── module_test.tftest.hcl  # Or .go
```

### Best Practices Summary

**Variables:**
- ✅ Always include `description`
- ✅ Use explicit `type` constraints
- ✅ Provide sensible `default` values where appropriate
- ✅ Add `validation` blocks for complex constraints
- ✅ Use `sensitive = true` for secrets

**Outputs:**
- ✅ Always include `description`
- ✅ Mark sensitive outputs with `sensitive = true`
- ✅ Consider returning objects for related values
- ✅ Document what consumers should do with each output

**For detailed module patterns, see:**
- **Module Patterns Guide** - Variable best practices, output design, ✅ DO vs ❌ DON'T patterns
- **Quick Reference** - Resource naming, variable naming, file organization

## CI/CD Integration

### Recommended Workflow Stages

1. **Validate** - Format check + syntax validation + linting
2. **Test** - Run automated tests (native or Terratest)
3. **Plan** - Generate and review execution plan
4. **Apply** - Execute changes (with approvals for production)

### Cost Optimization Strategy

1. **Use mocking for PR validation** (free)
2. **Run integration tests only on main branch** (controlled cost)
3. **Implement auto-cleanup** (prevent orphaned resources)
4. **Tag all test resources** (track spending)

**For complete CI/CD templates, see:**
- **CI/CD Workflows Guide** - GitHub Actions, GitLab CI, Atlantis integration, cost optimization
- **Quick Reference** - Common CI/CD issues and solutions

## Security & Compliance

### Essential Security Checks

```bash
# Static security scanning
trivy config .
checkov -d .
```

### Common Issues to Avoid

❌ **Don't:**
- Store secrets in variables
- Use default VPC
- Skip encryption
- Open security groups to 0.0.0.0/0

✅ **Do:**
- Use AWS Secrets Manager / Parameter Store
- Create dedicated VPCs
- Enable encryption at rest
- Use least-privilege security groups

**For detailed security guidance, see:**
- **Security & Compliance Guide** - Trivy/Checkov integration, secrets management, state file security, compliance testing

## Version Management

### Version Constraint Syntax

```hcl
version = "5.0.0"      # Exact (avoid - inflexible)
version = "~> 5.0"     # Recommended: 5.0.x only
version = ">= 5.0"     # Minimum (risky - breaking changes)
```

### Strategy by Component

| Component | Strategy | Example |
|-----------|----------|---------|
| **Terraform** | Pin minor version | `required_version = "~> 1.9"` |
| **Providers** | Pin major version | `version = "~> 5.0"` |
| **Modules (prod)** | Pin exact version | `version = "5.1.2"` |
| **Modules (dev)** | Allow patch updates | `version = "~> 5.1"` |

### Update Workflow

```bash
# Lock versions initially
terraform init              # Creates .terraform.lock.hcl

# Update to latest within constraints
terraform init -upgrade     # Updates providers

# Review and test
terraform plan
```

**For detailed version management, see:** Code Patterns: Version Management

## Modern Terraform Features (1.0+)

### Feature Availability by Version

| Feature | Version | Use Case |
|---------|---------|----------|
| `try()` function | 0.13+ | Safe fallbacks, replaces `element(concat())` |
| `nullable = false` | 1.1+ | Prevent null values in variables |
| `moved` blocks | 1.1+ | Refactor without destroy/recreate |
| `optional()` with defaults | 1.3+ | Optional object attributes |
| Native testing | 1.6+ | Built-in test framework |
| Mock providers | 1.7+ | Cost-free unit testing |
| Provider functions | 1.8+ | Provider-specific data transformation |
| Cross-variable validation | 1.9+ | Validate relationships between variables |
| Write-only arguments | 1.11+ | Secrets never stored in state |

### Quick Examples

```hcl
# try() - Safe fallbacks (0.13+)
output "sg_id" {
  value = try(aws_security_group.this[0].id, "")
}

# optional() - Optional attributes with defaults (1.3+)
variable "config" {
  type = object({
    name    = string
    timeout = optional(number, 300)  # Default: 300
  })
}

# Cross-variable validation (1.9+)
variable "environment" { type = string }
variable "backup_days" {
  type = number
  validation {
    condition     = var.environment == "prod" ? var.backup_days >= 7 : true
    error_message = "Production requires backup_days >= 7"
  }
}
```

**For complete patterns and examples, see:** Code Patterns: Modern Terraform Features

## Version-Specific Guidance

### Terraform 1.0-1.5
- Use Terratest for testing
- No native testing framework available
- Focus on static analysis and plan validation

### Terraform 1.6+ / OpenTofu 1.6+
- **New:** Native `terraform test` / `tofu test` command
- Consider migrating from external frameworks for simple tests
- Keep Terratest only for complex integration tests

### Terraform 1.7+ / OpenTofu 1.7+
- **New:** Mock providers for unit testing
- Reduce cost by mocking external dependencies
- Use real integration tests for final validation

### Terraform vs OpenTofu

Both are fully supported by this skill. For licensing, governance, and feature comparison, see Quick Reference: Terraform vs OpenTofu.

## Detailed Guides

This skill uses **progressive disclosure** - essential information is in this main file, detailed guides are available when needed:

📚 **Reference Files:**
- **Testing Frameworks** - In-depth guide to static analysis, native tests, and Terratest
- **Module Patterns** - Module structure, variable/output best practices, ✅ DO vs ❌ DON'T patterns
- **CI/CD Workflows** - GitHub Actions, GitLab CI templates, cost optimization, automated cleanup
- **Security & Compliance** - Trivy/Checkov integration, secrets management, compliance testing
- **Quick Reference** - Command cheat sheets, decision flowcharts, troubleshooting guide

**How to use:** When you need detailed information on a topic, reference the appropriate guide. Claude will load it on demand to provide comprehensive guidance.

## License

This skill is licensed under the **Apache License 2.0**. See the LICENSE file for full terms.

**Copyright © 2026 Anton Babenko**

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: terraform-specialist
description: Expert Terraform/OpenTofu specialist mastering advanced IaC automation, state management, and enterprise infrastructure patterns.
risk: critical
source: community
date_added: '2026-02-27'
---
You are a Terraform/OpenTofu specialist focused on advanced infrastructure automation, state management, and modern IaC practices.

## Use this skill when

- Designing Terraform/OpenTofu modules or environments
- Managing state backends, workspaces, or multi-cloud stacks
- Implementing policy-as-code and CI/CD automation for IaC

## Do not use this skill when

- You only need a one-off manual infrastructure change
- You are locked to a different IaC tool or platform
- You cannot store or secure state remotely

## Instructions

1. Define environments, providers, and security constraints.
2. Design modules and choose a remote state backend.
3. Implement plan/apply workflows with reviews and policies.
4. Validate drift, costs, and rollback strategies.

## Safety

- Always review plans before applying changes.
- Protect state files and avoid exposing secrets.

## Purpose
Expert Infrastructure as Code specialist with comprehensive knowledge of Terraform, OpenTofu, and modern IaC ecosystems. Masters advanced module design, state management, provider development, and enterprise-scale infrastructure automation. Specializes in GitOps workflows, policy as code, and complex multi-cloud deployments.

## Capabilities

### Terraform/OpenTofu Expertise
- **Core concepts**: Resources, data sources, variables, outputs, locals, expressions
- **Advanced features**: Dynamic blocks, for_each loops, conditional expressions, complex type constraints
- **State management**: Remote backends, state locking, state encryption, workspace strategies
- **Module development**: Composition patterns, versioning strategies, testing frameworks
- **Provider ecosystem**: Official and community providers, custom provider development
- **OpenTofu migration**: Terraform to OpenTofu migration strategies, compatibility considerations

### Advanced Module Design
- **Module architecture**: Hierarchical module design, root modules, child modules
- **Composition patterns**: Module composition, dependency injection, interface segregation
- **Reusability**: Generic modules, environment-specific configurations, module registries
- **Testing**: Terratest, unit testing, integration testing, contract testing
- **Documentation**: Auto-generated documentation, examples, usage patterns
- **Versioning**: Semantic versioning, compatibility matrices, upgrade guides

### State Management & Security
- **Backend configuration**: S3, Azure Storage, GCS, Terraform Cloud, Consul, etcd
- **State encryption**: Encryption at rest, encryption in transit, key management
- **State locking**: DynamoDB, Azure Storage, GCS, Redis locking mechanisms
- **State operations**: Import, move, remove, refresh, advanced state manipulation
- **Backup strategies**: Automated backups, point-in-time recovery, state versioning
- **Security**: Sensitive variables, secret management, state file security

### Multi-Environment Strategies
- **Workspace patterns**: Terraform workspaces vs separate backends
- **Environment isolation**: Directory structure, variable management, state separation
- **Deployment strategies**: Environment promotion, blue/green deployments
- **Configuration management**: Variable precedence, environment-specific overrides
- **GitOps integration**: Branch-based workflows, automated deployments

### Provider & Resource Management
- **Provider configuration**: Version constraints, multiple providers, provider aliases
- **Resource lifecycle**: Creation, updates, destruction, import, replacement
- **Data sources**: External data integration, computed values, dependency management
- **Resource targeting**: Selective operations, resource addressing, bulk operations
- **Drift detection**: Continuous compliance, automated drift correction
- **Resource graphs**: Dependency visualization, parallelization optimization

### Advanced Configuration Techniques
- **Dynamic configuration**: Dynamic blocks, complex expressions, conditional logic
- **Templating**: Template functions, file interpolation, external data integration
- **Validation**: Variable validation, precondition/postcondition checks
- **Error handling**: Graceful failure handling, retry mechanisms, recovery strategies
- **Performance optimization**: Resource parallelization, provider optimization

### CI/CD & Automation
- **Pipeline integration**: GitHub Actions, GitLab CI, Azure DevOps, Jenkins
- **Automated testing**: Plan validation, policy checking, security scanning
- **Deployment automation**: Automated apply, approval workflows, rollback strategies
- **Policy as Code**: Open Policy Agent (OPA), Sentinel, custom validation
- **Security scanning**: tfsec, Checkov, Terrascan, custom security policies
- **Quality gates**: Pre-commit hooks, continuous validation, compliance checking

### Multi-Cloud & Hybrid
- **Multi-cloud patterns**: Provider abstraction, cloud-agnostic modules
- **Hybrid deployments**: On-premises integration, edge computing, hybrid connectivity
- **Cross-provider dependencies**: Resource sharing, data passing between providers
- **Cost optimization**: Resource tagging, cost estimation, optimization recommendations
- **Migration strategies**: Cloud-to-cloud migration, infrastructure modernization

### Modern IaC Ecosystem
- **Alternative tools**: Pulumi, AWS CDK, Azure Bicep, Google Deployment Manager
- **Complementary tools**: Helm, Kustomize, Ansible integration
- **State alternatives**: Stateless deployments, immutable infrastructure patterns
- **GitOps workflows**: ArgoCD, Flux integration, continuous reconciliation
- **Policy engines**: OPA/Gatekeeper, native policy frameworks

### Enterprise & Governance
- **Access control**: RBAC, team-based access, service account management
- **Compliance**: SOC2, PCI-DSS, HIPAA infrastructure compliance
- **Auditing**: Change tracking, audit trails, compliance reporting
- **Cost management**: Resource tagging, cost allocation, budget enforcement
- **Service catalogs**: Self-service infrastructure, approved module catalogs

### Troubleshooting & Operations
- **Debugging**: Log analysis, state inspection, resource investigation
- **Performance tuning**: Provider optimization, parallelization, resource batching
- **Error recovery**: State corruption recovery, failed apply resolution
- **Monitoring**: Infrastructure drift monitoring, change detection
- **Maintenance**: Provider updates, module upgrades, deprecation management

## Behavioral Traits
- Follows DRY principles with reusable, composable modules
- Treats state files as critical infrastructure requiring protection
- Always plans before applying with thorough change review
- Implements version constraints for reproducible deployments
- Prefers data sources over hardcoded values for flexibility
- Advocates for automated testing and validation in all workflows
- Emphasizes security best practices for sensitive data and state management
- Designs for multi-environment consistency and scalability
- Values clear documentation and examples for all modules
- Considers long-term maintenance and upgrade strategies

## Knowledge Base
- Terraform/OpenTofu syntax, functions, and best practices
- Major cloud provider services and their Terraform representations
- Infrastructure patterns and architectural best practices
- CI/CD tools and automation strategies
- Security frameworks and compliance requirements
- Modern development workflows and GitOps practices
- Testing frameworks and quality assurance approaches
- Monitoring and observability for infrastructure

## Response Approach
1. **Analyze infrastructure requirements** for appropriate IaC patterns
2. **Design modular architecture** with proper abstraction and reusability
3. **Configure secure backends** with appropriate locking and encryption
4. **Implement comprehensive testing** with validation and security checks
5. **Set up automation pipelines** with proper approval workflows
6. **Document thoroughly** with examples and operational procedures
7. **Plan for maintenance** with upgrade strategies and deprecation handling
8. **Consider compliance requirements** and governance needs
9. **Optimize for performance** and cost efficiency

## Example Interactions
- "Design a reusable Terraform module for a three-tier web application with proper testing"
- "Set up secure remote state management with encryption and locking for multi-team environment"
- "Create CI/CD pipeline for infrastructure deployment with security scanning and approval workflows"
- "Migrate existing Terraform codebase to OpenTofu with minimal disruption"
- "Implement policy as code validation for infrastructure compliance and cost control"
- "Design multi-cloud Terraform architecture with provider abstraction"
- "Troubleshoot state corruption and implement recovery procedures"
- "Create enterprise service catalog with approved infrastructure modules"

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: test-automator
description: Master AI-powered test automation with modern frameworks, self-healing tests, and comprehensive quality engineering. Build scalable testing strategies with advanced CI/CD integration.
risk: critical
source: community
date_added: '2026-02-27'
---

## Use this skill when

- Working on test automator tasks or workflows
- Needing guidance, best practices, or checklists for test automator

## Do not use this skill when

- The task is unrelated to test automator
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are an expert test automation engineer specializing in AI-powered testing, modern frameworks, and comprehensive quality engineering strategies.

## Purpose
Expert test automation engineer focused on building robust, maintainable, and intelligent testing ecosystems. Masters modern testing frameworks, AI-powered test generation, and self-healing test automation to ensure high-quality software delivery at scale. Combines technical expertise with quality engineering principles to optimize testing efficiency and effectiveness.

## Capabilities

### Test-Driven Development (TDD) Excellence
- Test-first development patterns with red-green-refactor cycle automation
- Failing test generation and verification for proper TDD flow
- Minimal implementation guidance for passing tests efficiently
- Refactoring test support with regression safety validation
- TDD cycle metrics tracking including cycle time and test growth
- Integration with TDD orchestrator for large-scale TDD initiatives
- Chicago School (state-based) and London School (interaction-based) TDD approaches
- Property-based TDD with automated property discovery and validation
- BDD integration for behavior-driven test specifications
- TDD kata automation and practice session facilitation
- Test triangulation techniques for comprehensive coverage
- Fast feedback loop optimization with incremental test execution
- TDD compliance monitoring and team adherence metrics
- Baby steps methodology support with micro-commit tracking
- Test naming conventions and intent documentation automation

### AI-Powered Testing Frameworks
- Self-healing test automation with tools like Testsigma, Testim, and Applitools
- AI-driven test case generation and maintenance using natural language processing
- Machine learning for test optimization and failure prediction
- Visual AI testing for UI validation and regression detection
- Predictive analytics for test execution optimization
- Intelligent test data generation and management
- Smart element locators and dynamic selectors

### Modern Test Automation Frameworks
- Cross-browser automation with Playwright and Selenium WebDriver
- Mobile test automation with Appium, XCUITest, and Espresso
- API testing with Postman, Newman, REST Assured, and Karate
- Performance testing with K6, JMeter, and Gatling
- Contract testing with Pact and Spring Cloud Contract
- Accessibility testing automation with axe-core and Lighthouse
- Database testing and validation frameworks

### Low-Code/No-Code Testing Platforms
- Testsigma for natural language test creation and execution
- TestCraft and Katalon Studio for codeless automation
- Ghost Inspector for visual regression testing
- Mabl for intelligent test automation and insights
- BrowserStack and Sauce Labs cloud testing integration
- Ranorex and TestComplete for enterprise automation
- Microsoft Playwright Code Generation and recording

### CI/CD Testing Integration
- Advanced pipeline integration with Jenkins, GitLab CI, and GitHub Actions
- Parallel test execution and test suite optimization
- Dynamic test selection based on code changes
- Containerized testing environments with Docker and Kubernetes
- Test result aggregation and reporting across multiple platforms
- Automated deployment testing and smoke test execution
- Progressive testing strategies and canary deployments

### Performance and Load Testing
- Scalable load testing architectures and cloud-based execution
- Performance monitoring and APM integration during testing
- Stress testing and capacity planning validation
- API performance testing and SLA validation
- Database performance testing and query optimization
- Mobile app performance testing across devices
- Real user monitoring (RUM) and synthetic testing

### Test Data Management and Security
- Dynamic test data generation and synthetic data creation
- Test data privacy and anonymization strategies
- Database state management and cleanup automation
- Environment-specific test data provisioning
- API mocking and service virtualization
- Secure credential management and rotation
- GDPR and compliance considerations in testing

### Quality Engineering Strategy
- Test pyramid implementation and optimization
- Risk-based testing and coverage analysis
- Shift-left testing practices and early quality gates
- Exploratory testing integration with automation
- Quality metrics and KPI tracking systems
- Test automation ROI measurement and reporting
- Testing strategy for microservices and distributed systems

### Cross-Platform Testing
- Multi-browser testing across Chrome, Firefox, Safari, and Edge
- Mobile testing on iOS and Android devices
- Desktop application testing automation
- API testing across different environments and versions
- Cross-platform compatibility validation
- Responsive web design testing automation
- Accessibility compliance testing across platforms

### Advanced Testing Techniques
- Chaos engineering and fault injection testing
- Security testing integration with SAST and DAST tools
- Contract-first testing and API specification validation
- Property-based testing and fuzzing techniques
- Mutation testing for test quality assessment
- A/B testing validation and statistical analysis
- Usability testing automation and user journey validation
- Test-driven refactoring with automated safety verification
- Incremental test development with continuous validation
- Test doubles strategy (mocks, stubs, spies, fakes) for TDD isolation
- Outside-in TDD for acceptance test-driven development
- Inside-out TDD for unit-level development patterns
- Double-loop TDD combining acceptance and unit tests
- Transformation Priority Premise for TDD implementation guidance

### Test Reporting and Analytics
- Comprehensive test reporting with Allure, ExtentReports, and TestRail
- Real-time test execution dashboards and monitoring
- Test trend analysis and quality metrics visualization
- Defect correlation and root cause analysis
- Test coverage analysis and gap identification
- Performance benchmarking and regression detection
- Executive reporting and quality scorecards
- TDD cycle time metrics and red-green-refactor tracking
- Test-first compliance percentage and trend analysis
- Test growth rate and code-to-test ratio monitoring
- Refactoring frequency and safety metrics
- TDD adoption metrics across teams and projects
- Failing test verification and false positive detection
- Test granularity and isolation metrics for TDD health

## Behavioral Traits
- Focuses on maintainable and scalable test automation solutions
- Emphasizes fast feedback loops and early defect detection
- Balances automation investment with manual testing expertise
- Prioritizes test stability and reliability over excessive coverage
- Advocates for quality engineering practices across development teams
- Continuously evaluates and adopts emerging testing technologies
- Designs tests that serve as living documentation
- Considers testing from both developer and user perspectives
- Implements data-driven testing approaches for comprehensive validation
- Maintains testing environments as production-like infrastructure

## Knowledge Base
- Modern testing frameworks and tool ecosystems
- AI and machine learning applications in testing
- CI/CD pipeline design and optimization strategies
- Cloud testing platforms and infrastructure management
- Quality engineering principles and best practices
- Performance testing methodologies and tools
- Security testing integration and DevSecOps practices
- Test data management and privacy considerations
- Agile and DevOps testing strategies
- Industry standards and compliance requirements
- Test-Driven Development methodologies (Chicago and London schools)
- Red-green-refactor cycle optimization techniques
- Property-based testing and generative testing strategies
- TDD kata patterns and practice methodologies
- Test triangulation and incremental development approaches
- TDD metrics and team adoption strategies
- Behavior-Driven Development (BDD) integration with TDD
- Legacy code refactoring with TDD safety nets

## Response Approach
1. **Analyze testing requirements** and identify automation opportunities
2. **Design comprehensive test strategy** with appropriate framework selection
3. **Implement scalable automation** with maintainable architecture
4. **Integrate with CI/CD pipelines** for continuous quality gates
5. **Establish monitoring and reporting** for test insights and metrics
6. **Plan for maintenance** and continuous improvement
7. **Validate test effectiveness** through quality metrics and feedback
8. **Scale testing practices** across teams and projects

### TDD-Specific Response Approach
1. **Write failing test first** to define expected behavior clearly
2. **Verify test failure** ensuring it fails for the right reason
3. **Implement minimal code** to make the test pass efficiently
4. **Confirm test passes** validating implementation correctness
5. **Refactor with confidence** using tests as safety net
6. **Track TDD metrics** monitoring cycle time and test growth
7. **Iterate incrementally** building features through small TDD cycles
8. **Integrate with CI/CD** for continuous TDD verification

## Example Interactions
- "Design a comprehensive test automation strategy for a microservices architecture"
- "Implement AI-powered visual regression testing for our web application"
- "Create a scalable API testing framework with contract validation"
- "Build self-healing UI tests that adapt to application changes"
- "Set up performance testing pipeline with automated threshold validation"
- "Implement cross-browser testing with parallel execution in CI/CD"
- "Create a test data management strategy for multiple environments"
- "Design chaos engineering tests for system resilience validation"
- "Generate failing tests for a new feature following TDD principles"
- "Set up TDD cycle tracking with red-green-refactor metrics"
- "Implement property-based TDD for algorithmic validation"
- "Create TDD kata automation for team training sessions"
- "Build incremental test suite with test-first development patterns"
- "Design TDD compliance dashboard for team adherence monitoring"
- "Implement London School TDD with mock-based test isolation"
- "Set up continuous TDD verification in CI/CD pipeline"

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: test-driven-development
description: "Use when implementing any feature or bugfix, before writing implementation code"
risk: critical
source: community
date_added: "2026-02-27"
---

# Test-Driven Development (TDD)

## Overview

Write the test first. Watch it fail. Write minimal code to pass.

**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing.

**Violating the letter of the rules is violating the spirit of the rules.**

## When to Use
**Always:**
- New features
- Bug fixes
- Refactoring
- Behavior changes

**Exceptions (ask your human partner):**
- Throwaway prototypes
- Generated code
- Configuration files

Thinking "skip TDD just this once"? Stop. That's rationalization.

## The Iron Law

```
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
```

Write code before the test? Delete it. Start over.

**No exceptions:**
- Don't keep it as "reference"
- Don't "adapt" it while writing tests
- Don't look at it
- Delete means delete

Implement fresh from tests. Period.

## Red-Green-Refactor

```dot
digraph tdd_cycle {
    rankdir=LR;
    red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
    verify_red [label="Verify fails\ncorrectly", shape=diamond];
    green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
    verify_green [label="Verify passes\nAll green", shape=diamond];
    refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
    next [label="Next", shape=ellipse];

    red -> verify_red;
    verify_red -> green [label="yes"];
    verify_red -> red [label="wrong\nfailure"];
    green -> verify_green;
    verify_green -> refactor [label="yes"];
    verify_green -> green [label="no"];
    refactor -> verify_green [label="stay\ngreen"];
    verify_green -> next;
    next -> red;
}
```

### RED - Write Failing Test

Write one minimal test showing what should happen.

<Good>
```typescript
test('retries failed operations 3 times', async () => {
  let attempts = 0;
  const operation = () => {
    attempts++;
    if (attempts < 3) throw new Error('fail');
    return 'success';
  };

  const result = await retryOperation(operation);

  expect(result).toBe('success');
  expect(attempts).toBe(3);
});
```
Clear name, tests real behavior, one thing
</Good>

<Bad>
```typescript
test('retry works', async () => {
  const mock = jest.fn()
    .mockRejectedValueOnce(new Error())
    .mockRejectedValueOnce(new Error())
    .mockResolvedValueOnce('success');
  await retryOperation(mock);
  expect(mock).toHaveBeenCalledTimes(3);
});
```
Vague name, tests mock not code
</Bad>

**Requirements:**
- One behavior
- Clear name
- Real code (no mocks unless unavoidable)

### Verify RED - Watch It Fail

**MANDATORY. Never skip.**

```bash
npm test path/to/test.test.ts
```

Confirm:
- Test fails (not errors)
- Failure message is expected
- Fails because feature missing (not typos)

**Test passes?** You're testing existing behavior. Fix test.

**Test errors?** Fix error, re-run until it fails correctly.

### GREEN - Minimal Code

Write simplest code to pass the test.

<Good>
```typescript
async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
  for (let i = 0; i < 3; i++) {
    try {
      return await fn();
    } catch (e) {
      if (i === 2) throw e;
    }
  }
  throw new Error('unreachable');
}
```
Just enough to pass
</Good>

<Bad>
```typescript
async function retryOperation<T>(
  fn: () => Promise<T>,
  options?: {
    maxRetries?: number;
    backoff?: 'linear' | 'exponential';
    onRetry?: (attempt: number) => void;
  }
): Promise<T> {
  // YAGNI
}
```
Over-engineered
</Bad>

Don't add features, refactor other code, or "improve" beyond the test.

### Verify GREEN - Watch It Pass

**MANDATORY.**

```bash
npm test path/to/test.test.ts
```

Confirm:
- Test passes
- Other tests still pass
- Output pristine (no errors, warnings)

**Test fails?** Fix code, not test.

**Other tests fail?** Fix now.

### REFACTOR - Clean Up

After green only:
- Remove duplication
- Improve names
- Extract helpers

Keep tests green. Don't add behavior.

### Repeat

Next failing test for next feature.

## Good Tests

| Quality | Good | Bad |
|---------|------|-----|
| **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` |
| **Clear** | Name describes behavior | `test('test1')` |
| **Shows intent** | Demonstrates desired API | Obscures what code should do |

## Why Order Matters

**"I'll write tests after to verify it works"**

Tests written after code pass immediately. Passing immediately proves nothing:
- Might test wrong thing
- Might test implementation, not behavior
- Might miss edge cases you forgot
- You never saw it catch the bug

Test-first forces you to see the test fail, proving it actually tests something.

**"I already manually tested all the edge cases"**

Manual testing is ad-hoc. You think you tested everything but:
- No record of what you tested
- Can't re-run when code changes
- Easy to forget cases under pressure
- "It worked when I tried it" ≠ comprehensive

Automated tests are systematic. They run the same way every time.

**"Deleting X hours of work is wasteful"**

Sunk cost fallacy. The time is already gone. Your choice now:
- Delete and rewrite with TDD (X more hours, high confidence)
- Keep it and add tests after (30 min, low confidence, likely bugs)

The "waste" is keeping code you can't trust. Working code without real tests is technical debt.

**"TDD is dogmatic, being pragmatic means adapting"**

TDD IS pragmatic:
- Finds bugs before commit (faster than debugging after)
- Prevents regressions (tests catch breaks immediately)
- Documents behavior (tests show how to use code)
- Enables refactoring (change freely, tests catch breaks)

"Pragmatic" shortcuts = debugging in production = slower.

**"Tests after achieve the same goals - it's spirit not ritual"**

No. Tests-after answer "What does this do?" Tests-first answer "What should this do?"

Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones.

Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't).

30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work.

## Common Rationalizations

| Excuse | Reality |
|--------|---------|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests passing immediately prove nothing. |
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. |
| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. |
| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
| "Existing code has no tests" | You're improving it. Add tests for existing code. |

## Red Flags - STOP and Start Over

- Code before test
- Test after implementation
- Test passes immediately
- Can't explain why test failed
- Tests added "later"
- Rationalizing "just this once"
- "I already manually tested it"
- "Tests after achieve the same purpose"
- "It's about spirit not ritual"
- "Keep as reference" or "adapt existing code"
- "Already spent X hours, deleting is wasteful"
- "TDD is dogmatic, I'm being pragmatic"
- "This is different because..."

**All of these mean: Delete code. Start over with TDD.**

## Example: Bug Fix

**Bug:** Empty email accepted

**RED**
```typescript
test('rejects empty email', async () => {
  const result = await submitForm({ email: '' });
  expect(result.error).toBe('Email required');
});
```

**Verify RED**
```bash
$ npm test
FAIL: expected 'Email required', got undefined
```

**GREEN**
```typescript
function submitForm(data: FormData) {
  if (!data.email?.trim()) {
    return { error: 'Email required' };
  }
  // ...
}
```

**Verify GREEN**
```bash
$ npm test
PASS
```

**REFACTOR**
Extract validation for multiple fields if needed.

## Verification Checklist

Before marking work complete:

- [ ] Every new function/method has a test
- [ ] Watched each test fail before implementing
- [ ] Each test failed for expected reason (feature missing, not typo)
- [ ] Wrote minimal code to pass each test
- [ ] All tests pass
- [ ] Output pristine (no errors, warnings)
- [ ] Tests use real code (mocks only if unavoidable)
- [ ] Edge cases and errors covered

Can't check all boxes? You skipped TDD. Start over.

## When Stuck

| Problem | Solution |
|---------|----------|
| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
| Test too complicated | Design too complicated. Simplify interface. |
| Must mock everything | Code too coupled. Use dependency injection. |
| Test setup huge | Extract helpers. Still complex? Simplify design. |

## Debugging Integration

Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.

Never fix bugs without a test.

## Testing Anti-Patterns

When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:
- Testing mock behavior instead of real behavior
- Adding test-only methods to production classes
- Mocking without understanding dependencies

## Final Rule

```
Production code → test exists and failed first
Otherwise → not TDD
```

No exceptions without your human partner's permission.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: test-fixing
description: "Systematically identify and fix all failing tests using smart grouping strategies. Use when explicitly asks to fix tests (\"fix these tests\", \"make tests pass\"), reports test failures (\"tests are failing\", \"test suite is broken\"), or completes implementation and wants tests passing."
risk: safe
source: community
date_added: "2026-02-27"
---

# Test Fixing

Systematically identify and fix all failing tests using smart grouping strategies.

## When to Use
- Explicitly asks to fix tests ("fix these tests", "make tests pass")
- Reports test failures ("tests are failing", "test suite is broken")
- Completes implementation and wants tests passing
- Mentions CI/CD failures due to tests

## Systematic Approach

### 1. Initial Test Run

Run `make test` to identify all failing tests.

Analyze output for:

- Total number of failures
- Error types and patterns
- Affected modules/files

### 2. Smart Error Grouping

Group similar failures by:

- **Error type**: ImportError, AttributeError, AssertionError, etc.
- **Module/file**: Same file causing multiple test failure
- **Root cause**: Missing dependencies, API changes, refactoring impacts

Prioritize groups by:

- Number of affected tests (highest impact first)
- Dependency order (fix infrastructure before functionality)

### 3. Systematic Fixing Process

For each group (starting with highest impact):

1. **Identify root cause**

   - Read relevant code
   - Check recent changes with `git diff`
   - Understand the error pattern

2. **Implement fix**

   - Use Edit tool for code changes
   - Follow project conventions (see CLAUDE.md)
   - Make minimal, focused changes

3. **Verify fix**

   - Run subset of tests for this group
   - Use pytest markers or file patterns:
     ```bash
     uv run pytest tests/path/to/test_file.py -v
     uv run pytest -k "pattern" -v
     ```
   - Ensure group passes before moving on

4. **Move to next group**

### 4. Fix Order Strategy

**Infrastructure first:**

- Import errors
- Missing dependencies
- Configuration issues

**Then API changes:**

- Function signature changes
- Module reorganization
- Renamed variables/functions

**Finally, logic issues:**

- Assertion failures
- Business logic bugs
- Edge case handling

### 5. Final Verification

After all groups fixed:

- Run complete test suite: `make test`
- Verify no regressions
- Check test coverage remains intact

## Best Practices

- Fix one group at a time
- Run focused tests after each fix
- Use `git diff` to understand recent changes
- Look for patterns in failures
- Don't move to next group until current passes
- Keep changes minimal and focused

## Example Workflow

User: "The tests are failing after my refactor"

1. Run `make test` → 15 failures identified
2. Group errors:
   - 8 ImportErrors (module renamed)
   - 5 AttributeErrors (function signature changed)
   - 2 AssertionErrors (logic bugs)
3. Fix ImportErrors first → Run subset → Verify
4. Fix AttributeErrors → Run subset → Verify
5. Fix AssertionErrors → Run subset → Verify
6. Run full suite → All pass ✓

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: test-framework-migration-skill
description: Migrates and converts test automation scripts between Selenium, Playwright, Puppeteer, and Cypress. Use when the user asks to migrate, convert, or port tests from one framework to another; rewrite tests in a different framework; or switch from Selenium to Playwright, Playwright to...
risk: critical
source: https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill
source_repo: LambdaTest/agent-skills
source_type: community
date_added: 2026-07-01
license: MIT
license_source: https://github.com/LambdaTest/agent-skills/blob/main/LICENSE
---

# Test Framework Migration Skill
## When to Use

Use this skill when you need migrates and converts test automation scripts between Selenium, Playwright, Puppeteer, and Cypress. Use when the user asks to migrate, convert, or port tests from one framework to another; rewrite tests in a different framework; or switch from Selenium to Playwright, Playwright to...

You are a senior QA automation architect. You migrate test automation scripts from one framework (Selenium, Playwright, Puppeteer, Cypress) to another by applying API mappings, lifecycle changes, and pattern conversions from the skill reference docs.

## Step 1 — Detect Source Framework

Determine the **source** framework from the user message or from open files:

| Signal in message or code | Source framework |
|---------------------------|------------------|
| "Selenium", "WebDriver", "driver.findElement", "By.id", "ChromeDriver" | Selenium |
| "Playwright", "page.getByRole", "expect(locator).toBeVisible", "@playwright/test" | Playwright |
| "Puppeteer", "page.$", "page.goto", "puppeteer.launch" | Puppeteer |
| "Cypress", "cy.get", "cy.visit", "cy.contains", "cy.should" | Cypress |

If ambiguous (e.g. user says "convert my tests" with no file open), ask: "Which framework are your current tests in (Selenium, Playwright, Puppeteer, or Cypress)?"

## Step 2 — Detect Target Framework

Determine the **target** framework from the user message:

| User says... | Target |
|--------------|--------|
| "to Playwright", "to playwright" | Playwright |
| "to Selenium", "to WebDriver" | Selenium |
| "to Puppeteer" | Puppeteer |
| "to Cypress" | Cypress |

If the user only names the source (e.g. "convert my Selenium tests"), ask: "Which framework do you want to migrate to (Playwright, Puppeteer, Cypress, or keep Selenium with another language)?"

## Step 3 — Detect Language

| Source → Target | Language note |
|----------------|---------------|
| Selenium (Java/Python/C#) → Playwright | Playwright is typically JS/TS; migration usually implies rewriting to TypeScript or JavaScript. Mention this if source is Java/C#/Python. |
| Selenium (JS) → Playwright | Same language (JS/TS) possible. |
| Playwright/Puppeteer/Cypress → Selenium | Target can be Java, Python, JS, C#. Prefer same as project or ask. |
| Playwright ↔ Puppeteer ↔ Cypress | Typically stay in JS/TS. |

For language matrix details (which frameworks support which languages), see [reference/overview.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/overview.md).

## Step 4 — Route to Reference

**Always read** the matching reference file before generating migrated code:

| Source → Target | Reference file |
|----------------|----------------|
| Selenium → Playwright | [reference/selenium-to-playwright.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/selenium-to-playwright.md) |
| Playwright → Selenium | [reference/playwright-to-selenium.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/playwright-to-selenium.md) |
| Selenium → Puppeteer | [reference/selenium-to-puppeteer.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/selenium-to-puppeteer.md) |
| Puppeteer → Selenium | [reference/puppeteer-to-selenium.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/puppeteer-to-selenium.md) |
| Puppeteer → Playwright | [reference/puppeteer-to-playwright.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/puppeteer-to-playwright.md) |
| Playwright → Puppeteer | [reference/playwright-to-puppeteer.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/playwright-to-puppeteer.md) |
| Cypress → Playwright | [reference/cypress-to-playwright.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/cypress-to-playwright.md) |
| Playwright → Cypress | [reference/playwright-to-cypress.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/playwright-to-cypress.md) |
| Selenium → Cypress | [reference/selenium-to-cypress.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/selenium-to-cypress.md) |
| Cypress → Selenium | [reference/cypress-to-selenium.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/cypress-to-selenium.md) |

If the pair is not in the table, say so and suggest the closest supported migration (e.g. add WebDriverIO later as a new reference file).

## Step 5 — Apply Mappings

Using the reference doc:

1. **Locators** — Convert using the API mapping table (e.g. `By.id("x")` → `page.getByRole(...)` or `page.locator('#x')`).
2. **Waits** — Convert wait strategy (explicit wait / auto-wait / cy.should).
3. **Actions** — Map click, type, select, etc.
4. **Assertions** — Map to target's assertion style.
5. **Lifecycle** — Adjust setup/teardown (driver vs page, launch vs connect).
6. **Cloud (TestMu)** — If user runs on cloud, point to target framework's cloud docs after migration.

After generating migrated code, validate against the "Gotchas" section of the reference to avoid common pitfalls.

## Cross-References for Deep Patterns

| Need | Where to look |
|------|----------------|
| Full Playwright patterns, POM, cloud | `playwright-skill` and [playwright-skill/reference/cloud-integration.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/../playwright-skill/reference/cloud-integration.md) |
| Full Selenium patterns, POM, cloud | `selenium-skill` and [selenium-skill/reference/cloud-integration.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/../selenium-skill/reference/cloud-integration.md) |
| Full Puppeteer patterns, cloud | `puppeteer-skill` and [puppeteer-skill/reference/cloud-integration.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/../puppeteer-skill/reference/cloud-integration.md) |
| Full Cypress patterns, cloud | `cypress-skill` and [cypress-skill/reference/cloud-integration.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/../cypress-skill/reference/cloud-integration.md) |
| TestMu capabilities (all frameworks) | [shared/testmu-cloud-reference.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/../shared/testmu-cloud-reference.md) |

## Validation Workflow

After generating migrated code:

1. Ensure every locator/action/assertion was converted using the reference mapping (no leftover source API).
2. Ensure lifecycle (setup/teardown) matches target framework.
3. If target is Playwright: use auto-wait assertions (`expect(locator).toBeVisible()`), not raw `waitForTimeout`.
4. If target is Cypress: no async/await with `cy` commands; use chain style.
5. If target is Selenium: use explicit `WebDriverWait`, never `Thread.sleep`.

## Reference Files Summary

| File | When to read |
|------|--------------|
| [reference/overview.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/overview.md) | Framework comparison, language matrix, when to migrate |
| [reference/playbook.md](https://github.com/LambdaTest/agent-skills/tree/main/test-framework-migration-skill/reference/playbook.md) | Full migration workflow, debugging table, CI/CD checklist, best practices |
| `reference/<source>-to-<target>.md` | Before converting any script for that pair |

## Limitations

- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.


---
name: "test-guard"
description: "Review generated or changed test code against universal testing rules before it ships or is presented for approval."
risk: "critical"
source: "community"
source_repo: "amElnagdy/guard-skills"
source_type: "community"
date_added: 2026-07-13
author: "community"
tags: []
tools: []
---

# Test Guard

You are reviewing generated or changed test code before it ships. Enforce the rules below after the first test-writing pass and before the tests are presented, committed, or merged. Be a sharp reviewer, not a pedantic one: flag what wastes maintenance effort or hides real bugs, ignore cosmetic preferences.

These rules exist because coding agents over-generate tests. The common failure modes: mock-heavy unit tests that assert implementation details, near-duplicate test bodies that differ by one value, and tests that re-verify the framework instead of the project's logic. Each looks productive in a diff and costs maintenance forever.

## When to Use

Use this skill when reviewing generated or changed test code before it ships. Activate it reactively after an agent writes, edits, generates, or refactors tests — unit tests, integration tests, e2e tests, or snapshot tests in any framework.

## When this skill activates

- A coding agent has just written new test functions or test files, in any language
- You are editing existing tests
- You are reviewing a diff that contains test changes
- The user asks you to write, add, or review tests

## Adapt to the project first

These rules are universal, but their application is not. Before reviewing:

1. Check the project's own agent instructions (CLAUDE.md, AGENTS.md) and testing docs. Project-specific testing rules win over this skill when they conflict.
2. Identify the test stack, then read the matching reference for concrete patterns:
   - Python / pytest → [references/pytest.md](references/pytest.md)
   - PHP / PHPUnit / Pest / WordPress → [references/phpunit.md](references/phpunit.md)
   - JavaScript / TypeScript / Jest / Vitest → [references/jest.md](references/jest.md)
3. If the project calls LLM APIs, uses agent frameworks, or wires up observability/telemetry, also read [references/llm-app-testing.md](references/llm-app-testing.md) — it adds three rules specific to LLM applications.
4. Map the project's system boundaries: network calls, databases, filesystem, clock and randomness, third-party SDKs, LLM APIs. Existing fixtures and test helpers usually reveal where the project already draws these lines.

## What to do

1. Read the test code: the diff, the new file, or the section being modified.
2. Check each test against the rules below.
3. Report violations concisely: rule number, location, why it violates, suggested fix.
4. If the user explicitly invokes this skill before test writing, apply the rules as you write — don't write violations and then flag them.

When writing new tests, ask for each test: "What specific bug does this catch that no other test in this suite catches?" If you can't answer clearly, don't write it.

## The Nine Rules

### Rule 1: Test behavior, not implementation
Test what code does from the caller's perspective. Assert return values and observable side effects. Never assert that an internal helper was called with specific arguments — that test breaks on every refactor while catching nothing.

**Violation pattern:** asserting a mock of an internal function was called, where that function is not a system boundary.
**Fix:** assert the return value or the state change the caller observes.

### Rule 2: Every mock must be justified
Mock only at system boundaries: network and HTTP calls, LLM APIs, databases, filesystem I/O on external files, clock and randomness, third-party SDKs. Never mock internal classes or helper functions to isolate a "unit" — the seams you create hide the integration bugs worth catching.

When you mock a boundary, assert what the caller *does with the response*, not that the mock received specific arguments.

### Rule 3: One scenario per test, data-driven for variants
If two or more tests share identical setup and differ only in input/output values, merge them into one data-driven test (`@pytest.mark.parametrize`, PHPUnit `#[DataProvider]`, Jest `test.each`).

**When separate tests ARE correct:** different setup, different assertions, different mock configurations, or genuinely different scenarios that happen to exercise the same function.

### Rule 4: Every test must justify its existence
Ask: "What bug does this catch that no other test catches?" Delete tests that only catch typos, verify default values of data classes, or test trivial pass-through logic.

**Common unjustified tests:** constructors setting attributes, a function rejecting input the type system already forbids, string formatting of log messages, a constant equaling its literal value.

### Rule 5: Name tests for the scenario
Pattern: `test_<scenario>_<expected_outcome>`. The name should read like a requirement, not echo the function signature.

| Bad | Good |
|-----|------|
| `test_parse_response_missing_field` | `test_malformed_response_falls_back_to_default` |
| `test_get_language_no_class` | `test_element_without_class_returns_empty_language` |
| `test_add_tags_single_string` | `test_single_tag_normalizes_to_list` |

### Rule 6: Production regression tests are sacred
Tests that reproduce a real production bug are always justified. Reference the incident (date, issue ID, or short description) in the name or a comment, and never delete them. They are exempt from Rule 4 — their justification is the incident.

### Rule 7: No tests for framework guarantees
Don't test that the validation library validates, the ORM commits, the router returns 404, or the test framework's fixtures work. Test *your* logic that sits on top of the framework.

**Violation pattern:** a test that would still pass if you deleted all the project's custom code and kept only framework defaults.

### Rule 8: State and value objects are real, never mocked
Never mock a data model, DTO, entity, or state object. Construct a real instance. Mocking state hides field-name typos and validation errors — exactly the bugs worth catching. If constructing the real object is painful, that is design feedback, not a reason to mock; add a small builder or factory helper.

### Rule 9: Infrastructure under test gets real infrastructure
When database queries, schema behavior, or persistence logic *is the subject* of the test, run against a real test database with real migrations applied via fixtures. Mocking the session there tests nothing. Mocking the database is fine when persistence is only a side effect of the behavior under test.

## Reporting format

When flagging violations, use this format:

```
**Rule N violation** in `tests/path/file.ext::<test_name>`
- What: <one sentence describing the violation>
- Fix: <one sentence describing what to do instead>
```

Group violations by file. If a file has no violations, don't mention it.

## Severity guide

Not all violations are equal. Use judgment:

- **Must fix:** Rules 1, 2, 8 — these hide real bugs or make tests brittle
- **Should fix:** Rules 3, 4, 5, 7 — these cause bloat and maintenance drag
- **Sacred:** Rule 6 — never delete, always allow
- **Worth noting:** Rule 9 — test architecture; flag it, but don't block small changes on it

## References

- [references/pytest.md](references/pytest.md) — Python/pytest patterns: parametrize, fixtures, mock boundaries, real Pydantic instances
- [references/phpunit.md](references/phpunit.md) — PHP/PHPUnit/Pest patterns, including WordPress and WooCommerce test boundaries
- [references/jest.md](references/jest.md) — Jest/Vitest patterns: test.each, module mocks, msw, snapshot discipline
- [references/llm-app-testing.md](references/llm-app-testing.md) — three extra rules for LLM applications: prompt contracts, observability wiring, agent-flow transitions

## What this skill does NOT do

- It does not run tests. Use the project's test runner for that.
- It does not enforce code style — that's the linter's job.
- It does not decide *what* to test — only *how* to test it.
- It does not flag pre-existing violations in files you're not touching, unless asked to audit.


---
name: testing-patterns
description: "Jest testing patterns, factory functions, mocking strategies, and TDD workflow. Use when writing unit tests, creating test factories, or following TDD red-green-refactor cycle."
risk: critical
source: community
date_added: "2026-02-27"
---

# Testing Patterns and Utilities

## Testing Philosophy

**Test-Driven Development (TDD):**
- Write failing test FIRST
- Implement minimal code to pass
- Refactor after green
- Never write production code without a failing test

**Behavior-Driven Testing:**
- Test behavior, not implementation
- Focus on public APIs and business requirements
- Avoid testing implementation details
- Use descriptive test names that describe behavior

**Factory Pattern:**
- Create `getMockX(overrides?: Partial<X>)` functions
- Provide sensible defaults
- Allow overriding specific properties
- Keep tests DRY and maintainable

## Test Utilities

### Custom Render Function

Create a custom render that wraps components with required providers:

```typescript
// src/utils/testUtils.tsx
import { render } from '@testing-library/react-native';
import { ThemeProvider } from './theme';

export const renderWithTheme = (ui: React.ReactElement) => {
  return render(
    <ThemeProvider>{ui}</ThemeProvider>
  );
};
```

**Usage:**
```typescript
import { renderWithTheme } from 'utils/testUtils';
import { screen } from '@testing-library/react-native';

it('should render component', () => {
  renderWithTheme(<MyComponent />);
  expect(screen.getByText('Hello')).toBeTruthy();
});
```

## Factory Pattern

### Component Props Factory

```typescript
import { ComponentProps } from 'react';

const getMockMyComponentProps = (
  overrides?: Partial<ComponentProps<typeof MyComponent>>
) => {
  return {
    title: 'Default Title',
    count: 0,
    onPress: jest.fn(),
    isLoading: false,
    ...overrides,
  };
};

// Usage in tests
it('should render with custom title', () => {
  const props = getMockMyComponentProps({ title: 'Custom Title' });
  renderWithTheme(<MyComponent {...props} />);
  expect(screen.getByText('Custom Title')).toBeTruthy();
});
```

### Data Factory

```typescript
interface User {
  id: string;
  name: string;
  email: string;
  role: 'admin' | 'user';
}

const getMockUser = (overrides?: Partial<User>): User => {
  return {
    id: '123',
    name: 'John Doe',
    email: 'john@example.com',
    role: 'user',
    ...overrides,
  };
};

// Usage
it('should display admin badge for admin users', () => {
  const user = getMockUser({ role: 'admin' });
  renderWithTheme(<UserCard user={user} />);
  expect(screen.getByText('Admin')).toBeTruthy();
});
```

## Mocking Patterns

### Mocking Modules

```typescript
// Mock entire module
jest.mock('utils/analytics');

// Mock with factory function
jest.mock('utils/analytics', () => ({
  Analytics: {
    logEvent: jest.fn(),
  },
}));

// Access mock in test
const mockLogEvent = jest.requireMock('utils/analytics').Analytics.logEvent;
```

### Mocking GraphQL Hooks

```typescript
jest.mock('./GetItems.generated', () => ({
  useGetItemsQuery: jest.fn(),
}));

const mockUseGetItemsQuery = jest.requireMock(
  './GetItems.generated'
).useGetItemsQuery as jest.Mock;

// In test
mockUseGetItemsQuery.mockReturnValue({
  data: { items: [] },
  loading: false,
  error: undefined,
});
```

## Test Structure

```typescript
describe('ComponentName', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  describe('Rendering', () => {
    it('should render component with default props', () => {});
    it('should render loading state when loading', () => {});
  });

  describe('User interactions', () => {
    it('should call onPress when button is clicked', async () => {});
  });

  describe('Edge cases', () => {
    it('should handle empty data gracefully', () => {});
  });
});
```

## Query Patterns

```typescript
// Element must exist
expect(screen.getByText('Hello')).toBeTruthy();

// Element should not exist
expect(screen.queryByText('Goodbye')).toBeNull();

// Element appears asynchronously
await waitFor(() => {
  expect(screen.findByText('Loaded')).toBeTruthy();
});
```

## User Interaction Patterns

```typescript
import { fireEvent, screen } from '@testing-library/react-native';

it('should submit form on button click', async () => {
  const onSubmit = jest.fn();
  renderWithTheme(<LoginForm onSubmit={onSubmit} />);

  fireEvent.changeText(screen.getByLabelText('Email'), 'user@example.com');
  fireEvent.changeText(screen.getByLabelText('Password'), 'password123');
  fireEvent.press(screen.getByTestId('login-button'));

  await waitFor(() => {
    expect(onSubmit).toHaveBeenCalled();
  });
});
```

## Anti-Patterns to Avoid

### Testing Mock Behavior Instead of Real Behavior

```typescript
// Bad - testing the mock
expect(mockFetchData).toHaveBeenCalled();

// Good - testing actual behavior
expect(screen.getByText('John Doe')).toBeTruthy();
```

### Not Using Factories

```typescript
// Bad - duplicated, inconsistent test data
it('test 1', () => {
  const user = { id: '1', name: 'John', email: 'john@test.com', role: 'user' };
});
it('test 2', () => {
  const user = { id: '2', name: 'Jane', email: 'jane@test.com' }; // Missing role!
});

// Good - reusable factory
const user = getMockUser({ name: 'Custom Name' });
```

## Best Practices

1. **Always use factory functions** for props and data
2. **Test behavior, not implementation**
3. **Use descriptive test names**
4. **Organize with describe blocks**
5. **Clear mocks between tests**
6. **Keep tests focused** - one behavior per test

## Running Tests

```bash
# Run all tests
npm test

# Run with coverage
npm run test:coverage

# Run specific file
npm test ComponentName.test.tsx
```

## Integration with Other Skills

- **react-ui-patterns**: Test all UI states (loading, error, empty, success)
- **systematic-debugging**: Write test that reproduces bug before fixing

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: testing-qa
description: "Comprehensive testing and QA workflow covering unit testing, integration testing, E2E testing, browser automation, and quality assurance."
category: workflow-bundle
risk: safe
source: personal
date_added: "2026-02-27"
---

# Testing/QA Workflow Bundle

## Overview

Comprehensive testing and quality assurance workflow covering unit tests, integration tests, E2E tests, browser automation, and quality gates for production-ready software.

## When to Use This Workflow

Use this workflow when:
- Setting up testing infrastructure
- Writing unit and integration tests
- Implementing E2E tests
- Automating browser testing
- Establishing quality gates
- Performing code review

## Workflow Phases

### Phase 1: Test Strategy

#### Skills to Invoke
- `test-automator` - Test automation
- `test-driven-development` - TDD

#### Actions
1. Define testing strategy
2. Choose testing frameworks
3. Plan test coverage
4. Set up test infrastructure
5. Configure CI integration

#### Copy-Paste Prompts
```
Use @test-automator to design testing strategy
```

```
Use @test-driven-development to implement TDD workflow
```

### Phase 2: Unit Testing

#### Skills to Invoke
- `javascript-testing-patterns` - Jest/Vitest
- `python-testing-patterns` - pytest
- `unit-testing-test-generate` - Test generation
- `tdd-orchestrator` - TDD orchestration

#### Actions
1. Write unit tests
2. Set up test fixtures
3. Configure mocking
4. Measure coverage
5. Integrate with CI

#### Copy-Paste Prompts
```
Use @javascript-testing-patterns to write Jest tests
```

```
Use @python-testing-patterns to write pytest tests
```

```
Use @unit-testing-test-generate to generate unit tests
```

### Phase 3: Integration Testing

#### Skills to Invoke
- `api-testing-observability-api-mock` - API testing
- `e2e-testing-patterns` - Integration patterns

#### Actions
1. Design integration tests
2. Set up test databases
3. Configure API mocks
4. Test service interactions
5. Verify data flows

#### Copy-Paste Prompts
```
Use @api-testing-observability-api-mock to test APIs
```

### Phase 4: E2E Testing

#### Skills to Invoke
- `playwright-skill` - Playwright testing
- `e2e-testing-patterns` - E2E patterns
- `webapp-testing` - Web app testing

#### Actions
1. Design E2E scenarios
2. Write test scripts
3. Configure test data
4. Set up parallel execution
5. Implement visual regression

#### Copy-Paste Prompts
```
Use @playwright-skill to create E2E tests
```

```
Use @e2e-testing-patterns to design E2E strategy
```

### Phase 5: Browser Automation

#### Skills to Invoke
- `browser-automation` - Browser automation
- `webapp-testing` - Browser testing
- `screenshots` - Screenshot automation

#### Actions
1. Set up browser automation
2. Configure headless testing
3. Implement visual testing
4. Capture screenshots
5. Test responsive design

#### Copy-Paste Prompts
```
Use @browser-automation to automate browser tasks
```

```
Use @screenshots to capture marketing screenshots
```

### Phase 6: Performance Testing

#### Skills to Invoke
- `performance-engineer` - Performance engineering
- `performance-profiling` - Performance profiling
- `web-performance-optimization` - Web performance

#### Actions
1. Design performance tests
2. Set up load testing
3. Measure response times
4. Identify bottlenecks
5. Optimize performance

#### Copy-Paste Prompts
```
Use @performance-engineer to test application performance
```

### Phase 7: Code Review

#### Skills to Invoke
- `code-reviewer` - AI code review
- `code-review-excellence` - Review best practices
- `find-bugs` - Bug detection
- `security-scanning-security-sast` - Security scanning

#### Actions
1. Configure review tools
2. Run automated reviews
3. Check for bugs
4. Verify security
5. Approve changes

#### Copy-Paste Prompts
```
Use @code-reviewer to review pull requests
```

```
Use @find-bugs to detect bugs in code
```

### Phase 8: Quality Gates

#### Skills to Invoke
- `lint-and-validate` - Linting
- `verification-before-completion` - Verification

#### Actions
1. Configure linters
2. Set up formatters
3. Define quality metrics
4. Implement gates
5. Monitor compliance

#### Copy-Paste Prompts
```
Use @lint-and-validate to check code quality
```

```
Use @verification-before-completion to verify changes
```

## Testing Pyramid

```
        /       /  \    E2E Tests (10%)
      /----     /      \  Integration Tests (20%)
    /--------   /          \ Unit Tests (70%)
  /------------```

## Quality Gates Checklist

- [ ] Unit test coverage > 80%
- [ ] All tests passing
- [ ] E2E tests for critical paths
- [ ] Performance benchmarks met
- [ ] Security scan passed
- [ ] Code review approved
- [ ] Linting clean

## Related Workflow Bundles

- `development` - Development workflow
- `security-audit` - Security testing
- `cloud-devops` - CI/CD integration
- `ai-ml` - AI testing

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: testng-skill
description: 'Generates TestNG tests in Java with groups, data providers, parallel execution, XML suite configuration, and listeners. Use when user mentions "TestNG", "@DataProvider", "testng.xml", "groups". Triggers on: "TestNG", "@DataProvider", "testng.xml", "TestNG suite", "parallel tests Java".'
risk: critical
source: https://github.com/LambdaTest/agent-skills/tree/main/testng-skill
source_repo: LambdaTest/agent-skills
source_type: community
date_added: 2026-07-01
license: MIT
license_source: https://github.com/LambdaTest/agent-skills/blob/main/LICENSE
---

# TestNG Testing Skill
## When to Use

Use this skill when you need generates TestNG tests in Java with groups, data providers, parallel execution, XML suite configuration, and listeners. Use when user mentions "TestNG", "@DataProvider", "testng.xml", "groups". Triggers on: "TestNG", "@DataProvider", "testng.xml", "TestNG suite", "parallel tests Java".

## Core Patterns

### Basic Test with Groups

```java
import org.testng.annotations.*;
import org.testng.Assert;

public class LoginTest {
    @BeforeMethod
    public void setUp() { /* setup */ }

    @Test(groups = "smoke")
    public void testLoginSuccess() {
        Assert.assertTrue(loginService.login("user@test.com", "password123"));
    }

    @Test(groups = "regression", dependsOnMethods = "testLoginSuccess")
    public void testAccessDashboard() {
        Assert.assertNotNull(dashboard.getContent());
    }

    @Test(expectedExceptions = AuthenticationException.class)
    public void testLoginInvalidPassword() {
        loginService.login("user@test.com", "wrong");
    }

    @AfterMethod
    public void tearDown() { /* cleanup */ }
}
```

### Data Providers

```java
@DataProvider(name = "loginData")
public Object[][] loginData() {
    return new Object[][] {
        {"admin@test.com", "admin123", true},
        {"user@test.com", "password", true},
        {"invalid@test.com", "wrong", false},
    };
}

@Test(dataProvider = "loginData")
public void testLogin(String email, String password, boolean expected) {
    Assert.assertEquals(loginService.login(email, password), expected);
}
```

### TestNG XML Suite

```xml
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Regression" parallel="tests" thread-count="5">
  <test name="Smoke">
    <groups><run><include name="smoke"/></run></groups>
    <classes><class name="tests.LoginTest"/></classes>
  </test>
  <test name="Full">
    <groups><run><include name="regression"/><exclude name="flaky"/></run></groups>
    <packages><package name="tests.*"/></packages>
  </test>
</suite>
```

### Parallel Execution

```xml
<suite parallel="methods" thread-count="5">   <!-- Method level -->
<suite parallel="classes" thread-count="5">    <!-- Class level -->
<suite parallel="tests" thread-count="5">      <!-- Test level -->
```

### Soft Assertions

```java
SoftAssert soft = new SoftAssert();
soft.assertEquals(user.getName(), "Alice");
soft.assertEquals(user.getAge(), 25);
soft.assertTrue(user.isActive());
soft.assertAll();  // Reports all failures at once
```

### Listeners

```java
public class TestListener implements ITestListener {
    @Override public void onTestFailure(ITestResult result) {
        System.out.println("Failed: " + result.getName());
        // Take screenshot, log, etc.
    }
}

@Listeners(TestListener.class)
public class LoginTest { /* ... */ }
```

### Lifecycle Annotations

```
@BeforeSuite → @BeforeTest → @BeforeClass → @BeforeMethod → @Test → @AfterMethod → @AfterClass → @AfterTest → @AfterSuite
```

### Anti-Patterns

| Bad | Good | Why |
|-----|------|-----|
| `dependsOnMethods` everywhere | Independent tests | Cascading failures |
| No groups | `@Test(groups = "smoke")` | Can't run subsets |
| Hard-coded test data | `@DataProvider` | Reusable |
| Priority ordering | Independent tests | Fragile |

## Quick Reference

| Task | Command |
|------|---------|
| Run suite | `mvn test -DsuiteXmlFile=testng.xml` |
| Run group | `mvn test -Dgroups=smoke` |
| Run class | `mvn test -Dtest=LoginTest` |
| Reports | `test-output/index.html` |

## Deep Patterns → `reference/playbook.md`

| § | Section | Lines |
|---|---------|-------|
| 1 | Project Setup & Configuration | Maven + Surefire config |
| 2 | Suite XML Configuration | Multi-env, parallel, groups |
| 3 | BaseTest & Thread-Safe Driver | ThreadLocal, ConfigReader |
| 4 | Data Providers (Advanced) | Excel, JSON, CSV, parallel, cross-class |
| 5 | Factory Pattern | Cross-browser matrix |
| 6 | Listeners (Production Suite) | Retry, screenshot, timing |
| 7 | Soft Assertions & Dependencies | Groups, method deps |
| 8 | Page Object Integration | PageFactory, fluent POs |
| 9 | Parallel Execution Strategies | Method/class/test/mixed |
| 10 | Reporting Integration | Allure, ExtentReports |
| 11 | CI/CD Integration | GitHub Actions, Jenkins |
| 12 | Debugging Quick-Reference | 12 common problems |
| 13 | Best Practices Checklist | 14 items |

## Limitations

- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.