Initial commit
This commit is contained in:
commit
430ae2e266
56 files changed
+10826
No files matched your search
@@ -0,0 +1,31 @@
|
||||
# Development Prompts
|
||||
|
||||
This directory contains prompts specifically designed for software development tasks.
|
||||
|
||||
## Categories
|
||||
|
||||
- **Code Review**: Prompts for analyzing and improving code quality
|
||||
- **Documentation**: Generating technical documentation and comments
|
||||
- **Debugging**: Finding and fixing issues in code
|
||||
- **Architecture**: Planning system design and structure
|
||||
- **Testing**: Creating test cases and testing strategies
|
||||
- **Refactoring**: Improving code structure and maintainability
|
||||
|
||||
## Example Prompts
|
||||
|
||||
- `code-review.md` - Comprehensive code review assistant
|
||||
- `documentation-generator.md` - Auto-generate documentation from code
|
||||
- `bug-hunter.md` - Debug assistance and error analysis
|
||||
- `architecture-planner.md` - System design and planning
|
||||
- `test-case-generator.md` - Create comprehensive test suites
|
||||
- `refactoring-assistant.md` - Code improvement suggestions
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Choose a prompt that matches your development task
|
||||
2. Customize the prompt with your specific code or requirements
|
||||
3. Run it through your preferred AI model
|
||||
4. Iterate and refine based on the results
|
||||
|
||||
---
|
||||
*Add your development prompts to this directory following the template structure.*
|
||||
@@ -0,0 +1,331 @@
|
||||
# Architecture Planner
|
||||
|
||||
## Description
|
||||
|
||||
Helps design and plan software architecture, including system design, component relationships, technology stack decisions, and scalability considerations. Provides structured architectural guidance for projects of any size.
|
||||
|
||||
## Usage
|
||||
|
||||
Describe your project requirements, constraints, and goals. Include information about expected scale, performance requirements, team size, and any existing systems. Works for both new projects and architectural refactoring.
|
||||
|
||||
## Prompt
|
||||
|
||||
```markdown
|
||||
Help me design the software architecture for the following project:
|
||||
|
||||
**Project Overview:**
|
||||
[Describe what the system should do and its main purpose]
|
||||
|
||||
**Requirements:**
|
||||
- **Functional Requirements:**
|
||||
- [Core features and capabilities needed]
|
||||
- [User interactions and workflows]
|
||||
- [Data processing requirements]
|
||||
|
||||
- **Non-Functional Requirements:**
|
||||
- **Scale**: [Expected users, data volume, transaction volume]
|
||||
- **Performance**: [Response time, throughput requirements]
|
||||
- **Availability**: [Uptime requirements, disaster recovery needs]
|
||||
- **Security**: [Authentication, authorization, data protection needs]
|
||||
|
||||
**Constraints:**
|
||||
- **Budget**: [Budget limitations or cost considerations]
|
||||
- **Team**: [Team size, skill levels, experience with technologies]
|
||||
- **Timeline**: [Development timeline and milestones]
|
||||
- **Technology**: [Required technologies, existing systems to integrate]
|
||||
- **Compliance**: [Regulatory or industry standards to follow]
|
||||
|
||||
**Current State:** [Existing systems, legacy code, or starting from scratch]
|
||||
|
||||
Please provide:
|
||||
|
||||
1. **High-Level Architecture**
|
||||
- System overview and major components
|
||||
- Architecture pattern recommendation (MVC, microservices, etc.)
|
||||
- Data flow and component interactions
|
||||
|
||||
2. **Technology Stack Recommendations**
|
||||
- Backend technologies and frameworks
|
||||
- Database choices and rationale
|
||||
- Frontend technologies
|
||||
- Infrastructure and deployment options
|
||||
|
||||
3. **Detailed Component Design**
|
||||
- Core services/modules breakdown
|
||||
- API design considerations
|
||||
- Data models and relationships
|
||||
|
||||
4. **Scalability Strategy**
|
||||
- How to handle growth
|
||||
- Performance optimization points
|
||||
- Caching strategies
|
||||
|
||||
5. **Security Architecture**
|
||||
- Authentication and authorization approach
|
||||
- Data protection measures
|
||||
- Security best practices
|
||||
|
||||
6. **Implementation Roadmap**
|
||||
- Development phases and priorities
|
||||
- MVP scope and incremental features
|
||||
- Risk mitigation strategies
|
||||
```
|
||||
|
||||
## Example Input
|
||||
|
||||
```markdown
|
||||
**Project Overview:**
|
||||
A real-time collaboration platform for remote teams, similar to Slack but with integrated video calls, file sharing, and project management features.
|
||||
|
||||
**Requirements:**
|
||||
- **Functional Requirements:**
|
||||
- Real-time messaging and channels
|
||||
- Video/audio calling for up to 50 participants
|
||||
- File upload and sharing (up to 100MB per file)
|
||||
- Task management and project boards
|
||||
- User authentication and team management
|
||||
|
||||
- **Non-Functional Requirements:**
|
||||
- **Scale**: 10,000 concurrent users, 100,000 total users
|
||||
- **Performance**: <200ms message delivery, <3s file upload
|
||||
- **Availability**: 99.9% uptime
|
||||
- **Security**: Enterprise-grade security, GDPR compliance
|
||||
|
||||
**Constraints:**
|
||||
- **Budget**: $50k initial development budget
|
||||
- **Team**: 5 full-stack developers, 1 DevOps engineer
|
||||
- **Timeline**: 6 months to MVP, 12 months to full feature set
|
||||
- **Technology**: Team has experience with React, Node.js, PostgreSQL
|
||||
```
|
||||
|
||||
## Example Output
|
||||
|
||||
```markdown
|
||||
# Collaboration Platform Architecture Design
|
||||
|
||||
## High-Level Architecture
|
||||
|
||||
### Architecture Pattern: Microservices with Event-Driven Communication
|
||||
```
|
||||
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ Web Client │ │ Mobile Client │ │ Desktop App │
|
||||
│ (React) │ │ (React Native)│ │ (Electron) │
|
||||
└─────────┬───────┘ └─────────┬───────┘ └─────────┬───────┘
|
||||
│ │ │
|
||||
└──────────────────────┼──────────────────────┘
|
||||
│
|
||||
┌─────────────┴─────────────┐
|
||||
│ API Gateway │
|
||||
│ (Authentication + │
|
||||
│ Load Balancing) │
|
||||
└─────────────┬─────────────┘
|
||||
│
|
||||
┌─────────────┬───────────────┼───────────────┬─────────────┐
|
||||
│ │ │ │ │
|
||||
┌───▼───┐ ┌───▼───┐ ┌───▼───┐ ┌───▼───┐ ┌───▼───┐
|
||||
│Message│ │ User │ │ File │ │Video │ │Project│
|
||||
│Service│ │Service│ │Service│ │Service│ │Service│
|
||||
└───┬───┘ └───┬───┘ └───┬───┘ └───┬───┘ └───┬───┘
|
||||
│ │ │ │ │
|
||||
└────────────┼───────────────┼──────────────┼────────────┘
|
||||
│ │ │
|
||||
┌────▼────┐ ┌────▼────┐ ┌────▼────┐
|
||||
│PostgreSQL│ │ S3 │ │ Redis │
|
||||
│(Primary) │ │(Files) │ │(Cache) │
|
||||
└─────────┘ └─────────┘ └─────────┘
|
||||
|
||||
```
|
||||
|
||||
## Technology Stack Recommendations
|
||||
|
||||
### Backend
|
||||
- **Language**: Node.js with TypeScript (team familiarity)
|
||||
- **Framework**: Express.js with Fastify for high-performance services
|
||||
- **Real-time**: Socket.io for WebSocket connections
|
||||
- **Message Queue**: Redis for pub/sub and job queues
|
||||
- **Video**: WebRTC with Kurento Media Server for large calls
|
||||
|
||||
### Database
|
||||
- **Primary**: PostgreSQL for structured data (users, teams, projects)
|
||||
- **Cache**: Redis for sessions, real-time data, and message caching
|
||||
- **File Storage**: AWS S3 or MinIO for file uploads
|
||||
- **Search**: Elasticsearch for message search functionality
|
||||
|
||||
### Frontend
|
||||
- **Framework**: React with TypeScript
|
||||
- **State Management**: Redux Toolkit for complex state
|
||||
- **Real-time**: Socket.io client
|
||||
- **UI Library**: Material-UI or Ant Design for rapid development
|
||||
|
||||
### Infrastructure
|
||||
- **Containerization**: Docker with Docker Compose for development
|
||||
- **Orchestration**: Kubernetes for production (or start with simple VPS)
|
||||
- **CI/CD**: GitHub Actions
|
||||
- **Monitoring**: Prometheus + Grafana
|
||||
|
||||
## Detailed Component Design
|
||||
|
||||
### 1. Message Service
|
||||
```typescript
|
||||
interface MessageService {
|
||||
sendMessage(channelId: string, message: MessagePayload): Promise<void>
|
||||
getChannelHistory(channelId: string, limit: number): Promise<Message[]>
|
||||
subscribeToChannel(channelId: string, userId: string): void
|
||||
}
|
||||
```
|
||||
|
||||
- Real-time message delivery via Socket.io
|
||||
- Message persistence in PostgreSQL
|
||||
- Redis for message caching and pub/sub
|
||||
|
||||
### 2. User Service
|
||||
|
||||
```typescript
|
||||
interface UserService {
|
||||
authenticate(credentials: LoginCredentials): Promise<AuthResult>
|
||||
createUser(userData: CreateUserRequest): Promise<User>
|
||||
updateUserStatus(userId: string, status: UserStatus): Promise<void>
|
||||
}
|
||||
```
|
||||
|
||||
- JWT-based authentication
|
||||
- User management and team assignments
|
||||
- Integration with external OAuth providers
|
||||
|
||||
### 3. File Service
|
||||
|
||||
- Secure file upload with virus scanning
|
||||
- Progressive upload for large files
|
||||
- Automatic thumbnail generation for images
|
||||
- CDN integration for fast delivery
|
||||
|
||||
### 4. Video Service
|
||||
|
||||
- WebRTC peer-to-peer for small calls (<5 people)
|
||||
- Selective Forwarding Unit (SFU) for larger calls
|
||||
- Recording capabilities with cloud storage
|
||||
- Screen sharing support
|
||||
|
||||
## Scalability Strategy
|
||||
|
||||
### Phase 1 (MVP): Monolithic Start
|
||||
|
||||
- Single Node.js application
|
||||
- PostgreSQL primary database
|
||||
- Redis for caching
|
||||
- Supports up to 1,000 concurrent users
|
||||
|
||||
### Phase 2 (Growth): Service Separation
|
||||
|
||||
- Extract message service for independent scaling
|
||||
- Add read replicas for database
|
||||
- Implement horizontal scaling for video services
|
||||
- CDN for static assets
|
||||
|
||||
### Phase 3 (Scale): Full Microservices
|
||||
|
||||
- Complete service decomposition
|
||||
- Database sharding by team/organization
|
||||
- Multi-region deployment
|
||||
- Advanced caching strategies
|
||||
|
||||
## Security Architecture
|
||||
|
||||
### Authentication & Authorization
|
||||
|
||||
```
|
||||
User → API Gateway → JWT Validation → Service Authorization
|
||||
```
|
||||
|
||||
- JWT tokens with short expiry (15 minutes)
|
||||
- Refresh token rotation
|
||||
- Role-based access control (RBAC)
|
||||
- Rate limiting per user/IP
|
||||
|
||||
### Data Protection
|
||||
|
||||
- End-to-end encryption for sensitive messages
|
||||
- At-rest encryption for database and files
|
||||
- HTTPS everywhere with HSTS headers
|
||||
- Input validation and sanitization
|
||||
|
||||
## Implementation Roadmap
|
||||
|
||||
### Phase 1 (Months 1-2): Core MVP
|
||||
|
||||
**Goal**: Basic messaging and user management
|
||||
|
||||
- User authentication and team creation
|
||||
- Real-time messaging in channels
|
||||
- Basic file sharing
|
||||
- Simple web client
|
||||
|
||||
**MVP Features:**
|
||||
|
||||
- Login/signup
|
||||
- Create teams and channels
|
||||
- Send/receive messages
|
||||
- Upload/download files
|
||||
|
||||
### Phase 2 (Months 3-4): Enhanced Features
|
||||
|
||||
- Video calling (up to 10 participants)
|
||||
- Message search
|
||||
- Mobile-responsive design
|
||||
- Basic project management features
|
||||
|
||||
### Phase 3 (Months 5-6): Production Ready
|
||||
|
||||
- Advanced video features (screen sharing, recording)
|
||||
- Full project management integration
|
||||
- Admin dashboard
|
||||
- Comprehensive security features
|
||||
|
||||
### Risk Mitigation
|
||||
|
||||
1. **Technical Risks**:
|
||||
- Start with proven technologies
|
||||
- Build comprehensive testing early
|
||||
- Plan for database migration strategies
|
||||
|
||||
2. **Scalability Risks**:
|
||||
- Design with microservices in mind from day 1
|
||||
- Use feature flags for gradual rollouts
|
||||
- Monitor performance metrics continuously
|
||||
|
||||
3. **Security Risks**:
|
||||
- Regular security audits
|
||||
- Implement logging and monitoring
|
||||
- Have incident response plan ready
|
||||
|
||||
## Success Metrics
|
||||
|
||||
- Message delivery latency <200ms
|
||||
- 99.9% uptime
|
||||
- Support 10,000 concurrent users
|
||||
- File upload success rate >99%
|
||||
- Video call quality metrics
|
||||
|
||||
```
|
||||
|
||||
## Variations
|
||||
- **Enterprise Architecture**: Focus on enterprise patterns and governance
|
||||
- **Microservices Design**: Deep dive into service decomposition
|
||||
- **Cloud-Native**: Emphasize cloud services and serverless architectures
|
||||
- **Legacy Migration**: Focus on modernizing existing systems
|
||||
|
||||
## Tips
|
||||
- Be specific about scale and performance requirements
|
||||
- Include budget and timeline constraints for realistic recommendations
|
||||
- Mention team expertise to align technology choices
|
||||
- Consider starting simple and evolving the architecture over time
|
||||
- Always include security and compliance considerations
|
||||
|
||||
## Related Prompts
|
||||
- `code-review.md` - For reviewing architectural decisions in code
|
||||
- `documentation-generator.md` - For creating architecture documentation
|
||||
- `test-case-generator.md` - For testing architectural components
|
||||
|
||||
## Tags
|
||||
`architecture` `system-design` `scalability` `technology-stack` `development` `planning`
|
||||
@@ -0,0 +1,254 @@
|
||||
# Bug Hunter - Debug Assistant
|
||||
|
||||
## Description
|
||||
|
||||
A systematic debugging assistant that helps identify, analyze, and resolve software bugs and errors. Provides step-by-step troubleshooting approaches and suggests fixes for various types of issues.
|
||||
|
||||
## Usage
|
||||
|
||||
Provide error messages, problematic code, or describe unexpected behavior. Include relevant context like environment, inputs, and expected vs. actual outcomes. Works across all programming languages.
|
||||
|
||||
## Prompt
|
||||
|
||||
```markdown
|
||||
Help me debug the following issue. Please provide a systematic analysis:
|
||||
|
||||
**Problem Description:**
|
||||
[Describe what's happening vs. what should happen]
|
||||
|
||||
**Error Message/Symptoms:**
|
||||
```
|
||||
|
||||
[PASTE ERROR MESSAGE OR DESCRIBE SYMPTOMS]
|
||||
|
||||
```
|
||||
|
||||
**Code:**
|
||||
```
|
||||
|
||||
[PASTE RELEVANT CODE]
|
||||
|
||||
```
|
||||
|
||||
**Environment:**
|
||||
- Programming Language: [language and version]
|
||||
- Framework/Libraries: [if applicable]
|
||||
- Operating System: [OS details]
|
||||
- Input Data: [sample inputs that cause the issue]
|
||||
|
||||
Please analyze this by:
|
||||
|
||||
1. **Root Cause Analysis**
|
||||
- Identify the likely cause of the issue
|
||||
- Explain why this error occurs
|
||||
- Point to specific lines or components
|
||||
|
||||
2. **Debugging Strategy**
|
||||
- Step-by-step debugging approach
|
||||
- What to check or test first
|
||||
- Logging/debugging techniques to use
|
||||
|
||||
3. **Solution Options**
|
||||
- Primary fix recommendation
|
||||
- Alternative approaches
|
||||
- Preventive measures
|
||||
|
||||
4. **Testing Approach**
|
||||
- How to verify the fix works
|
||||
- Edge cases to test
|
||||
- Regression testing recommendations
|
||||
|
||||
Additional context:
|
||||
[ANY OTHER RELEVANT INFORMATION]
|
||||
```
|
||||
|
||||
## Example Input
|
||||
|
||||
```markdown
|
||||
**Problem Description:**
|
||||
My Python web scraper randomly fails with connection errors, but the website is accessible in the browser.
|
||||
|
||||
**Error Message:**
|
||||
```
|
||||
|
||||
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='example.com', port=443):
|
||||
Max retries exceeded with url: /api/data (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f8b8c0b1d90>: Failed to establish a new connection: [Errno 111] Connection refused'))
|
||||
|
||||
```
|
||||
|
||||
**Code:**
|
||||
```python
|
||||
import requests
|
||||
import time
|
||||
|
||||
def scrape_data():
|
||||
urls = ["https://example.com/api/data", "https://example.com/api/users"]
|
||||
results = []
|
||||
|
||||
for url in urls:
|
||||
response = requests.get(url)
|
||||
results.append(response.json())
|
||||
time.sleep(0.1)
|
||||
|
||||
return results
|
||||
```
|
||||
|
||||
**Environment:**
|
||||
|
||||
- Python 3.9
|
||||
- requests library 2.28.1
|
||||
- Running on Ubuntu 20.04
|
||||
- Input: Multiple URLs being scraped in sequence
|
||||
|
||||
```
|
||||
|
||||
## Example Output
|
||||
```
|
||||
|
||||
# Debug Analysis Report
|
||||
|
||||
## Root Cause Analysis
|
||||
|
||||
**Primary Issue:** Rate limiting and connection management
|
||||
The error indicates connection refusal, which typically occurs when:
|
||||
|
||||
1. **Rate Limiting**: The server is blocking requests due to too many rapid connections
|
||||
2. **Connection Pool Exhaustion**: Not properly managing HTTP connections
|
||||
3. **Server-side blocking**: Anti-bot measures detecting automated requests
|
||||
|
||||
**Specific Issues in Code:**
|
||||
|
||||
- Line 8: No error handling for failed requests
|
||||
- Line 9: Very short delay (0.1s) may trigger rate limiting
|
||||
- No User-Agent header (common anti-bot trigger)
|
||||
- No retry mechanism for transient failures
|
||||
|
||||
## Debugging Strategy
|
||||
|
||||
### Immediate Debugging Steps
|
||||
|
||||
1. **Test connectivity**: `curl -I https://example.com/api/data`
|
||||
2. **Check rate limits**: Increase delay to 2-3 seconds
|
||||
3. **Monitor network**: Use `netstat` or Wireshark to see connection states
|
||||
4. **Add logging**: Log response status codes before the error
|
||||
|
||||
### Code for Debugging
|
||||
|
||||
```python
|
||||
import logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# Add this before your request
|
||||
print(f"Attempting to connect to: {url}")
|
||||
response = requests.get(url, timeout=10)
|
||||
print(f"Response status: {response.status_code}")
|
||||
```
|
||||
|
||||
## Solution Options
|
||||
|
||||
### Primary Fix (Recommended)
|
||||
|
||||
```python
|
||||
import requests
|
||||
import time
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util.retry import Retry
|
||||
|
||||
def scrape_data():
|
||||
# Configure session with retry strategy
|
||||
session = requests.Session()
|
||||
retry_strategy = Retry(
|
||||
total=3,
|
||||
backoff_factor=1,
|
||||
status_forcelist=[429, 500, 502, 503, 504],
|
||||
)
|
||||
adapter = HTTPAdapter(max_retries=retry_strategy)
|
||||
session.mount("http://", adapter)
|
||||
session.mount("https://", adapter)
|
||||
|
||||
# Add headers to appear more like a browser
|
||||
headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
'Accept': 'application/json',
|
||||
'Accept-Language': 'en-US,en;q=0.9'
|
||||
}
|
||||
|
||||
urls = ["https://example.com/api/data", "https://example.com/api/users"]
|
||||
results = []
|
||||
|
||||
for url in urls:
|
||||
try:
|
||||
response = session.get(url, headers=headers, timeout=30)
|
||||
response.raise_for_status()
|
||||
results.append(response.json())
|
||||
# Respectful delay
|
||||
time.sleep(2)
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching {url}: {e}")
|
||||
continue
|
||||
|
||||
return results
|
||||
```
|
||||
|
||||
### Alternative Approaches
|
||||
|
||||
1. **Use connection pooling**: Implement session reuse
|
||||
2. **Implement exponential backoff**: Gradually increase delays
|
||||
3. **Add proxy rotation**: If being blocked by IP
|
||||
4. **Use async requests**: For better connection management
|
||||
|
||||
## Testing Approach
|
||||
|
||||
### Verification Steps
|
||||
|
||||
1. **Unit test**: Test with single URL first
|
||||
2. **Load test**: Gradually increase number of URLs
|
||||
3. **Network simulation**: Test with poor connectivity
|
||||
4. **Edge cases**: Test with invalid URLs, timeouts
|
||||
|
||||
### Test Code
|
||||
|
||||
```python
|
||||
def test_scraper():
|
||||
# Test single URL
|
||||
result = scrape_data_single("https://httpbin.org/json")
|
||||
assert result is not None
|
||||
|
||||
# Test with delay
|
||||
start_time = time.time()
|
||||
scrape_data()
|
||||
duration = time.time() - start_time
|
||||
assert duration >= 2 # Ensure delay is working
|
||||
```
|
||||
|
||||
## Prevention Measures
|
||||
|
||||
- Always implement proper error handling
|
||||
- Use session objects for connection reuse
|
||||
- Add appropriate delays between requests
|
||||
- Include realistic User-Agent headers
|
||||
- Implement retry logic for transient failures
|
||||
- Monitor rate limits and adjust accordingly
|
||||
|
||||
```
|
||||
|
||||
## Variations
|
||||
- **Performance Issues**: Focus on optimization and profiling
|
||||
- **Security Bugs**: Emphasize vulnerability analysis and secure coding
|
||||
- **Integration Issues**: Focus on API and service integration problems
|
||||
- **Frontend Debugging**: Specialized for JavaScript/browser issues
|
||||
|
||||
## Tips
|
||||
- Include full error stack traces when possible
|
||||
- Provide minimal reproducible examples
|
||||
- Mention any recent changes that might have introduced the bug
|
||||
- Include relevant log files or console output
|
||||
- Specify if the issue is intermittent or consistent
|
||||
|
||||
## Related Prompts
|
||||
- `code-review.md` - For preventing bugs through better code quality
|
||||
- `test-case-generator.md` - For creating tests to catch bugs
|
||||
- `refactoring-assistant.md` - For improving code structure to prevent issues
|
||||
|
||||
## Tags
|
||||
`debugging` `troubleshooting` `error-analysis` `bug-fixing` `development` `problem-solving`
|
||||
@@ -0,0 +1,162 @@
|
||||
# Code Review Assistant
|
||||
|
||||
## Description
|
||||
|
||||
A comprehensive code review prompt that analyzes code quality, identifies potential issues, suggests improvements, and provides detailed feedback on best practices, security, performance, and maintainability.
|
||||
|
||||
## Usage
|
||||
|
||||
Paste your code along with any specific concerns or focus areas. Works with any programming language. Best used for reviewing pull requests, refactoring decisions, or general code quality assessment.
|
||||
|
||||
## Prompt
|
||||
|
||||
```markdown
|
||||
Please perform a comprehensive code review of the following code. Analyze it for:
|
||||
|
||||
1. **Code Quality & Style**
|
||||
- Readability and clarity
|
||||
- Naming conventions
|
||||
- Code organization and structure
|
||||
- Adherence to language-specific best practices
|
||||
|
||||
2. **Performance & Efficiency**
|
||||
- Algorithm efficiency
|
||||
- Resource usage
|
||||
- Potential bottlenecks
|
||||
- Optimization opportunities
|
||||
|
||||
3. **Security Concerns**
|
||||
- Potential vulnerabilities
|
||||
- Input validation
|
||||
- Data handling practices
|
||||
- Security best practices
|
||||
|
||||
4. **Maintainability**
|
||||
- Code complexity
|
||||
- Documentation and comments
|
||||
- Modularity and reusability
|
||||
- Error handling
|
||||
|
||||
5. **Testing & Reliability**
|
||||
- Edge cases consideration
|
||||
- Error scenarios
|
||||
- Testing recommendations
|
||||
|
||||
Please provide:
|
||||
- Specific line-by-line feedback where applicable
|
||||
- Priority levels for each issue (Critical/High/Medium/Low)
|
||||
- Concrete suggestions for improvement
|
||||
- Positive aspects worth highlighting
|
||||
|
||||
Code to review:
|
||||
```
|
||||
|
||||
[YOUR CODE HERE]
|
||||
|
||||
```
|
||||
|
||||
Additional context or specific concerns:
|
||||
[SPECIFY ANY PARTICULAR AREAS TO FOCUS ON]
|
||||
```
|
||||
|
||||
## Example Input
|
||||
|
||||
```markdown
|
||||
```javascript
|
||||
function calculateDiscount(price, discountPercent) {
|
||||
var discount = price * discountPercent / 100;
|
||||
var finalPrice = price - discount;
|
||||
return finalPrice;
|
||||
}
|
||||
|
||||
function processOrder(items) {
|
||||
var total = 0;
|
||||
for(var i = 0; i < items.length; i++) {
|
||||
total += calculateDiscount(items[i].price, items[i].discount);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
```
|
||||
|
||||
```
|
||||
|
||||
## Example Output
|
||||
|
||||
```markdown
|
||||
## Code Review Feedback
|
||||
|
||||
### Overall Assessment
|
||||
The code is functional but has several areas for improvement in terms of best practices, error handling, and modern JavaScript conventions.
|
||||
|
||||
### Specific Issues
|
||||
|
||||
**Medium Priority Issues:**
|
||||
1. **Line 1-4**: Use `const`/`let` instead of `var` for better scoping
|
||||
2. **Line 1**: Missing input validation - function should handle edge cases
|
||||
3. **Line 6-10**: Consider using modern array methods like `reduce()`
|
||||
|
||||
**Low Priority Issues:**
|
||||
1. **General**: Add JSDoc comments for better documentation
|
||||
2. **Line 6**: Variable naming could be more descriptive
|
||||
|
||||
### Suggested Improvements
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* Calculates discounted price
|
||||
* @param {number} price - Original price (must be positive)
|
||||
* @param {number} discountPercent - Discount percentage (0-100)
|
||||
* @returns {number} Final price after discount
|
||||
*/
|
||||
function calculateDiscount(price, discountPercent) {
|
||||
if (price < 0 || discountPercent < 0 || discountPercent > 100) {
|
||||
throw new Error('Invalid input parameters');
|
||||
}
|
||||
|
||||
const discount = price * discountPercent / 100;
|
||||
return price - discount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates total for order with individual item discounts
|
||||
* @param {Array} items - Array of items with price and discount properties
|
||||
* @returns {number} Total order amount
|
||||
*/
|
||||
function processOrder(items) {
|
||||
if (!Array.isArray(items)) {
|
||||
throw new Error('Items must be an array');
|
||||
}
|
||||
|
||||
return items.reduce((total, item) => {
|
||||
return total + calculateDiscount(item.price, item.discount);
|
||||
}, 0);
|
||||
}
|
||||
```
|
||||
|
||||
### Positive Aspects
|
||||
|
||||
- Clear function naming that describes purpose
|
||||
- Simple, focused functions following single responsibility principle
|
||||
- Clean separation between discount calculation and order processing
|
||||
|
||||
```
|
||||
|
||||
## Variations
|
||||
- **Security-Focused**: Emphasize security vulnerabilities and data protection
|
||||
- **Performance-Focused**: Concentrate on optimization and efficiency
|
||||
- **Junior Developer**: Provide more educational explanations and learning resources
|
||||
- **Legacy Code**: Focus on modernization and technical debt reduction
|
||||
|
||||
## Tips
|
||||
- Provide the programming language for more targeted feedback
|
||||
- Include context about the application domain for better security analysis
|
||||
- Mention any specific coding standards or frameworks being used
|
||||
- Be specific about performance requirements or constraints
|
||||
|
||||
## Related Prompts
|
||||
- `refactoring-assistant.md` - For code improvement suggestions
|
||||
- `documentation-generator.md` - For adding comprehensive documentation
|
||||
- `test-case-generator.md` - For creating tests for reviewed code
|
||||
|
||||
## Tags
|
||||
`code-review` `quality-assurance` `best-practices` `development` `debugging`
|
||||
@@ -0,0 +1,242 @@
|
||||
# Documentation Generator
|
||||
|
||||
## Description
|
||||
|
||||
Automatically generates comprehensive documentation from code, including API documentation, README files, inline comments, and user guides. Supports multiple programming languages and documentation formats.
|
||||
|
||||
## Usage
|
||||
|
||||
Provide your code and specify the type of documentation needed. Works best with well-structured code that has clear function/class definitions. Specify the target audience and format requirements.
|
||||
|
||||
## Prompt
|
||||
|
||||
```markdown
|
||||
Generate comprehensive documentation for the following code. Please create:
|
||||
|
||||
1. **API Documentation**
|
||||
- Function/method signatures
|
||||
- Parameter descriptions with types
|
||||
- Return value specifications
|
||||
- Usage examples
|
||||
- Error conditions
|
||||
|
||||
2. **Inline Comments**
|
||||
- Code explanation comments
|
||||
- Complex logic breakdown
|
||||
- Algorithm descriptions
|
||||
- Performance considerations
|
||||
|
||||
3. **README Section** (if applicable)
|
||||
- Purpose and overview
|
||||
- Installation/setup instructions
|
||||
- Basic usage examples
|
||||
- Configuration options
|
||||
|
||||
4. **User Guide Elements**
|
||||
- Step-by-step usage instructions
|
||||
- Common use cases
|
||||
- Troubleshooting tips
|
||||
- Best practices
|
||||
|
||||
Documentation requirements:
|
||||
- Target audience: [developers/end-users/technical writers]
|
||||
- Format: [Markdown/JSDoc/Sphinx/other]
|
||||
- Documentation style: [comprehensive/concise/beginner-friendly]
|
||||
|
||||
Code to document:
|
||||
```
|
||||
|
||||
[YOUR CODE HERE]
|
||||
|
||||
```
|
||||
|
||||
Additional context:
|
||||
[PROJECT PURPOSE, DEPENDENCIES, SPECIAL REQUIREMENTS]
|
||||
```
|
||||
|
||||
## Example Input
|
||||
|
||||
```markdownpython
|
||||
import requests
|
||||
import json
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
class WeatherAPI:
|
||||
def __init__(self, api_key: str, base_url: str = "https://api.weather.com"):
|
||||
self.api_key = api_key
|
||||
self.base_url = base_url
|
||||
|
||||
def get_current_weather(self, city: str, units: str = "metric") -> Dict:
|
||||
endpoint = f"{self.base_url}/current"
|
||||
params = {
|
||||
"city": city,
|
||||
"units": units,
|
||||
"api_key": self.api_key
|
||||
}
|
||||
response = requests.get(endpoint, params=params)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def get_forecast(self, city: str, days: int = 5) -> List[Dict]:
|
||||
endpoint = f"{self.base_url}/forecast"
|
||||
params = {
|
||||
"city": city,
|
||||
"days": days,
|
||||
"api_key": self.api_key
|
||||
}
|
||||
response = requests.get(endpoint, params=params)
|
||||
response.raise_for_status()
|
||||
return response.json()["forecast"]
|
||||
```
|
||||
|
||||
## Example Output
|
||||
|
||||
```markdownmarkdown
|
||||
# WeatherAPI Documentation
|
||||
|
||||
## Overview
|
||||
The WeatherAPI class provides a simple interface to fetch current weather data and forecasts for any city using a weather service API.
|
||||
|
||||
## Installation
|
||||
```bash
|
||||
pip install requests
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```python
|
||||
from weather_api import WeatherAPI
|
||||
|
||||
# Initialize the API client
|
||||
weather = WeatherAPI(api_key="your_api_key_here")
|
||||
|
||||
# Get current weather
|
||||
current = weather.get_current_weather("New York")
|
||||
print(f"Temperature: {current['temperature']}°C")
|
||||
|
||||
# Get 7-day forecast
|
||||
forecast = weather.get_forecast("London", days=7)
|
||||
for day in forecast:
|
||||
print(f"{day['date']}: {day['temperature']}°C, {day['description']}")
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### Class: WeatherAPI
|
||||
|
||||
#### Constructor
|
||||
|
||||
```python
|
||||
WeatherAPI(api_key: str, base_url: str = "https://api.weather.com")
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `api_key` (str): Your API key for the weather service
|
||||
- `base_url` (str, optional): Base URL for the weather API. Defaults to "<https://api.weather.com>"
|
||||
|
||||
**Example:**
|
||||
|
||||
```python
|
||||
weather = WeatherAPI("your_api_key", "https://custom-weather-api.com")
|
||||
```
|
||||
|
||||
#### get_current_weather()
|
||||
|
||||
```python
|
||||
get_current_weather(city: str, units: str = "metric") -> Dict
|
||||
```
|
||||
|
||||
Retrieves current weather conditions for the specified city.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `city` (str): Name of the city to get weather for
|
||||
- `units` (str, optional): Temperature units ("metric", "imperial", "kelvin"). Defaults to "metric"
|
||||
|
||||
**Returns:**
|
||||
|
||||
- `Dict`: Weather data containing temperature, humidity, description, etc.
|
||||
|
||||
**Raises:**
|
||||
|
||||
- `requests.HTTPError`: If the API request fails
|
||||
- `requests.ConnectionError`: If unable to connect to the API
|
||||
|
||||
**Example:**
|
||||
|
||||
```python
|
||||
weather_data = weather.get_current_weather("Tokyo", units="imperial")
|
||||
temp_f = weather_data["temperature"] # Temperature in Fahrenheit
|
||||
```
|
||||
|
||||
#### get_forecast()
|
||||
|
||||
```python
|
||||
get_forecast(city: str, days: int = 5) -> List[Dict]
|
||||
```
|
||||
|
||||
Retrieves weather forecast for the specified city.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `city` (str): Name of the city to get forecast for
|
||||
- `days` (int, optional): Number of days to forecast (1-10). Defaults to 5
|
||||
|
||||
**Returns:**
|
||||
|
||||
- `List[Dict]`: List of daily forecast data
|
||||
|
||||
**Raises:**
|
||||
|
||||
- `requests.HTTPError`: If the API request fails
|
||||
- `ValueError`: If days parameter is outside valid range
|
||||
|
||||
**Example:**
|
||||
|
||||
```python
|
||||
forecast = weather.get_forecast("Paris", days=3)
|
||||
tomorrow = forecast[1] # Second day (tomorrow)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
All methods may raise HTTP-related exceptions. Implement proper error handling:
|
||||
|
||||
```python
|
||||
try:
|
||||
weather_data = weather.get_current_weather("InvalidCity")
|
||||
except requests.HTTPError as e:
|
||||
print(f"API error: {e}")
|
||||
except requests.ConnectionError:
|
||||
print("Unable to connect to weather service")
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
- Store your API key securely (environment variables)
|
||||
- Implement rate limiting to avoid API quota issues
|
||||
- Cache responses when appropriate to reduce API calls
|
||||
- Validate city names before making requests
|
||||
|
||||
```
|
||||
|
||||
## Variations
|
||||
- **API-Only**: Focus only on API documentation with technical details
|
||||
- **User Manual**: Create end-user focused documentation with tutorials
|
||||
- **Inline Comments**: Generate only code comments and docstrings
|
||||
- **Architecture Docs**: Create high-level system architecture documentation
|
||||
|
||||
## Tips
|
||||
- Include the programming language for language-specific documentation standards
|
||||
- Specify if you need examples for specific use cases
|
||||
- Mention any existing documentation standards or tools used in your project
|
||||
- Provide context about the intended users of the documentation
|
||||
|
||||
## Related Prompts
|
||||
- `code-review.md` - For improving code before documenting
|
||||
- `architecture-planner.md` - For system-level documentation
|
||||
- `test-case-generator.md` - For creating documented test examples
|
||||
|
||||
## Tags
|
||||
`documentation` `api-docs` `comments` `readme` `development` `technical-writing`
|
||||
@@ -0,0 +1,186 @@
|
||||
# Refactoring Assistant
|
||||
|
||||
## Description
|
||||
|
||||
This prompt helps you analyze and refactor existing code to improve its structure, readability, maintainability, and performance while preserving functionality.
|
||||
|
||||
## Usage
|
||||
|
||||
Perfect for improving legacy code, preparing code for new features, reducing technical debt, and following best practices and design patterns.
|
||||
|
||||
## Prompt
|
||||
|
||||
```markdown
|
||||
You are an expert code refactoring assistant. I need help refactoring the following code to improve its quality while maintaining the same functionality.
|
||||
|
||||
**Code to refactor:**
|
||||
```
|
||||
|
||||
[INSERT_CODE_HERE]
|
||||
|
||||
```
|
||||
|
||||
**Context:**
|
||||
- Programming language: [LANGUAGE]
|
||||
- Framework/library: [FRAMEWORK_IF_ANY]
|
||||
- Current issues: [DESCRIBE_PROBLEMS]
|
||||
- Performance requirements: [PERFORMANCE_NEEDS]
|
||||
- Coding standards: [STYLE_GUIDE_IF_ANY]
|
||||
|
||||
Please analyze the code and provide:
|
||||
|
||||
1. **Code Quality Assessment:**
|
||||
- Identify code smells and anti-patterns
|
||||
- Assess readability, maintainability, and performance
|
||||
- Check adherence to SOLID principles
|
||||
- Evaluate naming conventions and structure
|
||||
|
||||
2. **Refactoring Plan:**
|
||||
- List specific improvements needed
|
||||
- Prioritize changes by impact and complexity
|
||||
- Identify any breaking changes
|
||||
- Suggest design patterns if applicable
|
||||
|
||||
3. **Refactored Code:**
|
||||
- Provide the improved version
|
||||
- Add clear comments explaining changes
|
||||
- Ensure functionality is preserved
|
||||
- Follow best practices for the language/framework
|
||||
|
||||
4. **Explanation:**
|
||||
- Explain what was changed and why
|
||||
- Highlight performance improvements
|
||||
- Note any new dependencies or requirements
|
||||
- Provide migration steps if needed
|
||||
|
||||
5. **Testing Recommendations:**
|
||||
- Suggest test cases to verify functionality
|
||||
- Recommend regression testing approach
|
||||
- Identify potential edge cases to test
|
||||
|
||||
Focus on making the code more readable, maintainable, and efficient while following established best practices.
|
||||
```
|
||||
|
||||
## Example Input
|
||||
|
||||
```markdown
|
||||
Code to refactor:
|
||||
```javascript
|
||||
function processUsers(users) {
|
||||
var result = [];
|
||||
for (var i = 0; i < users.length; i++) {
|
||||
if (users[i].age >= 18 && users[i].active == true) {
|
||||
var userData = {};
|
||||
userData.name = users[i].firstName + " " + users[i].lastName;
|
||||
userData.email = users[i].email;
|
||||
userData.category = users[i].age >= 65 ? "senior" : "adult";
|
||||
result.push(userData);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
Context:
|
||||
|
||||
- Programming language: JavaScript (ES6+)
|
||||
- Framework/library: None
|
||||
- Current issues: Old syntax, not functional, poor readability
|
||||
- Performance requirements: Handle arrays up to 10,000 users
|
||||
- Coding standards: ES6+, functional programming preferred
|
||||
|
||||
```
|
||||
|
||||
## Example Output
|
||||
```
|
||||
|
||||
## Code Quality Assessment
|
||||
|
||||
- Uses var instead of const/let
|
||||
- Traditional for loop instead of array methods
|
||||
- Loose equality comparison (==)
|
||||
- Imperative style instead of functional
|
||||
- No input validation
|
||||
- String concatenation instead of template literals
|
||||
|
||||
## Refactoring Plan
|
||||
|
||||
1. Convert to functional programming style
|
||||
2. Use modern ES6+ syntax
|
||||
3. Add input validation
|
||||
4. Extract helper functions for better readability
|
||||
5. Use array methods for better performance
|
||||
|
||||
## Refactored Code
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* Processes users array to extract active adult users with formatted data
|
||||
* @param {Array<Object>} users - Array of user objects
|
||||
* @returns {Array<Object>} Filtered and formatted user data
|
||||
*/
|
||||
const processUsers = (users = []) => {
|
||||
if (!Array.isArray(users)) {
|
||||
throw new Error('Input must be an array');
|
||||
}
|
||||
|
||||
const isEligibleUser = (user) =>
|
||||
user?.age >= 18 && user?.active === true;
|
||||
|
||||
const formatUserData = (user) => ({
|
||||
name: `${user.firstName} ${user.lastName}`,
|
||||
email: user.email,
|
||||
category: user.age >= 65 ? 'senior' : 'adult'
|
||||
});
|
||||
|
||||
return users
|
||||
.filter(isEligibleUser)
|
||||
.map(formatUserData);
|
||||
};
|
||||
```
|
||||
|
||||
## Explanation
|
||||
|
||||
- **Modern syntax**: Used const, arrow functions, template literals
|
||||
- **Functional approach**: Replaced imperative loop with filter/map chain
|
||||
- **Better readability**: Extracted helper functions with descriptive names
|
||||
- **Input validation**: Added type checking and default parameter
|
||||
- **Performance**: Array methods are optimized and more readable
|
||||
- **Strict equality**: Used === instead of ==
|
||||
- **Optional chaining**: Added ?. for safer property access
|
||||
|
||||
## Testing Recommendations
|
||||
|
||||
- Test with empty array, null, undefined inputs
|
||||
- Test with users of various ages (under 18, 18-64, 65+)
|
||||
- Test with inactive users
|
||||
- Test with malformed user objects
|
||||
- Performance test with 10,000+ user array
|
||||
|
||||
```
|
||||
|
||||
## Variations
|
||||
|
||||
### Legacy Code Modernization
|
||||
Focus specifically on updating old syntax and patterns to modern standards while maintaining backward compatibility.
|
||||
|
||||
### Performance-Focused Refactoring
|
||||
Emphasize optimization for speed, memory usage, and scalability in the refactoring suggestions.
|
||||
|
||||
### Security-Focused Refactoring
|
||||
Prioritize identifying and fixing security vulnerabilities, input validation, and secure coding practices.
|
||||
|
||||
## Tips
|
||||
- Always preserve the original functionality unless explicitly asked to change it
|
||||
- Test thoroughly after refactoring to ensure no regressions
|
||||
- Refactor in small, incremental steps rather than large rewrites
|
||||
- Consider the team's skill level when suggesting modern patterns
|
||||
- Document any breaking changes clearly
|
||||
|
||||
## Related Prompts
|
||||
- [Code Review](./code-review.md) - For reviewing code quality
|
||||
- [Test Case Generator](./test-case-generator.md) - For creating tests after refactoring
|
||||
- [Documentation Generator](./documentation-generator.md) - For updating docs after refactoring
|
||||
|
||||
## Tags
|
||||
`refactoring` `code-quality` `best-practices` `modernization` `optimization` `maintainability` `technical-debt` `clean-code`
|
||||
@@ -0,0 +1,420 @@
|
||||
# Test Case Generator
|
||||
|
||||
## Description
|
||||
|
||||
Generates comprehensive test cases and testing strategies for software applications. Creates unit tests, integration tests, user acceptance tests, and edge case scenarios based on code, requirements, or functionality descriptions.
|
||||
|
||||
## Usage
|
||||
|
||||
Provide code, feature requirements, or API specifications that need testing. Specify the testing framework, level of coverage needed, and types of tests required. Works for all programming languages and testing approaches.
|
||||
|
||||
## Prompt
|
||||
|
||||
```markdown
|
||||
Generate comprehensive test cases for the following:
|
||||
|
||||
**Testing Target:**
|
||||
[Function/Class/API/Feature/User Story to be tested]
|
||||
|
||||
**Code/Requirements:**
|
||||
```
|
||||
|
||||
[PROVIDE CODE, API SPEC, OR FEATURE REQUIREMENTS HERE]
|
||||
|
||||
```
|
||||
|
||||
**Testing Requirements:**
|
||||
- **Test Types Needed:** [Unit tests / Integration tests / End-to-end tests / Performance tests]
|
||||
- **Testing Framework:** [Jest/Mocha/PyTest/JUnit/Cypress/Other]
|
||||
- **Coverage Goals:** [Basic functionality / Edge cases / Error conditions / Performance]
|
||||
- **Programming Language:** [JavaScript/Python/Java/C#/Other]
|
||||
|
||||
**Test Scenarios to Include:**
|
||||
1. **Happy Path Tests**
|
||||
- Normal operation with valid inputs
|
||||
- Expected successful outcomes
|
||||
- Standard use cases
|
||||
|
||||
2. **Edge Case Tests**
|
||||
- Boundary value testing
|
||||
- Unusual but valid inputs
|
||||
- Minimum and maximum values
|
||||
|
||||
3. **Error Handling Tests**
|
||||
- Invalid inputs and parameters
|
||||
- Network failures and timeouts
|
||||
- Resource limitations
|
||||
|
||||
4. **Integration Tests** (if applicable)
|
||||
- Component interactions
|
||||
- External service dependencies
|
||||
- Database operations
|
||||
|
||||
5. **Performance Tests** (if applicable)
|
||||
- Load testing scenarios
|
||||
- Response time requirements
|
||||
- Resource usage monitoring
|
||||
|
||||
**Additional Requirements:**
|
||||
- [Mock external dependencies]
|
||||
- [Test data setup/teardown]
|
||||
- [Specific assertion patterns]
|
||||
- [Documentation level needed]
|
||||
|
||||
Please provide:
|
||||
- Test case descriptions and rationale
|
||||
- Complete test code implementations
|
||||
- Test data and setup requirements
|
||||
- Expected outcomes and assertions
|
||||
- Comments explaining complex test logic
|
||||
```
|
||||
|
||||
## Example Input
|
||||
|
||||
```markdown
|
||||
**Testing Target:** User authentication function
|
||||
|
||||
**Code/Requirements:**
|
||||
```javascript
|
||||
async function authenticateUser(email, password) {
|
||||
if (!email || !password) {
|
||||
throw new Error('Email and password are required');
|
||||
}
|
||||
|
||||
if (!isValidEmail(email)) {
|
||||
throw new Error('Invalid email format');
|
||||
}
|
||||
|
||||
const user = await getUserByEmail(email);
|
||||
if (!user) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(password, user.hashedPassword);
|
||||
if (!isPasswordValid) {
|
||||
throw new Error('Invalid password');
|
||||
}
|
||||
|
||||
return {
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
token: generateJWT(user.id)
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Testing Requirements:**
|
||||
|
||||
- **Test Types:** Unit tests with mocking
|
||||
- **Framework:** Jest
|
||||
- **Coverage:** All branches and error conditions
|
||||
- **Language:** JavaScript/Node.js
|
||||
|
||||
```
|
||||
|
||||
## Example Output
|
||||
```javascript
|
||||
// authenticateUser.test.js
|
||||
const bcrypt = require('bcrypt');
|
||||
const { authenticateUser } = require('./auth');
|
||||
const { getUserByEmail, generateJWT, isValidEmail } = require('./utils');
|
||||
|
||||
// Mock dependencies
|
||||
jest.mock('./utils');
|
||||
jest.mock('bcrypt');
|
||||
|
||||
describe('authenticateUser', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Happy Path Tests', () => {
|
||||
test('should authenticate user with valid credentials', async () => {
|
||||
// Arrange
|
||||
const email = 'user@example.com';
|
||||
const password = 'securePassword123';
|
||||
const mockUser = {
|
||||
id: 1,
|
||||
email: 'user@example.com',
|
||||
hashedPassword: 'hashedPassword123'
|
||||
};
|
||||
const mockToken = 'jwt.token.here';
|
||||
|
||||
isValidEmail.mockReturnValue(true);
|
||||
getUserByEmail.mockResolvedValue(mockUser);
|
||||
bcrypt.compare.mockResolvedValue(true);
|
||||
generateJWT.mockReturnValue(mockToken);
|
||||
|
||||
// Act
|
||||
const result = await authenticateUser(email, password);
|
||||
|
||||
// Assert
|
||||
expect(result).toEqual({
|
||||
userId: 1,
|
||||
email: 'user@example.com',
|
||||
token: mockToken
|
||||
});
|
||||
expect(getUserByEmail).toHaveBeenCalledWith(email);
|
||||
expect(bcrypt.compare).toHaveBeenCalledWith(password, mockUser.hashedPassword);
|
||||
expect(generateJWT).toHaveBeenCalledWith(mockUser.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Input Validation Tests', () => {
|
||||
test('should throw error when email is missing', async () => {
|
||||
// Arrange & Act & Assert
|
||||
await expect(authenticateUser(null, 'password123'))
|
||||
.rejects
|
||||
.toThrow('Email and password are required');
|
||||
});
|
||||
|
||||
test('should throw error when password is missing', async () => {
|
||||
// Arrange & Act & Assert
|
||||
await expect(authenticateUser('user@example.com', null))
|
||||
.rejects
|
||||
.toThrow('Email and password are required');
|
||||
});
|
||||
|
||||
test('should throw error when both email and password are missing', async () => {
|
||||
// Arrange & Act & Assert
|
||||
await expect(authenticateUser(null, null))
|
||||
.rejects
|
||||
.toThrow('Email and password are required');
|
||||
});
|
||||
|
||||
test('should throw error when email format is invalid', async () => {
|
||||
// Arrange
|
||||
const invalidEmail = 'invalid-email';
|
||||
const password = 'password123';
|
||||
|
||||
isValidEmail.mockReturnValue(false);
|
||||
|
||||
// Act & Assert
|
||||
await expect(authenticateUser(invalidEmail, password))
|
||||
.rejects
|
||||
.toThrow('Invalid email format');
|
||||
|
||||
expect(isValidEmail).toHaveBeenCalledWith(invalidEmail);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Edge Case Tests', () => {
|
||||
test('should handle empty string email', async () => {
|
||||
// Arrange & Act & Assert
|
||||
await expect(authenticateUser('', 'password123'))
|
||||
.rejects
|
||||
.toThrow('Email and password are required');
|
||||
});
|
||||
|
||||
test('should handle empty string password', async () => {
|
||||
// Arrange & Act & Assert
|
||||
await expect(authenticateUser('user@example.com', ''))
|
||||
.rejects
|
||||
.toThrow('Email and password are required');
|
||||
});
|
||||
|
||||
test('should handle very long email', async () => {
|
||||
// Arrange
|
||||
const longEmail = 'a'.repeat(250) + '@example.com';
|
||||
const password = 'password123';
|
||||
|
||||
isValidEmail.mockReturnValue(true);
|
||||
getUserByEmail.mockResolvedValue(null);
|
||||
|
||||
// Act & Assert
|
||||
await expect(authenticateUser(longEmail, password))
|
||||
.rejects
|
||||
.toThrow('User not found');
|
||||
});
|
||||
});
|
||||
|
||||
describe('User Not Found Tests', () => {
|
||||
test('should throw error when user does not exist', async () => {
|
||||
// Arrange
|
||||
const email = 'nonexistent@example.com';
|
||||
const password = 'password123';
|
||||
|
||||
isValidEmail.mockReturnValue(true);
|
||||
getUserByEmail.mockResolvedValue(null);
|
||||
|
||||
// Act & Assert
|
||||
await expect(authenticateUser(email, password))
|
||||
.rejects
|
||||
.toThrow('User not found');
|
||||
|
||||
expect(getUserByEmail).toHaveBeenCalledWith(email);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Password Validation Tests', () => {
|
||||
test('should throw error when password is incorrect', async () => {
|
||||
// Arrange
|
||||
const email = 'user@example.com';
|
||||
const password = 'wrongPassword';
|
||||
const mockUser = {
|
||||
id: 1,
|
||||
email: 'user@example.com',
|
||||
hashedPassword: 'hashedPassword123'
|
||||
};
|
||||
|
||||
isValidEmail.mockReturnValue(true);
|
||||
getUserByEmail.mockResolvedValue(mockUser);
|
||||
bcrypt.compare.mockResolvedValue(false);
|
||||
|
||||
// Act & Assert
|
||||
await expect(authenticateUser(email, password))
|
||||
.rejects
|
||||
.toThrow('Invalid password');
|
||||
|
||||
expect(bcrypt.compare).toHaveBeenCalledWith(password, mockUser.hashedPassword);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling Tests', () => {
|
||||
test('should handle database connection error', async () => {
|
||||
// Arrange
|
||||
const email = 'user@example.com';
|
||||
const password = 'password123';
|
||||
|
||||
isValidEmail.mockReturnValue(true);
|
||||
getUserByEmail.mockRejectedValue(new Error('Database connection failed'));
|
||||
|
||||
// Act & Assert
|
||||
await expect(authenticateUser(email, password))
|
||||
.rejects
|
||||
.toThrow('Database connection failed');
|
||||
});
|
||||
|
||||
test('should handle bcrypt comparison error', async () => {
|
||||
// Arrange
|
||||
const email = 'user@example.com';
|
||||
const password = 'password123';
|
||||
const mockUser = {
|
||||
id: 1,
|
||||
email: 'user@example.com',
|
||||
hashedPassword: 'hashedPassword123'
|
||||
};
|
||||
|
||||
isValidEmail.mockReturnValue(true);
|
||||
getUserByEmail.mockResolvedValue(mockUser);
|
||||
bcrypt.compare.mockRejectedValue(new Error('Bcrypt error'));
|
||||
|
||||
// Act & Assert
|
||||
await expect(authenticateUser(email, password))
|
||||
.rejects
|
||||
.toThrow('Bcrypt error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Integration Tests', () => {
|
||||
test('should call dependencies in correct order', async () => {
|
||||
// Arrange
|
||||
const email = 'user@example.com';
|
||||
const password = 'password123';
|
||||
const mockUser = {
|
||||
id: 1,
|
||||
email: 'user@example.com',
|
||||
hashedPassword: 'hashedPassword123'
|
||||
};
|
||||
|
||||
isValidEmail.mockReturnValue(true);
|
||||
getUserByEmail.mockResolvedValue(mockUser);
|
||||
bcrypt.compare.mockResolvedValue(true);
|
||||
generateJWT.mockReturnValue('token');
|
||||
|
||||
// Act
|
||||
await authenticateUser(email, password);
|
||||
|
||||
// Assert - verify call order
|
||||
expect(isValidEmail).toHaveBeenCalledBefore(getUserByEmail);
|
||||
expect(getUserByEmail).toHaveBeenCalledBefore(bcrypt.compare);
|
||||
expect(bcrypt.compare).toHaveBeenCalledBefore(generateJWT);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Performance test example
|
||||
describe('authenticateUser Performance', () => {
|
||||
test('should complete authentication within 100ms', async () => {
|
||||
// Arrange
|
||||
const email = 'user@example.com';
|
||||
const password = 'password123';
|
||||
const mockUser = { id: 1, email, hashedPassword: 'hash' };
|
||||
|
||||
isValidEmail.mockReturnValue(true);
|
||||
getUserByEmail.mockResolvedValue(mockUser);
|
||||
bcrypt.compare.mockResolvedValue(true);
|
||||
generateJWT.mockReturnValue('token');
|
||||
|
||||
// Act
|
||||
const startTime = Date.now();
|
||||
await authenticateUser(email, password);
|
||||
const endTime = Date.now();
|
||||
|
||||
// Assert
|
||||
expect(endTime - startTime).toBeLessThan(100);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Test Coverage Report
|
||||
|
||||
The above test suite provides:
|
||||
|
||||
- **Function Coverage**: 100% - All functions are tested
|
||||
- **Branch Coverage**: 100% - All conditional paths tested
|
||||
- **Statement Coverage**: 100% - All code lines executed
|
||||
- **Edge Case Coverage**: Comprehensive boundary testing
|
||||
|
||||
## Test Data Setup
|
||||
|
||||
```javascript
|
||||
// testData/users.js
|
||||
export const validUsers = [
|
||||
{
|
||||
id: 1,
|
||||
email: 'user1@example.com',
|
||||
hashedPassword: '$2b$10$validHashedPassword1'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
email: 'user2@example.com',
|
||||
hashedPassword: '$2b$10$validHashedPassword2'
|
||||
}
|
||||
];
|
||||
|
||||
export const invalidEmails = [
|
||||
'invalid-email',
|
||||
'user@',
|
||||
'@example.com',
|
||||
'user..name@example.com',
|
||||
'user name@example.com'
|
||||
];
|
||||
```
|
||||
|
||||
## Variations
|
||||
|
||||
- **API Testing**: Focus on HTTP endpoint testing with request/response validation
|
||||
- **Frontend Testing**: UI component testing with user interactions
|
||||
- **Database Testing**: Data layer testing with setup/teardown procedures
|
||||
- **Security Testing**: Penetration testing and vulnerability assessment
|
||||
|
||||
## Tips
|
||||
|
||||
- Always test both positive and negative scenarios
|
||||
- Include boundary value testing for numeric inputs
|
||||
- Mock external dependencies to isolate unit tests
|
||||
- Use descriptive test names that explain the scenario
|
||||
- Group related tests using `describe` blocks
|
||||
- Include performance tests for critical functions
|
||||
- Test error conditions as thoroughly as success conditions
|
||||
|
||||
## Related Prompts
|
||||
|
||||
- `code-review.md` - For reviewing test quality and coverage
|
||||
- `bug-hunter.md` - For creating tests that reproduce bugs
|
||||
- `documentation-generator.md` - For documenting test procedures
|
||||
|
||||
## Tags
|
||||
|
||||
`testing` `unit-tests` `test-automation` `quality-assurance` `development` `debugging`
|
||||
Reference in new issue
Block a user