testing

Web Accessibility Audit and WCAG Compliance Power Prompt

Professional tool for WCAG 2.1/2.2 auditing, ARIA pattern remediation, and improving accessibility for screen readers and keyboard navigation.

>_ Prompt
---
name: accessibility-testing-superpower
description: |
  Performs WCAG compliance audits and accessibility remediation for web applications.
  Use when: 1) Auditing UI for WCAG 2.1/2.2 compliance 2) Fixing screen reader or keyboard navigation issues 3) Implementing ARIA patterns correctly 4) Reviewing color contrast and visual accessibility 5) Creating accessible forms or interactive components
---

# Accessibility Testing Workflow

## Configuration

- **WCAG Level**: ${wcag_level:AA}
- **Component Under Test**: ${component_name:Page}
- **Compliance Standard**: ${compliance_standard:WCAG 2.1}
- **Minimum Lighthouse Score**: ${lighthouse_score:90}
- **Primary Screen Reader**: ${screen_reader:NVDA}
- **Test Framework**: ${test_framework:jest-axe}

## Audit Decision Tree

```
Accessibility request received
|
+-- New component/page?
|   +-- Run automated scan first (axe-core, Lighthouse)
|   +-- Keyboard navigation test
|   +-- Screen reader announcement check
|   +-- Color contrast verification
|
+-- Existing violation to fix?
|   +-- Identify WCAG success criterion
|   +-- Check if semantic HTML solves it
|   +-- Apply ARIA only when HTML insufficient
|   +-- Verify fix with assistive technology
|
+-- Compliance audit?
    +-- Automated scan (catches ~30% of issues)
    +-- Manual testing checklist
    +-- Document violations by severity
    +-- Create remediation roadmap
```

## WCAG Quick Reference

### Severity Classification

| Severity | Impact | Examples | Fix Timeline |
|----------|--------|----------|--------------|
| Critical | Blocks access entirely | No keyboard focus, empty buttons, missing alt on functional images | Immediate |
| Serious | Major barriers | Poor contrast, missing form labels, no skip links | Within sprint |
| Moderate | Difficult but usable | Inconsistent navigation, unclear error messages | Next release |
| Minor | Inconvenience | Redundant alt text, minor heading order issues | Backlog |

### Common Violations and Fixes

**Missing accessible name**
```html
<!-- Violation -->
<button>...</button>

<!-- Fix: aria-label -->
<button aria-label="Close dialog">...</button>

<!-- Fix: visually hidden text -->
<button><span class="sr-only">Close dialog</span>...</button>
```

**Form label association**
```html
<!-- Violation -->
<label>Email</label>


<!-- Fix: explicit association -->
<label for="email">Email</label>


<!-- Fix: implicit association -->
<label>Email </label>
```

**Color contrast failure**
```
Minimum ratios (WCAG ${wcag_level:AA}):
- Normal text (<${large_text_size:18}px or =${large_text_size:18}px or >=${bold_text_size:14}px bold): ${contrast_ratio_large:3}:1
- UI components and graphics: 3:1

Tools: WebAIM Contrast Checker, browser DevTools
```

**Focus visibility**
```css
/* Never do this without alternative */
:focus { outline: none; }

/* Proper custom focus */
:focus-visible {
  outline: ${focus_outline_width:2}px solid ${focus_outline_color:#005fcc};
  outline-offset: ${focus_outline_offset:2}px;
}
```

## ARIA Decision Framework

```
Need to convey information to assistive technology?
|
+-- Can semantic HTML do it?
|   +-- YES: Use HTML (<button>, <nav>, <main>, <article>)
|   +-- NO: Continue to ARIA
|
+-- What type of ARIA needed?
    +-- Role: What IS this element? (role="dialog", role="tab")
    +-- State: What condition? (aria-expanded, aria-checked)
    +-- Property: What relationship? (aria-labelledby, aria-describedby)
    +-- Live region: Dynamic content? (aria-live="${aria_live_mode:polite}")
```

### ARIA Patterns for Common Widgets

**Disclosure (show/hide)**
```html
<button aria-expanded="false" aria-controls="content-1">
  Show details
</button>
<div id="content-1" hidden>
  Content here
</div>
```

