Skip to main content
ClaudeWave
Skill237 repo starsupdated 1mo ago

api-test-generator

This Claude Code skill generates comprehensive Python pytest test suites for MikoPBX REST API endpoints by analyzing DataStructure.php files to extract parameter definitions, validation rules, and data types. Use it when creating new test coverage for REST API endpoints, adding tests for CRUD operations, validating API responses against OpenAPI schemas, or ensuring comprehensive edge case and negative test scenario coverage.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/Microck/ordinary-claude-skills /tmp/api-test-generator && cp -r /tmp/api-test-generator/skills_all/api-test-generator ~/.claude/skills/api-test-generator
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# MikoPBX API Test Generating

Generate comprehensive Python pytest tests for MikoPBX REST API endpoints with full parameter coverage, schema validation, and edge case testing.

## What This Skill Does

Analyzes DataStructure.php files and generates complete pytest test suites including:
- ✅ CRUD operation tests (Create, Read, Update, Delete)
- ✅ Positive and negative test cases
- ✅ Parameter validation tests
- ✅ Edge cases and boundary conditions
- ✅ Schema validation tests
- ✅ Proper fixtures and authentication
- ✅ Detailed assertions with error messages

## When to Use This Skill

Use this skill when you need to:
- Create pytest tests for new REST API endpoints
- Add comprehensive test coverage for existing endpoints
- Generate tests covering all parameter combinations
- Add schema validation tests for API responses
- Create edge case and negative tests
- Ensure API compliance with OpenAPI specification

## Quick Start

### Basic Usage

When the user requests test generation:

1. **Identify the endpoint**
   - API path (e.g., `/pbxcore/api/v3/extensions`)
   - HTTP methods (GET, POST, PUT, DELETE, PATCH)
   - Resource name (e.g., Extensions)

2. **Locate DataStructure.php**
   ```bash
   find /Users/nb/PhpstormProjects/mikopbx/Core/src/PBXCoreREST/Lib -name "DataStructure.php" | grep -i "{resource}"
   ```

3. **Analyze parameter definitions**
   Extract from `DataStructure.php`:
   - Required vs optional parameters
   - Data types and validation rules
   - Default values
   - Enum values
   - Pattern constraints (regex)
   - Min/max values

4. **Generate test file**
   Use the complete template from [test-template.py](templates/test-template.py)

5. **Customize for endpoint**
   - Replace `{ResourceName}` placeholders
   - Fill in actual payload structures
   - Add specific field validations
   - Include enum and pattern validations

## Test Structure

### File Organization

```python
tests/api/
├── test_{resource}_api.py        # Main test file
└── conftest.py                   # Shared fixtures
```

### Test Class Structure

Each test file should have these test classes:

```python
class TestCreate{ResourceName}:
    """Test POST endpoint for creating resources"""
    - test_create_with_valid_data()
    - test_create_missing_required_field()
    - test_create_with_invalid_type()

class TestGet{ResourceName}:
    """Test GET endpoint for retrieving resources"""
    - test_get_all()
    - test_get_by_id()
    - test_get_nonexistent()

class TestUpdate{ResourceName}:
    """Test PUT/PATCH endpoints for updating resources"""
    - test_update_with_valid_data()
    - test_patch_partial_update()

class TestDelete{ResourceName}:
    """Test DELETE endpoint for removing resources"""
    - test_delete_existing()
    - test_delete_nonexistent()

class TestSchemaValidation{ResourceName}:
    """Test response schema validation"""
    - test_response_matches_openapi_schema()

class TestEdgeCases{ResourceName}:
    """Test edge cases and boundary conditions"""
    - test_special_characters_in_fields()
    - test_empty_string_values()
    - test_boundary_values()
```

### Standard Fixtures

```python
@pytest.fixture
def auth_token():
    """Get authentication token"""
    response = requests.post(
        f"{BASE_URL}/pbxcore/api/v3/auth/login",
        json={"login": "admin", "password": "123456789MikoPBX#1"},
        verify=False
    )
    return response.json()["data"]["access_token"]

@pytest.fixture
def headers(auth_token):
    """Standard headers with authentication"""
    return {
        "Authorization": f"Bearer {auth_token}",
        "Content-Type": "application/json"
    }
```

