# TestAPIX - Modern Python API Testing Framework
[](https://www.python.org/downloads/)
[](https://opensource.org/licenses/MIT)
[](https://github.com/psf/black)
TestAPIX is a modern, comprehensive API testing framework designed to make API testing both powerful and accessible. Built from the ground up with Python async patterns, TestAPIX provides everything from simple functional tests to sophisticated security testing, schema validation, and interactive API exploration.
## Why TestAPIX?
Traditional API testing tools force you to choose between simplicity and power. TestAPIX eliminates this compromise by providing:
**Instant Productivity**: Get from zero to comprehensive tests in under 5 minutes with our intelligent CLI and generated examples that demonstrate best practices.
**Learning Through Examples**: Every generated test includes detailed comments explaining not just what the code does, but why it's structured that way and how to extend it.
**Progressive Enhancement**: Start simple with basic functional tests, then seamlessly adopt advanced features like security testing, persona-based authentication, and interactive exploration as your needs evolve.
**Actionable Insights**: When tests fail, TestAPIX provides clear, contextual error messages with suggestions for resolution, not cryptic stack traces.
**Interactive Development**: Explore APIs in real-time with our rich interactive CLI, then generate tests from your exploration sessions.
## Key Features
### Comprehensive Testing Capabilities
- **Async-First Architecture**: Built on modern Python async/await for superior performance and scalability
- **Fluent Assertions**: Write tests that read like specifications with comprehensive assertion chaining
- **Smart API Client**: Automatic retries, intelligent error handling, and response enhancement
- **Realistic Test Data**: Context-aware data generation that uncovers real edge cases and bugs
### Security Testing
- **OWASP-Compliant Security Tests**: Comprehensive security vulnerability testing including:
- SQL injection prevention validation
- Cross-Site Scripting (XSS) attack detection
- Authentication and authorization boundary testing
- Rate limiting and abuse prevention verification
- Security headers validation
- **Security Test Payloads**: Comprehensive payloads across multiple attack vectors
- **Responsible Testing**: Built-in safeguards and warnings for ethical security testing
### Persona-Based Authentication Testing
- **Business-Context Authentication**: Test with realistic user personas and roles
- **Multi-Provider Support**: Bearer tokens, API keys, OAuth2, Basic Auth, and custom providers
- **Session Management**: Automatic token refresh, auth failure handling, and session persistence
- **Cross-Authentication Testing**: Validate proper isolation between different user contexts
### Interactive API Exploration
- **Rich Interactive CLI**: Explore APIs in real-time with syntax highlighting and intelligent suggestions
- **Session Management**: Save and restore exploration sessions with secure credential handling
- **Test Generation**: Convert interactive sessions into automated test files
- **Multiple Export Formats**: Generate tests in pytest, curl, Postman collection, or Python requests format
### Developer Experience Excellence
- **Intelligent CLI**: Generate projects, tests, and configurations with helpful guidance and validation
- **Multi-Environment Support**: Seamlessly test across development, staging, and production environments
- **Advanced Error Reporting**: Batch error aggregation, detailed context, and intelligent error suggestions
- **Schema Validation**: JSON Schema validation with detailed mismatch reporting
- **Extensible Architecture**: Plugin-ready design for custom assertions, generators, and authentication providers
## Quick Start
### Installation
Install TestAPIX from PyPI:
```bash
# Basic installation
pip install testapix
# Full installation with interactive CLI support
pip install 'testapix[interactive]'
```
### Option 1: Traditional Project Setup
Create a structured test project:
```bash
# Create a new test project
testapix init my-api-tests
# Navigate to your project
cd my-api-tests
# Generate comprehensive functional tests
testapix generate functional user-api
# Run your tests
pytest tests/ -v
```
### Option 2: Interactive API Exploration
Start exploring APIs immediately:
```bash
# Launch interactive CLI
testapix interactive --api https://api.example.com
# Or with authentication
testapix interactive --api https://api.example.com
```
```bash
# In the interactive shell:
TestAPIX Interactive Shell
> auth bearer your-token-here
Authentication configured
> get /users
GET /users → 200 OK (234ms)
{
"users": [{"id": 1, "name": "John", "email": "john@example.com"}]
}
> generate test functional my-users-test.py
Test file generated from session history
> save my-exploration-session
Session saved for later use
```
That's it! You now have either a complete test project or interactive exploration ready to generate tests.
## Core Usage Examples
### Writing Comprehensive Tests
TestAPIX tests are clean, readable, and powerful:
```python
import pytest
from testapix import APIClient, assert_that
from testapix.generators import BaseGenerator
class TestUserAPI:
def setup_method(self):
self.generator = BaseGenerator()
@pytest.fixture(autouse=True)
def setup(self, api_client: APIClient):
self.client = api_client
async def test_create_user_comprehensive(self):
# Generate realistic test data
user_data = self.generator.generate_user_data()
# Create user with comprehensive validation
response = await self.client.post("/users", json=user_data)
# Fluent assertions with detailed validation
assert_that(response) \
.has_status(201) \
.has_header("location") \
.has_json_path("id") \
.has_json_path("email") \
.response_time_less_than(2.0)
# Verify user can be retrieved
user_id = response.json().get("id")
get_response = await self.client.get(f"/users/{user_id}")
assert_that(get_response) \
.has_status(200) \
.has_json_path("id")
```
### Persona-Based Authentication Testing
Test with realistic business contexts:
```python
from testapix.auth import PersonaPool, UserPersona, PersonaRole
class TestUserPermissions:
def setup_method(self):
# Define business personas
self.personas = PersonaPool([
UserPersona(
name="admin_user",
role=PersonaRole.ADMIN,
credentials={"token": "admin-token-here"}
),
UserPersona(
name="regular_user",
role=PersonaRole.USER,
credentials={"token": "user-token-here"}
)
])
async def test_admin_can_delete_users(self):
# Test as admin persona
async with self.personas.get_client("admin_user") as admin_client:
response = await admin_client.delete("/users/123")
assert_that(response).has_status(204)
async def test_user_cannot_delete_users(self):
# Test as regular user persona
async with self.personas.get_client("regular_user") as user_client:
response = await user_client.delete("/users/123")
assert_that(response).has_status(403)
```
### Security Testing
Comprehensive security validation:
```python
from testapix.generators import BaseGenerator
class TestAPISecurity:
def setup_method(self):
self.generator = BaseGenerator()
@pytest.mark.security
async def test_sql_injection_protection(self, api_client: APIClient):
"""Verify API protects against SQL injection attacks."""
# Generate SQL injection payloads
payloads = self.generator.generate_security_test_data("sql_injection")
for payload_name, payload in payloads.items():
response = await api_client.get("/users", params={"search": payload})
# API should either reject malicious input or handle it safely
assert response.status_code in [400, 401, 403, 422] or \
(response.status_code == 200 and "error" not in response.text.lower()), \
f"SQL injection vulnerability detected with payload: {payload_name}"
@pytest.mark.security
async def test_xss_protection(self, api_client: APIClient):
"""Verify API protects against XSS attacks."""
xss_payloads = self.generator.generate_security_test_data("xss")
for payload_name, payload in xss_payloads.items():
user_data = {"name": payload, "email": "test@example.com"}
response = await api_client.post("/users", json=user_data)
if response.status_code == 201:
# If user created, ensure XSS payload is properly escaped
user_id = response.json().get("id")
get_response = await api_client.get(f"/users/{user_id}")
assert_that(get_response).has_status(200)
# Verify no script tags in response
assert "<script>" not in get_response.text
assert "javascript:" not in get_response.text
assert "onerror=" not in get_response.text
```
### Multi-Environment Configuration
Seamless environment management:
```yaml
# configs/base.yaml
http:
timeout: 30.0
retries: 3
verify_ssl: true
auth:
type: "bearer"
token: "${TESTAPIX_AUTH_TOKEN}"
security_testing:
enable_sql_injection: true
enable_xss_tests: true
max_payload_size: 10000
reporting:
formats: ["console", "html", "junit"]
output_dir: "reports"
```
```yaml
# configs/staging.yaml
http:
base_url: "https://staging-api.example.com"
timeout: 60.0 # Longer timeout for staging
security_testing:
enable_sql_injection: false # Skip in staging
```
```bash
# Run tests across environments
TESTAPIX_ENVIRONMENT=local pytest tests/
TESTAPIX_ENVIRONMENT=staging pytest tests/ -m "not destructive"
TESTAPIX_ENVIRONMENT=production pytest tests/ -m "smoke"
```
## Interactive CLI Features
The TestAPIX Interactive CLI provides a rich, terminal-based environment for real-time API exploration:
### Key Interactive Features
- **Authentication Management**: Configure and switch between multiple authentication methods
- **Rich Response Display**: JSON syntax highlighting with intelligent data analysis
- **Session Persistence**: Save exploration sessions and reload them later
- **Test Generation**: Convert interactive sessions into automated test files
- **Advanced Response Analysis**: Extract data with JSON paths, validate schemas, analyze performance
### Interactive CLI Example Session
```bash
$ testapix interactive --api https://api.github.com
TestAPIX Interactive Shell - API Exploration Environment
Connected to: https://api.github.com
# Configure authentication
> auth bearer ghp_your_token_here
Authentication configured
# Explore endpoints with rich output
> get /user
GET /user → 200 OK (156ms)
{
"login": "octocat",
"id": 1,
"name": "The Octocat",
"email": "octocat@github.com"
}
# Extract specific data
> extract login
Extracted: "octocat"
# Save session for later
> save github-exploration
Session saved: github-exploration
# Generate test file from session
> generate test testapix github_tests.py
Generated test file: github_tests.py
- 5 test methods created from session history
- Includes authentication setup
- Comprehensive assertions included
# Export in different formats
> export curl github_commands.sh
Exported 5 curl commands to github_commands.sh
> export postman github_collection.json
Exported Postman collection to github_collection.json
```
## Project Structure
TestAPIX projects follow a comprehensive, scalable structure:
```
my-api-tests/
├── configs/ # Environment configurations
│ ├── base.yaml # Shared settings
│ ├── local.yaml # Local development overrides
│ ├── staging.yaml # Staging environment settings
│ └── production.yaml # Production settings (smoke tests only)
├── tests/ # Test suites organized by paradigm
│ ├── functional/ # API functionality tests
│ ├── security/ # Security vulnerability tests
│ ├── contract/ # Basic response structure validation
│ ├── performance/ # Response time and basic load tests
│ └── integration/ # End-to-end integration tests
├── personas/ # User personas and authentication configs
│ ├── admin_personas.yaml # Admin user configurations
│ └── user_personas.yaml # Regular user configurations
├── data_generators/ # Custom test data generators
│ ├── user_generator.py # User-specific data generation
│ └── product_generator.py # Product/business domain data
├── schemas/ # API schemas and validation rules
│ ├── openapi.yaml # OpenAPI/Swagger specifications
│ └── json_schemas/ # JSON schema validation files
├── reports/ # Test execution reports
│ ├── coverage/ # Test coverage reports
│ ├── security/ # Security scan results
│ └── performance/ # Performance test results
├── sessions/ # Saved interactive CLI sessions
└── .testapix/ # Framework configuration and cache
```
## Advanced Features
### Security Testing
TestAPIX includes production-ready security testing capabilities:
```bash
# Generate comprehensive security test suite
testapix generate security payment-api --endpoints "/charge,/refund,/admin"
```
**Generated Security Test Categories:**
1. **Authentication & Authorization**
- Missing authentication detection
- Invalid token/credential testing
- Cross-user authorization boundary validation
- Privilege escalation attempt detection
2. **Injection Attack Prevention**
- SQL injection with 13+ attack vectors
- XSS prevention with 14+ payload variations
- Command injection detection
- Path traversal attack testing
- LDAP and XML injection testing
3. **HTTP Security Standards**
- Security headers validation (CSP, HSTS, X-Frame-Options)
- Basic CORS configuration testing
- Content-type validation
4. **Rate Limiting & Basic Abuse Prevention**
- Basic rate limiting detection
- Request validation testing
### Basic Contract Testing & Schema Validation
Ensure API compatibility and data integrity:
```bash
# Generate basic contract tests from OpenAPI specification
testapix generate contract user-api --schema-file openapi.yaml
```
**Note**: TestAPIX provides basic response structure validation and schema compliance checking. For full consumer-driven contract testing and API evolution management, consider complementing with specialized contract testing tools.
### Advanced Error Reporting & Debugging
TestAPIX provides sophisticated error analysis:
```python
from testapix import batch_operation, get_batch_aggregator
# Batch operations with comprehensive error aggregation
async def test_bulk_user_operations(api_client):
user_ids = [1, 2, 3, 4, 5]
async with batch_operation("bulk_user_deletion"):
for user_id in user_ids:
response = await api_client.delete(f"/users/{user_id}")
assert_that(response).has_status(204)
# Get detailed error report if any operations failed
error_report = get_batch_aggregator().get_detailed_report()
if error_report.has_errors():
print(error_report.format_with_suggestions())
```
### Performance Testing
Basic performance validation capabilities:
```python
@pytest.mark.performance
async def test_api_performance_requirements(api_client):
"""Validate API meets basic performance requirements."""
# Test response time requirements
response = await api_client.get("/users", params={"limit": 100})
assert_that(response) \
.has_status(200) \
.response_time_less_than(2.0)
# Test basic concurrent request handling
import asyncio
async def make_request():
return await api_client.get("/users")
# Execute 5 concurrent requests
responses = await asyncio.gather(*[make_request() for _ in range(5)])
assert all(r.status_code == 200 for r in responses)
```
**Note**: TestAPIX provides basic performance testing for response times and simple concurrent requests. For comprehensive load testing, consider integrating with specialized tools like Locust or Artillery.
## CLI Command Reference
### Project Management
```bash
# Initialize new testing project
testapix init my-project --template advanced
# Validate configuration files
testapix validate-config --environment staging
```
### Test Generation
```bash
# Functional tests
testapix generate functional user-api --endpoints "/users,/profiles"
# Security tests (with safety warnings)
testapix generate security api --endpoints "/admin,/payment"
# Basic contract tests from OpenAPI spec
testapix generate contract api --schema-file swagger.yaml
# Basic performance tests
testapix generate performance api --endpoints "/search,/reports"
```
### Interactive Exploration
```bash
# Basic interactive session
testapix interactive
# With API URL and authentication
testapix interactive --api https://api.example.com --auth-file auth.yaml
# Load previous session
testapix interactive --session my-saved-session
```
## Learning Resources
TestAPIX is designed as a teaching tool that promotes best practices:
### Generated Code Quality
- **Comprehensive Documentation**: Every generated test includes detailed comments explaining patterns and best practices
- **Real-World Examples**: Generated tests demonstrate actual edge cases and error scenarios you'll encounter
- **Progressive Complexity**: Start with basic patterns and learn advanced techniques through example
- **Best Practice Patterns**: Authentication handling, error management, and test organization following industry standards
### Educational Features
- **Error Context**: When tests fail, get explanations of what went wrong and how to fix it
- **Pattern Recognition**: Learn to recognize anti-patterns and security vulnerabilities through hands-on testing
- **Interactive Learning**: Use the CLI to explore APIs and understand their behavior before writing tests
## Enterprise Deployment
### CI/CD Integration
TestAPIX integrates seamlessly with modern CI/CD pipelines:
```yaml
# .github/workflows/api-tests.yml
name: API Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
test-type: [functional, security, contract]
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install TestAPIX
run: pip install 'testapix[interactive]'
- name: Run API Tests
run: |
testapix validate-config
pytest tests/${{ matrix.test-type }}/ -v --junit-xml=reports/results.xml
- name: Upload Test Results
uses: actions/upload-artifact@v3
with:
name: test-results-${{ matrix.test-type }}
path: reports/
```
### Security & Compliance
- **Responsible Testing**: Built-in warnings and safeguards for security testing
- **Credential Management**: Secure handling of authentication tokens and sensitive data
- **Audit Trails**: Comprehensive logging of all test activities for compliance
- **Data Privacy**: Automatic sanitization of sensitive data in logs and reports
## Contributing
TestAPIX is designed for extensibility. Common contribution areas:
- **Custom Assertions**: Domain-specific validation logic
- **Authentication Providers**: Enterprise authentication systems
- **Data Generators**: Industry-specific test data patterns
- **Security Tests**: Additional vulnerability detection patterns
- **Report Formats**: Integration with monitoring and alerting systems
See our [Contributing Guide](CONTRIBUTING.md) for development setup and guidelines.
## Development Roadmap
### Phase 1 - Core Foundation (Complete)
- Modern async API Client with intelligent retry logic
- Fluent assertion library with comprehensive validation
- Multi-environment configuration system
- Intelligent CLI with project scaffolding
- Advanced test generation with best practices
### Phase 2 - Enhanced Features (Complete)
- Persona-based authentication system
- Interactive CLI with session management
- Advanced error reporting and batch operations
- JSON Schema validation system
- Comprehensive security testing framework
### Phase 3 - Advanced Integration (In Progress)
- Plugin system for custom extensions
- Enhanced contract testing with API evolution tracking
- Comprehensive performance testing and load generation
- Extended GraphQL support and testing
### Phase 4 - Ecosystem & Tooling (Planned)
- IDE plugins (VS Code, PyCharm) with intelligent test generation
- Cloud service integrations (AWS, Azure, GCP)
- Advanced CI/CD integrations and pipeline templates
- Real-time collaboration features for team testing
### Phase 5 - AI-Powered Testing (Future)
- Intelligent test case generation from API usage patterns
- Automated vulnerability discovery and test creation
- Natural language test specification and generation
- Predictive API reliability and performance analysis
## License
TestAPIX is released under the MIT License. See [LICENSE](LICENSE) for details.
## Acknowledgments
TestAPIX stands on the shoulders of giants in the Python ecosystem:
- **[httpx](https://www.python-httpx.org/)** - Modern, async API Client foundation
- **[pytest](https://pytest.org/)** - Powerful, flexible testing framework
- **[Click](https://click.palletsprojects.com/)** - Beautiful command-line interface creation
- **[Rich](https://rich.readthedocs.io/)** - Rich terminal output and interactive interfaces
- **[Pydantic](https://pydantic-docs.helpmanual.io/)** - Data validation and settings management
- **[Mimesis](https://mimesis.name/)** - Realistic test data generation
- **[Prompt Toolkit](https://python-prompt-toolkit.readthedocs.io/)** - Interactive CLI foundation
- **[Jinja2](https://jinja.palletsprojects.com/)** - Flexible template engine for code generation
## Get Started Now!
Ready to transform your API testing workflow?
### Quick Start (2 minutes)
```bash
pip install 'testapix[interactive]'
testapix init my-first-project
cd my-first-project
testapix generate functional my-api
pytest tests/ -v
```
### Interactive Exploration (30 seconds)
```bash
pip install 'testapix[interactive]'
testapix interactive --api https://jsonplaceholder.typicode.com
```
### Security Testing
```bash
pip install 'testapix[interactive]'
testapix init secure-api-tests --template microservices
testapix generate security payment-api --endpoints "/charge,/refund"
pytest tests/security/ -v
```
---
<p align="center">
<strong>Built by API testing professionals who believe comprehensive testing should be intuitive, powerful, and enjoyable.</strong>
</p>
<p align="center">
Join the TestAPIX community and help shape the future of intelligent API testing.
</p>
Raw data
{
"_id": null,
"home_page": null,
"name": "testapix",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.11",
"maintainer_email": null,
"keywords": "api, testing, framework, pytest, automation, test",
"author": "Your Name",
"author_email": "your.email@example.com",
"download_url": "https://files.pythonhosted.org/packages/0b/ae/fce856ec53055c8faab3d2017a513b79254f3f33e8b9b73df62220f9cc80/testapix-0.1.4.tar.gz",
"platform": null,
"description": "# TestAPIX - Modern Python API Testing Framework\n\n[](https://www.python.org/downloads/)\n[](https://opensource.org/licenses/MIT)\n[](https://github.com/psf/black)\n\nTestAPIX is a modern, comprehensive API testing framework designed to make API testing both powerful and accessible. Built from the ground up with Python async patterns, TestAPIX provides everything from simple functional tests to sophisticated security testing, schema validation, and interactive API exploration.\n\n## Why TestAPIX?\n\nTraditional API testing tools force you to choose between simplicity and power. TestAPIX eliminates this compromise by providing:\n\n**Instant Productivity**: Get from zero to comprehensive tests in under 5 minutes with our intelligent CLI and generated examples that demonstrate best practices.\n\n**Learning Through Examples**: Every generated test includes detailed comments explaining not just what the code does, but why it's structured that way and how to extend it.\n\n**Progressive Enhancement**: Start simple with basic functional tests, then seamlessly adopt advanced features like security testing, persona-based authentication, and interactive exploration as your needs evolve.\n\n**Actionable Insights**: When tests fail, TestAPIX provides clear, contextual error messages with suggestions for resolution, not cryptic stack traces.\n\n**Interactive Development**: Explore APIs in real-time with our rich interactive CLI, then generate tests from your exploration sessions.\n\n## Key Features\n\n### Comprehensive Testing Capabilities\n- **Async-First Architecture**: Built on modern Python async/await for superior performance and scalability\n- **Fluent Assertions**: Write tests that read like specifications with comprehensive assertion chaining\n- **Smart API Client**: Automatic retries, intelligent error handling, and response enhancement\n- **Realistic Test Data**: Context-aware data generation that uncovers real edge cases and bugs\n\n### Security Testing\n- **OWASP-Compliant Security Tests**: Comprehensive security vulnerability testing including:\n - SQL injection prevention validation\n - Cross-Site Scripting (XSS) attack detection\n - Authentication and authorization boundary testing\n - Rate limiting and abuse prevention verification\n - Security headers validation\n- **Security Test Payloads**: Comprehensive payloads across multiple attack vectors\n- **Responsible Testing**: Built-in safeguards and warnings for ethical security testing\n\n### Persona-Based Authentication Testing\n- **Business-Context Authentication**: Test with realistic user personas and roles\n- **Multi-Provider Support**: Bearer tokens, API keys, OAuth2, Basic Auth, and custom providers\n- **Session Management**: Automatic token refresh, auth failure handling, and session persistence\n- **Cross-Authentication Testing**: Validate proper isolation between different user contexts\n\n### Interactive API Exploration\n- **Rich Interactive CLI**: Explore APIs in real-time with syntax highlighting and intelligent suggestions\n- **Session Management**: Save and restore exploration sessions with secure credential handling\n- **Test Generation**: Convert interactive sessions into automated test files\n- **Multiple Export Formats**: Generate tests in pytest, curl, Postman collection, or Python requests format\n\n### Developer Experience Excellence\n- **Intelligent CLI**: Generate projects, tests, and configurations with helpful guidance and validation\n- **Multi-Environment Support**: Seamlessly test across development, staging, and production environments\n- **Advanced Error Reporting**: Batch error aggregation, detailed context, and intelligent error suggestions\n- **Schema Validation**: JSON Schema validation with detailed mismatch reporting\n- **Extensible Architecture**: Plugin-ready design for custom assertions, generators, and authentication providers\n\n## Quick Start\n\n### Installation\n\nInstall TestAPIX from PyPI:\n\n```bash\n# Basic installation\npip install testapix\n\n# Full installation with interactive CLI support\npip install 'testapix[interactive]'\n```\n\n### Option 1: Traditional Project Setup\n\nCreate a structured test project:\n\n```bash\n# Create a new test project\ntestapix init my-api-tests\n\n# Navigate to your project\ncd my-api-tests\n\n# Generate comprehensive functional tests\ntestapix generate functional user-api\n\n# Run your tests\npytest tests/ -v\n```\n\n### Option 2: Interactive API Exploration\n\nStart exploring APIs immediately:\n\n```bash\n# Launch interactive CLI\ntestapix interactive --api https://api.example.com\n\n# Or with authentication\ntestapix interactive --api https://api.example.com\n```\n\n```bash\n# In the interactive shell:\nTestAPIX Interactive Shell\n> auth bearer your-token-here\nAuthentication configured\n\n> get /users\nGET /users \u2192 200 OK (234ms)\n{\n \"users\": [{\"id\": 1, \"name\": \"John\", \"email\": \"john@example.com\"}]\n}\n\n> generate test functional my-users-test.py\nTest file generated from session history\n\n> save my-exploration-session\nSession saved for later use\n```\n\nThat's it! You now have either a complete test project or interactive exploration ready to generate tests.\n\n## Core Usage Examples\n\n### Writing Comprehensive Tests\n\nTestAPIX tests are clean, readable, and powerful:\n\n```python\nimport pytest\nfrom testapix import APIClient, assert_that\nfrom testapix.generators import BaseGenerator\n\nclass TestUserAPI:\n def setup_method(self):\n self.generator = BaseGenerator()\n\n @pytest.fixture(autouse=True)\n def setup(self, api_client: APIClient):\n self.client = api_client\n\n async def test_create_user_comprehensive(self):\n # Generate realistic test data\n user_data = self.generator.generate_user_data()\n\n # Create user with comprehensive validation\n response = await self.client.post(\"/users\", json=user_data)\n\n # Fluent assertions with detailed validation\n assert_that(response) \\\n .has_status(201) \\\n .has_header(\"location\") \\\n .has_json_path(\"id\") \\\n .has_json_path(\"email\") \\\n .response_time_less_than(2.0)\n\n # Verify user can be retrieved\n user_id = response.json().get(\"id\")\n get_response = await self.client.get(f\"/users/{user_id}\")\n assert_that(get_response) \\\n .has_status(200) \\\n .has_json_path(\"id\")\n```\n\n### Persona-Based Authentication Testing\n\nTest with realistic business contexts:\n\n```python\nfrom testapix.auth import PersonaPool, UserPersona, PersonaRole\n\nclass TestUserPermissions:\n def setup_method(self):\n # Define business personas\n self.personas = PersonaPool([\n UserPersona(\n name=\"admin_user\",\n role=PersonaRole.ADMIN,\n credentials={\"token\": \"admin-token-here\"}\n ),\n UserPersona(\n name=\"regular_user\",\n role=PersonaRole.USER,\n credentials={\"token\": \"user-token-here\"}\n )\n ])\n\n async def test_admin_can_delete_users(self):\n # Test as admin persona\n async with self.personas.get_client(\"admin_user\") as admin_client:\n response = await admin_client.delete(\"/users/123\")\n assert_that(response).has_status(204)\n\n async def test_user_cannot_delete_users(self):\n # Test as regular user persona\n async with self.personas.get_client(\"regular_user\") as user_client:\n response = await user_client.delete(\"/users/123\")\n assert_that(response).has_status(403)\n```\n\n### Security Testing\n\nComprehensive security validation:\n\n```python\nfrom testapix.generators import BaseGenerator\n\nclass TestAPISecurity:\n def setup_method(self):\n self.generator = BaseGenerator()\n\n @pytest.mark.security\n async def test_sql_injection_protection(self, api_client: APIClient):\n \"\"\"Verify API protects against SQL injection attacks.\"\"\"\n\n # Generate SQL injection payloads\n payloads = self.generator.generate_security_test_data(\"sql_injection\")\n\n for payload_name, payload in payloads.items():\n response = await api_client.get(\"/users\", params={\"search\": payload})\n\n # API should either reject malicious input or handle it safely\n assert response.status_code in [400, 401, 403, 422] or \\\n (response.status_code == 200 and \"error\" not in response.text.lower()), \\\n f\"SQL injection vulnerability detected with payload: {payload_name}\"\n\n @pytest.mark.security\n async def test_xss_protection(self, api_client: APIClient):\n \"\"\"Verify API protects against XSS attacks.\"\"\"\n\n xss_payloads = self.generator.generate_security_test_data(\"xss\")\n\n for payload_name, payload in xss_payloads.items():\n user_data = {\"name\": payload, \"email\": \"test@example.com\"}\n response = await api_client.post(\"/users\", json=user_data)\n\n if response.status_code == 201:\n # If user created, ensure XSS payload is properly escaped\n user_id = response.json().get(\"id\")\n get_response = await api_client.get(f\"/users/{user_id}\")\n assert_that(get_response).has_status(200)\n # Verify no script tags in response\n assert \"<script>\" not in get_response.text\n assert \"javascript:\" not in get_response.text\n assert \"onerror=\" not in get_response.text\n```\n\n### Multi-Environment Configuration\n\nSeamless environment management:\n\n```yaml\n# configs/base.yaml\nhttp:\n timeout: 30.0\n retries: 3\n verify_ssl: true\n\nauth:\n type: \"bearer\"\n token: \"${TESTAPIX_AUTH_TOKEN}\"\n\nsecurity_testing:\n enable_sql_injection: true\n enable_xss_tests: true\n max_payload_size: 10000\n\nreporting:\n formats: [\"console\", \"html\", \"junit\"]\n output_dir: \"reports\"\n```\n\n```yaml\n# configs/staging.yaml\nhttp:\n base_url: \"https://staging-api.example.com\"\n timeout: 60.0 # Longer timeout for staging\n\nsecurity_testing:\n enable_sql_injection: false # Skip in staging\n```\n\n```bash\n# Run tests across environments\nTESTAPIX_ENVIRONMENT=local pytest tests/\nTESTAPIX_ENVIRONMENT=staging pytest tests/ -m \"not destructive\"\nTESTAPIX_ENVIRONMENT=production pytest tests/ -m \"smoke\"\n```\n\n## Interactive CLI Features\n\nThe TestAPIX Interactive CLI provides a rich, terminal-based environment for real-time API exploration:\n\n### Key Interactive Features\n\n- **Authentication Management**: Configure and switch between multiple authentication methods\n- **Rich Response Display**: JSON syntax highlighting with intelligent data analysis\n- **Session Persistence**: Save exploration sessions and reload them later\n- **Test Generation**: Convert interactive sessions into automated test files\n- **Advanced Response Analysis**: Extract data with JSON paths, validate schemas, analyze performance\n\n### Interactive CLI Example Session\n\n```bash\n$ testapix interactive --api https://api.github.com\n\nTestAPIX Interactive Shell - API Exploration Environment\nConnected to: https://api.github.com\n\n# Configure authentication\n> auth bearer ghp_your_token_here\nAuthentication configured\n\n# Explore endpoints with rich output\n> get /user\nGET /user \u2192 200 OK (156ms)\n{\n \"login\": \"octocat\",\n \"id\": 1,\n \"name\": \"The Octocat\",\n \"email\": \"octocat@github.com\"\n}\n\n# Extract specific data\n> extract login\nExtracted: \"octocat\"\n\n# Save session for later\n> save github-exploration\nSession saved: github-exploration\n\n# Generate test file from session\n> generate test testapix github_tests.py\nGenerated test file: github_tests.py\n - 5 test methods created from session history\n - Includes authentication setup\n - Comprehensive assertions included\n\n# Export in different formats\n> export curl github_commands.sh\nExported 5 curl commands to github_commands.sh\n\n> export postman github_collection.json\nExported Postman collection to github_collection.json\n```\n\n## Project Structure\n\nTestAPIX projects follow a comprehensive, scalable structure:\n\n```\nmy-api-tests/\n\u251c\u2500\u2500 configs/ # Environment configurations\n\u2502 \u251c\u2500\u2500 base.yaml # Shared settings\n\u2502 \u251c\u2500\u2500 local.yaml # Local development overrides\n\u2502 \u251c\u2500\u2500 staging.yaml # Staging environment settings\n\u2502 \u2514\u2500\u2500 production.yaml # Production settings (smoke tests only)\n\u251c\u2500\u2500 tests/ # Test suites organized by paradigm\n\u2502 \u251c\u2500\u2500 functional/ # API functionality tests\n\u2502 \u251c\u2500\u2500 security/ # Security vulnerability tests\n\u2502 \u251c\u2500\u2500 contract/ # Basic response structure validation\n\u2502 \u251c\u2500\u2500 performance/ # Response time and basic load tests\n\u2502 \u2514\u2500\u2500 integration/ # End-to-end integration tests\n\u251c\u2500\u2500 personas/ # User personas and authentication configs\n\u2502 \u251c\u2500\u2500 admin_personas.yaml # Admin user configurations\n\u2502 \u2514\u2500\u2500 user_personas.yaml # Regular user configurations\n\u251c\u2500\u2500 data_generators/ # Custom test data generators\n\u2502 \u251c\u2500\u2500 user_generator.py # User-specific data generation\n\u2502 \u2514\u2500\u2500 product_generator.py # Product/business domain data\n\u251c\u2500\u2500 schemas/ # API schemas and validation rules\n\u2502 \u251c\u2500\u2500 openapi.yaml # OpenAPI/Swagger specifications\n\u2502 \u2514\u2500\u2500 json_schemas/ # JSON schema validation files\n\u251c\u2500\u2500 reports/ # Test execution reports\n\u2502 \u251c\u2500\u2500 coverage/ # Test coverage reports\n\u2502 \u251c\u2500\u2500 security/ # Security scan results\n\u2502 \u2514\u2500\u2500 performance/ # Performance test results\n\u251c\u2500\u2500 sessions/ # Saved interactive CLI sessions\n\u2514\u2500\u2500 .testapix/ # Framework configuration and cache\n```\n\n## Advanced Features\n\n### Security Testing\n\nTestAPIX includes production-ready security testing capabilities:\n\n```bash\n# Generate comprehensive security test suite\ntestapix generate security payment-api --endpoints \"/charge,/refund,/admin\"\n```\n\n**Generated Security Test Categories:**\n\n1. **Authentication & Authorization**\n - Missing authentication detection\n - Invalid token/credential testing\n - Cross-user authorization boundary validation\n - Privilege escalation attempt detection\n\n2. **Injection Attack Prevention**\n - SQL injection with 13+ attack vectors\n - XSS prevention with 14+ payload variations\n - Command injection detection\n - Path traversal attack testing\n - LDAP and XML injection testing\n\n3. **HTTP Security Standards**\n - Security headers validation (CSP, HSTS, X-Frame-Options)\n - Basic CORS configuration testing\n - Content-type validation\n\n4. **Rate Limiting & Basic Abuse Prevention**\n - Basic rate limiting detection\n - Request validation testing\n\n### Basic Contract Testing & Schema Validation\n\nEnsure API compatibility and data integrity:\n\n```bash\n# Generate basic contract tests from OpenAPI specification\ntestapix generate contract user-api --schema-file openapi.yaml\n```\n\n**Note**: TestAPIX provides basic response structure validation and schema compliance checking. For full consumer-driven contract testing and API evolution management, consider complementing with specialized contract testing tools.\n\n### Advanced Error Reporting & Debugging\n\nTestAPIX provides sophisticated error analysis:\n\n```python\nfrom testapix import batch_operation, get_batch_aggregator\n\n# Batch operations with comprehensive error aggregation\nasync def test_bulk_user_operations(api_client):\n user_ids = [1, 2, 3, 4, 5]\n\n async with batch_operation(\"bulk_user_deletion\"):\n for user_id in user_ids:\n response = await api_client.delete(f\"/users/{user_id}\")\n assert_that(response).has_status(204)\n\n # Get detailed error report if any operations failed\n error_report = get_batch_aggregator().get_detailed_report()\n if error_report.has_errors():\n print(error_report.format_with_suggestions())\n```\n\n### Performance Testing\n\nBasic performance validation capabilities:\n\n```python\n@pytest.mark.performance\nasync def test_api_performance_requirements(api_client):\n \"\"\"Validate API meets basic performance requirements.\"\"\"\n\n # Test response time requirements\n response = await api_client.get(\"/users\", params={\"limit\": 100})\n assert_that(response) \\\n .has_status(200) \\\n .response_time_less_than(2.0)\n\n # Test basic concurrent request handling\n import asyncio\n async def make_request():\n return await api_client.get(\"/users\")\n\n # Execute 5 concurrent requests\n responses = await asyncio.gather(*[make_request() for _ in range(5)])\n\n assert all(r.status_code == 200 for r in responses)\n```\n\n**Note**: TestAPIX provides basic performance testing for response times and simple concurrent requests. For comprehensive load testing, consider integrating with specialized tools like Locust or Artillery.\n\n## CLI Command Reference\n\n### Project Management\n```bash\n# Initialize new testing project\ntestapix init my-project --template advanced\n\n# Validate configuration files\ntestapix validate-config --environment staging\n```\n\n### Test Generation\n```bash\n# Functional tests\ntestapix generate functional user-api --endpoints \"/users,/profiles\"\n\n# Security tests (with safety warnings)\ntestapix generate security api --endpoints \"/admin,/payment\"\n\n# Basic contract tests from OpenAPI spec\ntestapix generate contract api --schema-file swagger.yaml\n\n# Basic performance tests\ntestapix generate performance api --endpoints \"/search,/reports\"\n```\n\n### Interactive Exploration\n```bash\n# Basic interactive session\ntestapix interactive\n\n# With API URL and authentication\ntestapix interactive --api https://api.example.com --auth-file auth.yaml\n\n# Load previous session\ntestapix interactive --session my-saved-session\n```\n\n## Learning Resources\n\nTestAPIX is designed as a teaching tool that promotes best practices:\n\n### Generated Code Quality\n- **Comprehensive Documentation**: Every generated test includes detailed comments explaining patterns and best practices\n- **Real-World Examples**: Generated tests demonstrate actual edge cases and error scenarios you'll encounter\n- **Progressive Complexity**: Start with basic patterns and learn advanced techniques through example\n- **Best Practice Patterns**: Authentication handling, error management, and test organization following industry standards\n\n### Educational Features\n- **Error Context**: When tests fail, get explanations of what went wrong and how to fix it\n- **Pattern Recognition**: Learn to recognize anti-patterns and security vulnerabilities through hands-on testing\n- **Interactive Learning**: Use the CLI to explore APIs and understand their behavior before writing tests\n\n## Enterprise Deployment\n\n### CI/CD Integration\n\nTestAPIX integrates seamlessly with modern CI/CD pipelines:\n\n```yaml\n# .github/workflows/api-tests.yml\nname: API Tests\n\non: [push, pull_request]\n\njobs:\n test:\n runs-on: ubuntu-latest\n strategy:\n matrix:\n test-type: [functional, security, contract]\n\n steps:\n - uses: actions/checkout@v4\n\n - name: Set up Python\n uses: actions/setup-python@v4\n with:\n python-version: '3.11'\n\n - name: Install TestAPIX\n run: pip install 'testapix[interactive]'\n\n - name: Run API Tests\n run: |\n testapix validate-config\n pytest tests/${{ matrix.test-type }}/ -v --junit-xml=reports/results.xml\n\n - name: Upload Test Results\n uses: actions/upload-artifact@v3\n with:\n name: test-results-${{ matrix.test-type }}\n path: reports/\n```\n\n### Security & Compliance\n\n- **Responsible Testing**: Built-in warnings and safeguards for security testing\n- **Credential Management**: Secure handling of authentication tokens and sensitive data\n- **Audit Trails**: Comprehensive logging of all test activities for compliance\n- **Data Privacy**: Automatic sanitization of sensitive data in logs and reports\n\n## Contributing\n\nTestAPIX is designed for extensibility. Common contribution areas:\n\n- **Custom Assertions**: Domain-specific validation logic\n- **Authentication Providers**: Enterprise authentication systems\n- **Data Generators**: Industry-specific test data patterns\n- **Security Tests**: Additional vulnerability detection patterns\n- **Report Formats**: Integration with monitoring and alerting systems\n\nSee our [Contributing Guide](CONTRIBUTING.md) for development setup and guidelines.\n\n## Development Roadmap\n\n### Phase 1 - Core Foundation (Complete)\n- Modern async API Client with intelligent retry logic\n- Fluent assertion library with comprehensive validation\n- Multi-environment configuration system\n- Intelligent CLI with project scaffolding\n- Advanced test generation with best practices\n\n### Phase 2 - Enhanced Features (Complete)\n- Persona-based authentication system\n- Interactive CLI with session management\n- Advanced error reporting and batch operations\n- JSON Schema validation system\n- Comprehensive security testing framework\n\n### Phase 3 - Advanced Integration (In Progress)\n- Plugin system for custom extensions\n- Enhanced contract testing with API evolution tracking\n- Comprehensive performance testing and load generation\n- Extended GraphQL support and testing\n\n### Phase 4 - Ecosystem & Tooling (Planned)\n- IDE plugins (VS Code, PyCharm) with intelligent test generation\n- Cloud service integrations (AWS, Azure, GCP)\n- Advanced CI/CD integrations and pipeline templates\n- Real-time collaboration features for team testing\n\n### Phase 5 - AI-Powered Testing (Future)\n- Intelligent test case generation from API usage patterns\n- Automated vulnerability discovery and test creation\n- Natural language test specification and generation\n- Predictive API reliability and performance analysis\n\n## License\n\nTestAPIX is released under the MIT License. See [LICENSE](LICENSE) for details.\n\n## Acknowledgments\n\nTestAPIX stands on the shoulders of giants in the Python ecosystem:\n\n- **[httpx](https://www.python-httpx.org/)** - Modern, async API Client foundation\n- **[pytest](https://pytest.org/)** - Powerful, flexible testing framework\n- **[Click](https://click.palletsprojects.com/)** - Beautiful command-line interface creation\n- **[Rich](https://rich.readthedocs.io/)** - Rich terminal output and interactive interfaces\n- **[Pydantic](https://pydantic-docs.helpmanual.io/)** - Data validation and settings management\n- **[Mimesis](https://mimesis.name/)** - Realistic test data generation\n- **[Prompt Toolkit](https://python-prompt-toolkit.readthedocs.io/)** - Interactive CLI foundation\n- **[Jinja2](https://jinja.palletsprojects.com/)** - Flexible template engine for code generation\n\n## Get Started Now!\n\nReady to transform your API testing workflow?\n\n### Quick Start (2 minutes)\n```bash\npip install 'testapix[interactive]'\ntestapix init my-first-project\ncd my-first-project\ntestapix generate functional my-api\npytest tests/ -v\n```\n\n### Interactive Exploration (30 seconds)\n```bash\npip install 'testapix[interactive]'\ntestapix interactive --api https://jsonplaceholder.typicode.com\n```\n\n### Security Testing\n```bash\npip install 'testapix[interactive]'\ntestapix init secure-api-tests --template microservices\ntestapix generate security payment-api --endpoints \"/charge,/refund\"\npytest tests/security/ -v\n```\n\n---\n\n<p align=\"center\">\n <strong>Built by API testing professionals who believe comprehensive testing should be intuitive, powerful, and enjoyable.</strong>\n</p>\n\n<p align=\"center\">\n Join the TestAPIX community and help shape the future of intelligent API testing.\n</p>\n\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A comprehensive Python API testing framework",
"version": "0.1.4",
"project_urls": {
"Documentation": "https://testapix.readthedocs.io",
"Homepage": "https://github.com/yourusername/testapix",
"Repository": "https://github.com/yourusername/testapix"
},
"split_keywords": [
"api",
" testing",
" framework",
" pytest",
" automation",
" test"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "812f9a05903a8814e9b0e0c36452abd88b22f3c5228a0095a92bb49fac2953c8",
"md5": "22f4b28ecef42cf9d3a94cddbd9fec92",
"sha256": "c3985fd5889eb2a168808995e58dcda2dc4b3cc2c8f2cf5128724b6aa95e6835"
},
"downloads": -1,
"filename": "testapix-0.1.4-py3-none-any.whl",
"has_sig": false,
"md5_digest": "22f4b28ecef42cf9d3a94cddbd9fec92",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.11",
"size": 195206,
"upload_time": "2025-08-10T07:05:03",
"upload_time_iso_8601": "2025-08-10T07:05:03.623688Z",
"url": "https://files.pythonhosted.org/packages/81/2f/9a05903a8814e9b0e0c36452abd88b22f3c5228a0095a92bb49fac2953c8/testapix-0.1.4-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "0baefce856ec53055c8faab3d2017a513b79254f3f33e8b9b73df62220f9cc80",
"md5": "4facaf1489c5eafb02dab2c36a89b26b",
"sha256": "e26126acf85c45ba0d7202c8dc9b67de760d00cc37074c2c5edc4cecba66c048"
},
"downloads": -1,
"filename": "testapix-0.1.4.tar.gz",
"has_sig": false,
"md5_digest": "4facaf1489c5eafb02dab2c36a89b26b",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.11",
"size": 172215,
"upload_time": "2025-08-10T07:05:04",
"upload_time_iso_8601": "2025-08-10T07:05:04.998962Z",
"url": "https://files.pythonhosted.org/packages/0b/ae/fce856ec53055c8faab3d2017a513b79254f3f33e8b9b73df62220f9cc80/testapix-0.1.4.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-10 07:05:04",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "yourusername",
"github_project": "testapix",
"github_not_found": true,
"lcname": "testapix"
}