api-test-generator
Automates the creation of robust pytest tests for REST APIs by analyzing DataStructure.php definitions.
Install
mkdir -p .claude/skills/api-test-generator && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/4940" && unzip -o skill.zip -d .claude/skills/api-test-generator && rm skill.zipInstalls to .claude/skills/api-test-generator
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Генерация полных Python pytest тестов для REST API эндпоинтов с валидацией схемы. Использовать при создании тестов для новых эндпоинтов, добавлении покрытия для CRUD операций или валидации соответствия API с OpenAPI схемами.Key capabilities
- →Locates DataStructure.php files via grep
- →Extracts parameter types, constraints, and enums
- →Generates pytest suites from templates
- →Produces CRUD-specific test logic
- →Validates OpenAPI schema structures
How it works
It parses DataStructure.php files to extract API definitions and injects them into a pre-defined test-template.py file to ensure coverage.
Inputs & outputs
When to use api-test-generator
- →Testing new REST API endpoints
- →Adding test coverage for CRUD operations
- →Validating API against OpenAPI specs
- →Generating negative test cases
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:
-
Identify the endpoint
- API path (e.g.,
/pbxcore/api/v3/extensions) - HTTP methods (GET, POST, PUT, DELETE, PATCH)
- Resource name (e.g., Extensions)
- API path (e.g.,
-
Locate DataStructure.php
find /Users/nb/PhpstormProjects/mikopbx/Core/src/PBXCoreREST/Lib -name "DataStructure.php" | grep -i "{resource}" -
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
-
Generate test file Use the complete template from test-template.py
-
Customize for endpoint
- Replace
{ResourceName}placeholders - Fill in actual payload structures
- Add specific field validations
- Include enum and pattern validations
- Replace
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
- Generate valid payloads - Use
exampleanddefaultvalues - Test required fields - Create tests omitting each required field
- Test data types - Create tests with wrong types
- Test enums - Create tests for each enum value and invalid values
- Test patterns - Create tests for valid/invalid patterns
- 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:
- ✅ Complete pytest file - Runnable without modifications
- ✅ Documentation block - Clear description at the top
- ✅ All test classes - CRUD, schema validation, edge cases
- ✅ Proper fixtures - Authentication and headers
- ✅ Clear assertions - With descriptive error messages
- ✅ 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=Falsefor self-signed certificates - Base URL: Default is
https://mikopbx-php83.localhost:8445 - Schema validation: Only active when
SCHEMA_VALIDATION_STRICT=1in container - Container restart: Changes to PHP code require container restart
- Test isolation: Each test should be independent and idempotent
Best Practices
- ✅ Analyze DataStructure first - Don't guess parameter structures
- ✅ Include schema validation tests - Only work with SCHEMA_VALIDATION_STRICT=1
- ✅ Test success and failure cases - Negative tests are critical
- ✅ Use fixtures for auth - Avoid code duplication
- ✅ Clean up after tests - Delete created resources in teardown
- ✅ Document expected behavior - Each test should state what it validates
- ✅ Use descriptive test names - Clear indication of what's being tested
- ✅ One assertion per test - Or group related assertions
Additional Resources
Templates
Complete test templates for copy-paste usage:
- test-template.py - Complete pytest template with all test classes
- crud-tests.py - Reusable CRUD operation patterns
- edge-cases.py - Edge case and boundary test patterns
Reference Documentat
Content truncated.
When not to use it
- →Non-REST API codebases
- →Projects without OpenAPI/DataStructure specifications
- →Manual test suites requiring highly custom logic
Prerequisites
Limitations
- →Requires predictable DataStructure.php format
- →Limited by the completeness of the source schema definitions
How it compares
Unlike a generic code-generating prompt, this tool follows a project-specific architectural pattern for MikoPBX to ensure tests are runnable and standard-compliant.
Compared to similar skills
api-test-generator side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| api-test-generator (this skill) | 1 | 9mo | Review | Intermediate |
| test-api-serializer | 0 | 4mo | No flags | Intermediate |
| fastapi-templates | 520 | 2mo | No flags | Intermediate |
| fastapi-pro | 79 | 4mo | No flags | Advanced |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by mikopbx
View all by mikopbx →You might also like
test-api-serializer
engremran07
Serializer tests: to_representation, to_internal_value, validation. Use when: testing DRF serializer output, input validation, custom field logic.
fastapi-templates
wshobson
Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
fastapi-pro
sickn33
Build high-performance async APIs with FastAPI, SQLAlchemy 2.0, and Pydantic V2. Master microservices, WebSockets, and modern Python async patterns. Use PROACTIVELY for FastAPI development, async optimization, or API architecture.
sexp
atopile
How the Zig S-expression engine and typed KiCad models work, how they are exposed to Python (pyzig_sexp), and the invariants around parsing, formatting, and freeing.
add-vault-protocol
tradingstrategy-ai
Add support for a new ERC-4626 vault protocol. Use when the user wants to integrate a new vault protocol like IPOR, Plutus, Morpho, etc. Requires vault smart contract address, protocol name, and protocol slug as inputs.
property-based-testing
trailofbits
Provides guidance for property-based testing across multiple languages and smart contracts. Use when writing tests, reviewing code with serialization/validation/parsing patterns, designing features, or when property-based testing would provide stronger coverage than example-based tests.