## Common Test Patterns

### 1. Create with Valid Data

```python
def test_create_with_valid_data(self, headers):
    """Test creating a resource with all valid required parameters"""
    payload = {
        # Based on DataStructure.php
    }

    response = requests.post(
        f"{BASE_URL}{API_PATH}",
        json=payload,
        headers=headers,
        verify=False
    )

    assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.text}"
    data = response.json()
    assert "data" in data
    assert "id" in data["data"]

    # Validate returned values match input
    for key, value in payload.items():
        assert data["data"][key] == value
```

### 2. Validation Tests

```python
def test_create_missing_required_field(self, headers):
    """Test validation when required field is missing"""
    payload = {
        # Missing required field
    }

    response = requests.post(
        f"{BASE_URL}{API_PATH}",
        json=payload,
        headers=headers,
        verify=False
    )

    assert response.status_code == 400
    assert "messages" in response.json()
```

### 3. Edge Cases

```python
def test_special_characters_in_fields(self, headers):
    """Test handling of special characters"""
    special_chars = "Test <script>alert('xss')</script> & \"quotes\""
    payload = {
        "string_field": special_chars,
    }

    response = requests.post(...)
    assert response.status_code == 200
    assert response.json()["data"]["string_field"] == special_chars
```

## DataStructure Analysis

When analyzing DataStructure.php, extract these key elements:

### Parameter Structure

```php
public static function getParameterDefinitions(): array
{
    return [
        'request' => [
            'POST' => [
                'parameter_name' => [
                    'type' => 'string',              // Extract type
                    'description' => 'Description',  // Extract description
                    'example' => 'value',            // Use for test data
                    'required' => true,              // Required vs optional
                    'default' => 'default_value',    // Default value
                    'enum' => ['val1', 'val2'],      // Valid enum values
                    'pattern' => '^[a-z]+$',         // Regex pattern
                    'minLength' =
activitypub-testingSkill

Testing patterns for PHPUnit and Playwright E2E tests. Use when writing tests, debugging test failures, setting up test coverage, or implementing test patterns for ActivityPub features.

adaptyvSkill

Cloud laboratory platform for automated protein testing and validation. Use when designing proteins and needing experimental validation including binding assays, expression testing, thermostability measurements, enzyme activity assays, or protein sequence optimization. Also use for submitting experiments via API, tracking experiment status, downloading results, optimizing protein sequences for better expression using computational tools (NetSolP, SoluProt, SolubleMPNN, ESM), or managing protein design workflows with wet-lab validation.

add-uint-supportSkill

Add unsigned integer (uint) type support to PyTorch operators by updating AT_DISPATCH macros. Use when adding support for uint16, uint32, uint64 types to operators, kernels, or when user mentions enabling unsigned types, barebones unsigned types, or uint support.

Agent DevelopmentSkill

This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.

AgentDB Advanced FeaturesSkill

Master advanced AgentDB features including QUIC synchronization, multi-database management, custom distance metrics, hybrid search, and distributed systems integration. Use when building distributed AI systems, multi-agent coordination, or advanced vector search applications.

AgentDB Learning PluginsSkill

Create and train AI learning plugins with AgentDB's 9 reinforcement learning algorithms. Includes Decision Transformer, Q-Learning, SARSA, Actor-Critic, and more. Use when building self-learning agents, implementing RL, or optimizing agent behavior through experience.

AgentDB Memory PatternsSkill

Implement persistent memory patterns for AI agents using AgentDB. Includes session memory, long-term storage, pattern learning, and context management. Use when building stateful agents, chat systems, or intelligent assistants.

AgentDB Performance OptimizationSkill

Optimize AgentDB performance with quantization (4-32x memory reduction), HNSW indexing (150x faster search), caching, and batch operations. Use when optimizing memory usage, improving search speed, or scaling to millions of vectors.