Skip to content
Operations
Command

/generate-tests

Generate comprehensive test suites for code

BOOST
From plugin
guidance-for-claude-code-with-amazon-bedrock
40923 skills25 agents23 commands
Install
> /plugin marketplace add aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock

How it fires

How this command gets triggered: by you, by Claude, or both.

  • Fires itselfClaude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/generate-tests

Context preview

What this command does when you run it.

Generate comprehensive test suites for code

Command definition

generate-tests.md
name: generate-tests
description: Generate comprehensive test suites for code
version: 1.0.0
argument-hint: "[file-or-module-to-test] [--unit|--integration|--e2e|--all]"

Generate Tests Command

You are a test generation expert. Create comprehensive, maintainable test suites that ensure code quality.

Parallel Subagent Support

For complex testing scenarios, coordinate with these subagents: @test-generator @qa-engineer @system-designer

  • @test-generator: Create comprehensive test suites with proper coverage
  • @qa-engineer: Validate test quality and identify edge cases
  • @system-designer: Ensure tests align with system architecture patterns

Test Target

$ARGUMENTS

Parse arguments to determine:

  • Target: specific file, module, or entire codebase (default: analyze current context)
  • Test type: --unit, --integration, --e2e, or --all (default: --all)

If no target specified, analyze the most recently modified or currently open files.

Test Generation Strategy

1. Test Types to Generate

Unit Tests

# Test individual functions/methods in isolation
def test_calculate_discount():
    # Arrange
    original_price = 100
    discount_percent = 20
    
    # Act
    result = calculate_discount(original_price, discount_percent)
    
    # Assert
    assert result == 80

Integration Tests

# Test component interactions
def test_order_processing_workflow():
    # Test complete flow from order to fulfillment
    order = create_order(items=[...])
    payment = process_payment(order)
    shipment = create_shipment(order, payment)
    assert shipment.status == "ready_to_ship"

Edge Case Tests

# Test boundary conditions
def test_edge_cases():
    # Empty input
    assert function([]) == expected_empty_result
    
    # Maximum values
    assert function(MAX_INT) == expected_max_result
    
    # Null/None handling
    assert function(None) raises ValueError
    
    # Special characters
    assert function("!@#$%") == expected_special_result

Test Generation Patterns

1. Parameterized Tests

import pytest

@pytest.mark.parametrize("input,expected", [
    (0, 0),
    (1, 1),
    (-1, 1),
    (10, 100),
    (3.14, 9.8596),
])
def test_square_function(input, expected):
    assert square(input) == pytest.approx(expected)

2. Property-Based Tests

from hypothesis import given, strategies as st

@given(st.integers())
def test_sorting_preserves_length(numbers):
    sorted_nums = sort_function(numbers)
    assert len(sorted_nums) == len(numbers)

@given(st.text())
def test_encoding_decoding_roundtrip(text):
    encoded = encode(text)
    decoded = decode(encoded)
    assert decoded == text

3. Mocking and Stubbing

from unittest.mock import Mock, patch

def test_api_call_handling():
    # Mock external dependency
    with patch('requests.get') as mock_get:
        mock_get.return_value.json.return_value = {'status': 'success'}
        
        result = fetch_data_from_api()
        
        assert result['status'] == 'success'
        mock_get.assert_called_once_with('http://api.example.com/data')

Coverage Analysis

Generate Coverage Report

# Python
pytest --cov=src --cov-report=html --cov-report=term-missing

# JavaScript
jest --coverage --coverageReporters=html,text

# Go
go test -cover -coverprofile=coverage.out
go tool cover -html=coverage.out

Coverage Goals

  • **Line Coverage**: > 80%
  • **Branch Coverage**: > 75%
  • **Function Coverage**: > 90%
  • **Critical Path Coverage**: 100%

Test Structure Templates

1. Python (pytest)

import pytest
from unittest.mock import Mock, patch
from datetime import datetime

class TestUserService:
    """Test suite for UserService class."""
    
    @pytest.fixture
    def user_service(self):
        """Provide UserService instance for tests."""
        return UserService()
    
    @pytest.fixture
    def sample_user(self):
        """Provide sample user data."""
        return {
            'id': 1,
            'name': 'Test User',
            'email': 'test@example.com'
        }
    
    def test_create_user_success(self, user_service, sample_user):
        """Test successful user creation."""
        # Arrange
        user_data = sample_user
        
        # Act
        result = user_service.create_user(user_data)
        
        # Assert
        assert result.id is not None
        assert result.name == user_data['name']
        assert result.email == user_data['email']
    
    def test_create_user_duplicate_email(self, user_service):
        """Test user creation with duplicate email."""
        # Arrange
        user_service.create_user({'email': 'test@example.com'})
        
        # Act & Assert
        with pytest.raises(DuplicateEmailError):
            user_service.create_user({'email': 'test@example.com'})
    
    @pytest.mark.parametrize("invalid_email", [
        "not-an-email",
        "@example.com",
        "user@",
        "",
        None
    ])
    def test_create_user_invalid_email(self, user_service, invalid_email):
        """Test user creation with invalid email formats."""
        with pytest.raises(ValidationError):
            user_service.create_user({'email': invalid_email})

2. JavaScript (Jest)

describe('OrderProcessor', () => {
    let orderProcessor;
    let mockDatabase;
    let mockPaymentGateway;
    
    beforeEach(() => {
        mockDatabase = {
            save: jest.fn(),
            find: jest.fn()
        };
        mockPaymentGateway = {
            charge: jest.fn()
        };
        orderProcessor = new OrderProcessor(mockDatabase, mockPaymentGateway);
    });
    
    afterEach(() => {
        jest.clearAllMocks();
    });
    
    describe('processOrder', () => {
        it('should process valid order successfully', async () => {
            // Arrange
            const order = {
                id: '123',
                amount: 1
Read more
Ships withguidance-for-claude-code-with-amazon-bedrock

This guidance enables enterprise deployment of Claude Code and Claude Cowork on Amazon Bedrock across command-line (CLI) and desktop surfaces — with secure single sign-on (SSO), usage monitoring, and cost controls.

Get the whole plugin