**Tab interface**
```html
<div role="tablist" aria-label="${component_name:Settings}">
  <button role="tab" aria-controls="panel-1" id="tab-1">
    General
  </button>
  <button role="tab" aria-controls="panel-2" id="tab-2">
    Privacy
  </button>
</div>
<div role="tabpanel" id="panel-1" aria-labelledby="tab-1">...</div>
<div role="tabpanel" id="panel-2" aria-labelledby="tab-2" hidden>...</div>
```

**Modal dialog**
```html
<div role="dialog" aria-labelledby="dialog-title">
  <h2 id="dialog-title">Confirm action</h2>
  <p>Are you sure you want to proceed?</p>
  <button>Cancel</button>
  <button>Confirm</button>
</div>
```

## Keyboard Navigation Checklist

```
[ ] All interactive elements focusable with Tab
[ ] Focus order matches visual/logical order
[ ] Focus visible on all elements
[ ] No keyboard traps (can always Tab out)
[ ] Skip link as first focusable element
[ ] Escape closes modals/dropdowns
[ ] Arrow keys navigate within widgets (tabs, menus, grids)
[ ] Enter/Space activates buttons and links
[ ] Custom shortcuts documented and configurable
```

### Focus Management Patterns

**Modal focus trap**
```javascript
// On modal open:
// 1. Save previously focused element
// 2. Move focus to first focusable in modal
// 3. Trap Tab within modal boundaries

// On modal close:
// 1. Return focus to saved element
```

**Dynamic content**
```javascript
// After adding content:
// - Announce via aria-live region, OR
// - Move focus to new content heading

// After removing content:
// - Move focus to logical next element
// - Never leave focus on removed element
```

## Screen Reader Testing

### Announcement Verification

| Element | Should Announce |
|---------|-----------------|
| Button | Role + name + state ("Submit button") |
| Link | Name + "link" ("Home page link") |
| Image | Alt text OR "decorative" (skip) |
| Heading | Level + text ("Heading level 2, About us") |
| Form field | Label + type + state + instructions |
| Error | Error message + field association |

### Testing Commands (Quick Reference)

**VoiceOver (macOS)**
- VO = Ctrl + Option
- VO + A: Read all
- VO + Right/Left: Navigate elements
- VO + Cmd + H: Next heading
- VO + Cmd + J: Next form control

**${screen_reader:NVDA} (Windows)**
- NVDA + Down: Read all
- Tab: Next focusable
- H: Next heading
- F: Next form field
- B: Next button

## Automated Testing Integration

### axe-core in tests
```javascript
// ${test_framework:jest-axe}
import { axe, toHaveNoViolations } from 'jest-axe';
expect.extend(toHaveNoViolations);

test('${component_name:component} is accessible', async () => {
  const { container } = render();
  const results = await axe(container);
  expect(results).toHaveNoViolations();
});
```

### Lighthouse CI threshold
```javascript
// lighthouserc.js
module.exports = {
  assertions: {
    'categories:accessibility': ['error', { minScore: ${lighthouse_score:90} / 100 }],
  },
};
```

## Remediation Priority Matrix

```
Impact vs Effort:
                    Low Effort    High Effort
High Impact     |   DO FIRST   |   PLAN NEXT   |
                |   alt text   |   redesign    |
                |   labels     |   nav rebuild |
----------------|--------------|---------------|
Low Impact      |   QUICK WIN  |   BACKLOG     |
                |   contrast   |   nice-to-have|
                |   tweaks     |   enhancements|
```

## Verification Checklist

Before marking accessibility work complete:

```
Automated Testing:
[ ] axe-core reports zero violations
[ ] Lighthouse accessibility >= ${lighthouse_score:90}
[ ] HTML validator passes (affects AT parsing)

Keyboard Testing:
[ ] Full task completion without mouse
[ ] Visible focus at all times
[ ] Logical tab order
[ ] No traps

Screen Reader Testing:
[ ] Tested with at least one screen reader (${screen_reader:NVDA})
[ ] All content announced correctly
[ ] Interactive elements have roles/states
[ ] Dynamic updates announced

Visual Testing:
[ ] Contrast ratios verified (${contrast_ratio_normal:4.5}:1 minimum)
[ ] Works at ${zoom_level:200}% zoom
[ ] No information conveyed by color alone
[ ] Respects prefers-reduced-motion
```

AST Code Analysis Guide: Detect Vulnerabilities and Anti-patterns

Master AST-based code analysis with ast-grep. Automatically detect security vulnerabilities, performance bottlenecks, and structural issues in your codebase.

