api-test-generator

4
1
Source

Генерация полных Python pytest тестов для REST API эндпоинтов с валидацией схемы. Использовать при создании тестов для новых эндпоинтов, добавлении покрытия для CRUD операций или валидации соответствия API с OpenAPI схемами.

Install

mkdir -p .claude/skills/api-test-generator && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4940" && unzip -o skill.zip -d .claude/skills/api-test-generator && rm skill.zip

Installs to .claude/skills/api-test-generator

About this skill

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

    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

  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

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

Test Class Structure

Each test file should have these test classes:

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

@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

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

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

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

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' => 1,                // Min length
                    'maxLength' => 100,              // Max length
                ],
            ],
        ],
    ];
}

Use This Data To

  1. Generate valid payloads - Use example and default values
  2. Test required fields - Create tests omitting each required field
  3. Test data types - Create tests with wrong types
  4. Test enums - Create tests for each enum value and invalid values
  5. Test patterns - Create tests for valid/invalid patterns
  6. Test boundaries - Create tests for min/max values

Test Documentation Template

Add to the top of each test file:

"""
Tests for {ResourceName} API endpoint

API Endpoint: /pbxcore/api/v3/{resource-path}
DataStructure: src/PBXCoreREST/Lib/{ResourceName}/DataStructure.php

Test Coverage:
- CRUD operations (Create, Read, Update, Delete)
- Required vs optional parameters
- Data type validations
- Enum value validations
- Pattern validations (regex)
- Boundary conditions (min/max values)
- Special characters and edge cases
- Schema validation (when SCHEMA_VALIDATION_STRICT=1)

Requirements:
- pytest
- requests
- Docker container running with MikoPBX

Run tests:
    pytest tests/api/test_{resource_name}.py -v

Run with schema validation:
    # Ensure SCHEMA_VALIDATION_STRICT=1 is set in container
    pytest tests/api/test_{resource_name}.py -v
"""

Output Format

Always generate:

  1. Complete pytest file - Runnable without modifications
  2. Documentation block - Clear description at the top
  3. All test classes - CRUD, schema validation, edge cases
  4. Proper fixtures - Authentication and headers
  5. Clear assertions - With descriptive error messages
  6. Comments - Explaining complex validations

Running Tests

Basic Execution

# Run all API tests
pytest tests/api/ -v

# Run specific endpoint tests
pytest tests/api/test_extensions_api.py -v

# Run specific test class
pytest tests/api/test_extensions_api.py::TestCreateExtensions -v

# Run specific test
pytest tests/api/test_extensions_api.py::TestCreateExtensions::test_create_with_valid_data -v

With Schema Validation

# Enable schema validation in container
docker exec mikopbx_container sh -c 'export SCHEMA_VALIDATION_STRICT=1'

# Run tests
pytest tests/api/test_extensions_api.py -v

Test Markers

# Run only CRUD tests
pytest tests/api/ -m crud -v

# Skip slow tests
pytest tests/api/ -m "not slow" -v

# Run smoke tests
pytest tests/api/ -m smoke -v

Important Notes

MikoPBX-Specific Considerations

  • Authentication: All tests need Bearer token from /auth/login
  • HTTPS: Use verify=False for self-signed certificates
  • Base URL: Default is https://mikopbx-php83.localhost:8445
  • Schema validation: Only active when SCHEMA_VALIDATION_STRICT=1 in container
  • Container restart: Changes to PHP code require container restart
  • Test isolation: Each test should be independent and idempotent

Best Practices

  1. Analyze DataStructure first - Don't guess parameter structures
  2. Include schema validation tests - Only work with SCHEMA_VALIDATION_STRICT=1
  3. Test success and failure cases - Negative tests are critical
  4. Use fixtures for auth - Avoid code duplication
  5. Clean up after tests - Delete created resources in teardown
  6. Document expected behavior - Each test should state what it validates
  7. Use descriptive test names - Clear indication of what's being tested
  8. One assertion per test - Or group related assertions

Additional Resources

Templates

Complete test templates for copy-paste usage:

Reference Documentat


Content truncated.

sqlite-inspector

mikopbx

Проверка консистентности данных в SQLite баз данных MikoPBX после операций REST API. Использовать при валидации результатов API, отладке проблем с данными, проверке связей внешних ключей или инспектировании CDR записей для тестирования.

664

openapi-analyzer

mikopbx

Извлечение и анализ OpenAPI 3.1.0 спецификации из MikoPBX для валидации эндпоинтов. Использовать при проверке соответствия API, генерации тестов, проверке схем эндпоинтов или интеграции с навыками endpoint-validator и api-test-generator.

42

babel-compiler

mikopbx

Транспиляция ES6+ JavaScript в ES5 для совместимости с браузерами используя Docker-based Babel компилятор. Использовать при транспиляции JavaScript файлов после внесения изменений в ES6+ исходный код.

31

asterisk-validator

mikopbx

Валидация конфигурационных файлов Asterisk и анализ логов на корректность и best practices. Использовать при отладке проблем запуска Asterisk, проверке изменений конфигурации или проверке ошибок после регенерации воркерами.

31

endpoint-validator

mikopbx

Валидация REST API эндпоинтов на соответствие OpenAPI схеме и консистентность параметров. Использовать при реализации эндпоинтов, ревью кода или перед слиянием изменений API.

41

browserstack-tester

mikopbx

Тестирование веб-интерфейса MikoPBX через BrowserStack. Запуск PHPUnit тестов с Selenium WebDriver в облачных браузерах. Использовать для автоматизированного тестирования админ-панели, проверки форм, навигации и интерактивных элементов.

21

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,5741,370

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,1161,191

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,4181,109

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,199751

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,157685

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,322617

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.