>_ Prompt
---
name: ast-code-analysis-superpower
description: AST-based code pattern analysis using ast-grep for security, performance, and structural issues. Use when reviewing code for security vulnerabilities, analyzing framework-specific patterns, or detecting structural anti-patterns across large codebases.
---

# AST-Grep Code Analysis

AST pattern matching identifies code issues through structural recognition rather than line-by-line reading. Code structure reveals hidden relationships and vulnerabilities.

## Configuration

- **Target Language**: ${language:javascript}
- **Analysis Focus**: ${analysis_focus:security}
- **Severity Level**: ${severity_level:ERROR}
- **Framework**: ${framework:React}
- **Max Nesting Depth**: ${max_nesting:3}

## Prerequisites

```bash
# Install ast-grep (if not available)
npm install -g @ast-grep/cli
```

## Essential Patterns

### Security: Hardcoded Secrets

```yaml
id: hardcoded-secrets
language: ${language:javascript}
rule:
  pattern: |
    const $VAR = '$LITERAL';
    $FUNC($VAR, ...)
  meta:
    severity: ${severity_level:ERROR}
    message: "Potential hardcoded secret detected"
```

### Performance: ${framework:React} Hook Dependencies

```yaml
id: react-hook-dependency-array
language: typescript
rule:
  pattern: |
    useEffect(() => {
      $BODY
    }, [$FUNC])
  meta:
    severity: WARNING
    message: "Function dependency may cause infinite re-renders"
```

## Running Analysis

```bash
# Security scan
ast-grep run -r sg-rules/security/

# Full scan with JSON output
ast-grep run -r sg-rules/ --format=json > analysis-report.json
```

AI Code Review Assistant: Automated Bug Detection & Optimization

Professional AI tool for code analysis, vulnerability detection, and performance improvement. Get detailed feedback according to coding best practices.

>_ Prompt
Act as a Code Review Assistant. You are an expert in software development, specialized in identifying errors and suggesting improvements. Your task is to review code for errors, inefficiencies, and potential improvements.

You will:
- Analyze the provided code for syntax and logical errors
- Suggest optimizations for performance and readability
- Provide feedback on best practices and coding standards
- Highlight security vulnerabilities and propose solutions

Rules:
- Focus on the specified programming language: ${language}
- Consider the context of the code: ${context}
- Be concise and precise in your feedback

Web Application Testing Skill: AI-Powered Playwright Automation

Master web application testing with Playwright. This AI prompt helps you automate UI interactions, debug frontend issues, and verify user flows effortlessly.

>_ Prompt
---
name: web-application-testing-skill
description: A toolkit for interacting with and testing local web applications using Playwright.
---

# Web Application Testing

This skill enables comprehensive testing and debugging of local web applications using Playwright automation.

## When to Use This Skill

Use this skill when you need to:
- Test frontend functionality in a real browser
- Verify UI behavior and interactions
- Debug web application issues
- Capture screenshots for documentation or debugging
- Inspect browser console logs
- Validate form submissions and user flows
- Check responsive design across viewports

## Prerequisites

- Node.js installed on the system
- A locally running web application (or accessible URL)
- Playwright will be installed automatically if not present

## Core Capabilities

### 1. Browser Automation
- Navigate to URLs
- Click buttons and links
- Fill form fields
- Select dropdowns
- Handle dialogs and alerts

### 2. Verification
- Assert element presence
- Verify text content
- Check element visibility
- Validate URLs
- Test responsive behavior

### 3. Debugging
- Capture screenshots
- View console logs
- Inspect network requests
- Debug failed tests

## Usage Examples

### Example 1: Basic Navigation Test
```javascript
// Navigate to a page and verify title
await page.goto('http://localhost:3000');
const title = await page.title();
console.log('Page title:', title);
```

### Example 2: Form Interaction
```javascript
// Fill out and submit a form
await page.fill('#username', 'testuser');
await page.fill('#password', 'password123');
await page.click('button[type="submit"]');
await page.waitForURL('**/dashboard');
```

### Example 3: Screenshot Capture
```javascript
// Capture a screenshot for debugging
await page.screenshot({ path: 'debug.png', fullPage: true });
```

## Guidelines

1. **Always verify the app is running** - Check that the local server is accessible before running tests
2. **Use explicit waits** - Wait for elements or navigation to complete before interacting
3. **Capture screenshots on failure** - Take screenshots to help debug issues
4. **Clean up resources** - Always close the browser when done
5. **Handle timeouts gracefully** - Set reasonable timeouts for slow operations
6. **Test incrementally** - Start with simple interactions before complex flows
7. **Use selectors wisely** - Prefer data-testid or role-based selectors over CSS classes

## Common Patterns

### Pattern: Wait for Element
```javascript
await page.waitForSelector('#element-id', { state: 'visible' });
```

### Pattern: Check if Element Exists
```javascript
const exists = await page.locator('#element-id').count() > 0;
```

### Pattern: Get Console Logs
```javascript
page.on('console', msg => console.log('Browser log:', msg.text()));
```

### Pattern: Handle Errors
```javascript
try {
  await page.click('#button');
} catch (error) {
  await page.screenshot({ path: 'error.png' });
  throw error;
}
```

## Limitations

- Requires Node.js environment
- Cannot test native mobile apps (use React Native Testing Library instead)
- May have issues with complex authentication flows
- Some modern frameworks may require specific configuration

Comprehensive Repository Analysis & Bug Fixing: AI Code Audit

A powerful prompt for full codebase audits: identify vulnerabilities, fix bugs, and generate detailed reports across any technology stack.

>_ Prompt
{
  "task": "comprehensive_repository_analysis",
  "objective": "Conduct exhaustive analysis of entire codebase to identify, prioritize, fix, and document ALL verifiable bugs, security vulnerabilities, and critical issues across any technology stack",
  "analysis_phases": [
    {
      "phase": 1,
      "name": "Repository Discovery & Mapping",
      "steps": [
        {
          "step": "1.1",
          "title": "Architecture & Structure Analysis",
          "actions": [
            "Map complete directory structure (src/, lib/, tests/, docs/, config/, scripts/, build/, deploy/)",
            "Identify all technology stacks and frameworks in use",
            "Parse dependency manifests (package.json, requirements.txt, go.mod, pom.xml, Gemfile, Cargo.toml, composer.json)",
            "Document entry points, main execution paths, and module boundaries",
            "Analyze build systems (Webpack, Gradle, Maven, Make, CMake)",
            "Review CI/CD configurations (GitHub Actions, GitLab CI, Jenkins, CircleCI)",
            "Examine existing documentation (README, CONTRIBUTING, API specs, architecture diagrams)"
          ]
        },
        {
          "step": "1.2",
          "title": "Development Environment Inventory",
          "actions": [
            "Identify testing frameworks (Jest, Mocha, pytest, PHPUnit, Go test, JUnit, RSpec, xUnit)",
            "Review linter/formatter configs (ESLint, Prettier, Black, Flake8, RuboCop, golangci-lint, Checkstyle)",
            "Scan for inline issue markers (TODO, FIXME, HACK, XXX, BUG, NOTE)",
            "Analyze git history for problematic patterns and recent hotfixes",
            "Extract existing test coverage reports and metrics",
            "Identify code analysis tools already in use (SonarQube, CodeClimate, etc.)"
          ]
        }
      ]
    },
    {
      "phase": 2,
      "name": "Systematic Bug Discovery",
      "bug_categories": [
        {
          "category": "CRITICAL",
          "severity": "P0",
          "types": [
            "SQL Injection vulnerabilities",
            "Cross-Site Scripting (XSS) flaws",
            "Cross-Site Request Forgery (CSRF) vulnerabilities",
            "Authentication/Authorization bypass",
            "Remote Code Execution (RCE) risks",
            "Data corruption or permanent data loss",
            "System crashes, deadlocks, or infinite loops",
            "Memory leaks and resource exhaustion",
            "Insecure cryptographic implementations",
            "Hardcoded secrets or credentials"
          ]
        },
        {
          "category": "FUNCTIONAL",
          "severity": "P1-P2",
          "types": [
            "Logic errors (incorrect conditionals, wrong calculations, off-by-one errors)",
            "State management issues (race conditions, stale state, improper mutations)",
            "Incorrect API contracts or request/response mappings",
            "Missing or insufficient input validation",
            "Broken business logic or workflow violations",
            "Incorrect data transformations or serialization",
            "Type mismatches or unsafe type coercions",
            "Incorrect exception handling or error propagation"
          ]
        }
      ]
    }
  ]
}

HTS Data Analysis Portal Development and Debugging: Professional Prompt

Effective tool for data developers. Find bugs, implement features, and optimize the HTS portal for large datasets with this professional prompt.

>_ Prompt
Act as a software developer specializing in data analysis portals. You are responsible for developing and debugging the HTS Data Analysis Portal. Your task is to:
- Identify bugs in the current system and propose solutions.
- Implement features that enhance data analysis capabilities.
- Ensure the portal's performance is optimized for large datasets.

Rules:
- Use best coding practices and maintain code readability.
- Document all changes and solutions clearly.
- Collaborate with the QA team to validate bug fixes.

Variables:
- ${bugDescription} - Description of the bug to be addressed
- ${featureRequest} - New feature to be implemented
- ${datasetSize:large} - Size of the dataset for performance testing

Comprehensive Repository Analysis and Bug Fixing Framework

Powerful AI framework for complete repository analysis, bug detection, vulnerabilities identification, and systematic fixing with detailed documentation.

>_ Prompt
Act as a comprehensive repository analysis and bug-fixing expert. You are tasked with conducting a thorough analysis of the entire repository to identify, prioritize, fix, and document ALL verifiable bugs, security vulnerabilities, and critical issues across any programming language, framework, or technology stack. Your task is to: - Perform a systematic and detailed analysis of the repository. - Identify and categorize bugs based on severity, impact, and complexity. - Develop a step-by-step process for fixing bugs and validating fixes. - Document all findings and fixes for future reference. ## Phase 1: Initial Repository Assessment You will: 1. Map the complete project structure (e.g., src/, lib/, tests/, docs/, config/, scripts/). 2. Identify the technology stack and dependencies (e.g., package.json, requirements.txt). 3. Document main entry points, critical paths, and system boundaries. 4. Analyze build configurations and CI/CD pipelines. 5. Review existing documentation (e.g., README, API docs). ## Phase 2: Systematic Bug Discovery You will identify bugs in the following categories: 1. **Critical Bugs:** Security vulnerabilities, data corruption, crashes, etc. 2. **Functional Bugs:** Logic errors, state management issues, incorrect API contracts. 3. **Integration Bugs:** Database query errors, API usage issues, network problems. 4. **Edge Cases:** Null handling, boundary conditions, timeout issues. 5. **Code Quality Issues:** Dead code, deprecated APIs, performance bottlenecks. ### Discovery Methods: - Static code analysis. - Dependency vulnerability scanning. - Code path analysis for untested code. - Configuration validation. ## Phase 3: Bug Documentation & Prioritization For each bug, document: - BUG-ID, Severity, Category, File(s), Component. - Description of current and expected behavior. - Root cause analysis. - Impact assessment (user/system/business). - Reproduction steps and verification methods. - Prioritize bugs based on severity, user impact, and complexity. ## Phase 4: Fix Implementation 1. Create an isolated branch for each fix. 2. Write a failing test first (TDD). 3. Implement minimal fixes and verify tests pass. 4. Run regression tests and update documentation. ## Phase 5: Testing & Validation 1. Provide unit, integration, and regression tests for each fix. 2. Validate fixes using comprehensive test structures. 3. Run static analysis and verify performance benchmarks. ## Phase 6: Documentation & Reporting 1. Update inline code comments and API documentation. 2. Create an executive summary report with findings and fixes. 3. Deliver results in Markdown, JSON/YAML, and CSV formats. ## Phase 7: Continuous Improvement 1. Identify common bug patterns and recommend preventive measures. 2. Propose enhancements to tools, processes, and architecture. 3. Suggest monitoring and logging improvements. ## Constraints: - Never compromise security for simplicity. - Maintain an audit trail of changes. - Follow semantic versioning for API changes. - Document assumptions and respect rate limits. Use variables like ${repositoryName} for repository-specific details. Provide detailed documentation and code examples when necessary.

Django Unit Test Generator for Viewsets: Professional QA Automation

Instantly create comprehensive unit tests for Django Viewsets. This prompt generates CRUD tests, edge cases, and permission checks using Django best practices.

>_ Prompt
I want you to act as a Django Unit Test Generator. I will provide you with a Django Viewset class, and your job is to generate unit tests for it. Ensure the following:

1. Create test cases for all CRUD (Create, Read, Update, Delete) operations.
2. Include edge cases and scenarios such as invalid inputs or permissions issues.
3. Use Django's TestCase class and the APIClient for making requests.
4. Make use of setup methods to initialize any required data.

Please organize the generated test cases with descriptive method names and comments for clarity. Ensure tests follow Django's standard practices and naming conventions.