MkDocs documentation integration
This commit is contained in:
164
docs/api/index.md
Normal file
164
docs/api/index.md
Normal file
@@ -0,0 +1,164 @@
|
||||
# API Overview
|
||||
|
||||
The Letzshop Import API provides comprehensive endpoints for managing products, shops, users, and marketplace imports. This section provides high-level guidance and concepts for working with our API.
|
||||
|
||||
## Interactive Documentation
|
||||
|
||||
For hands-on API exploration and testing, use our interactive documentation:
|
||||
|
||||
!!! tip "Live API Documentation"
|
||||
- **[Swagger UI](http://localhost:8000/docs)** - Interactive API testing interface
|
||||
- **[ReDoc](http://localhost:8000/redoc)** - Clean, readable API reference
|
||||
- **[OpenAPI Spec](http://localhost:8000/openapi.json)** - Machine-readable API specification
|
||||
|
||||
## API Structure
|
||||
|
||||
### Base URL
|
||||
```
|
||||
Production: https://api.letzshop.com/api/v1
|
||||
Development: http://localhost:8000/api/v1
|
||||
```
|
||||
|
||||
### API Versioning
|
||||
All API endpoints are versioned using URL path versioning:
|
||||
- Current version: `v1`
|
||||
- All endpoints are prefixed with `/api/v1/`
|
||||
|
||||
## Endpoint Categories
|
||||
|
||||
### Authentication (`/auth/`)
|
||||
- User registration and login
|
||||
- Token refresh and validation
|
||||
- Password reset workflows
|
||||
|
||||
### Admin (`/admin/`)
|
||||
- User management (admin only)
|
||||
- System statistics
|
||||
- Configuration management
|
||||
|
||||
### Products (`/products/`)
|
||||
- Product CRUD operations
|
||||
- Product search and filtering
|
||||
- Bulk operations
|
||||
|
||||
### Shops (`/shops/`)
|
||||
- Shop management
|
||||
- Shop-product associations
|
||||
- Shop statistics
|
||||
|
||||
### Stock (`/stock/`)
|
||||
- Inventory management
|
||||
- Stock movements
|
||||
- Stock reporting
|
||||
|
||||
### Marketplace (`/marketplace/`)
|
||||
- Import job management
|
||||
- CSV file processing
|
||||
- Import status tracking
|
||||
|
||||
### Statistics (`/stats/`)
|
||||
- System-wide statistics
|
||||
- User activity metrics
|
||||
- Import performance data
|
||||
|
||||
## Request/Response Format
|
||||
|
||||
### Content Type
|
||||
All API endpoints use JSON for request and response bodies:
|
||||
```
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
### Standard Response Format
|
||||
```json
|
||||
{
|
||||
"data": {...}, // Main response data
|
||||
"message": "Success", // Human-readable message
|
||||
"status": 200 // HTTP status code
|
||||
}
|
||||
```
|
||||
|
||||
### Error Response Format
|
||||
```json
|
||||
{
|
||||
"detail": "Error description",
|
||||
"type": "validation_error",
|
||||
"errors": [ // Field-specific errors (if applicable)
|
||||
{
|
||||
"field": "email",
|
||||
"message": "Invalid email format"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Pagination
|
||||
Most list endpoints support pagination:
|
||||
|
||||
```bash
|
||||
GET /api/v1/products?skip=0&limit=20
|
||||
```
|
||||
|
||||
Response includes pagination metadata:
|
||||
```json
|
||||
{
|
||||
"items": [...],
|
||||
"total": 150,
|
||||
"skip": 0,
|
||||
"limit": 20,
|
||||
"has_next": true
|
||||
}
|
||||
```
|
||||
|
||||
### Filtering and Searching
|
||||
Many endpoints support filtering and search:
|
||||
|
||||
```bash
|
||||
GET /api/v1/products?search=laptop&category=electronics&min_price=100
|
||||
```
|
||||
|
||||
### Sorting
|
||||
Use the `sort` parameter with field names:
|
||||
|
||||
```bash
|
||||
GET /api/v1/products?sort=name&order=desc
|
||||
```
|
||||
|
||||
## Status Codes
|
||||
|
||||
| Code | Meaning | Description |
|
||||
|------|---------|-------------|
|
||||
| 200 | OK | Request successful |
|
||||
| 201 | Created | Resource created successfully |
|
||||
| 204 | No Content | Request successful, no content returned |
|
||||
| 400 | Bad Request | Invalid request data |
|
||||
| 401 | Unauthorized | Authentication required |
|
||||
| 403 | Forbidden | Insufficient permissions |
|
||||
| 404 | Not Found | Resource not found |
|
||||
| 422 | Unprocessable Entity | Validation error |
|
||||
| 429 | Too Many Requests | Rate limit exceeded |
|
||||
| 500 | Internal Server Error | Server error |
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
API endpoints are rate limited to ensure fair usage:
|
||||
|
||||
- **Default limit**: 100 requests per minute per IP
|
||||
- **Authenticated users**: 1000 requests per minute
|
||||
- **Admin users**: 5000 requests per minute
|
||||
|
||||
Rate limit headers are included in responses:
|
||||
```
|
||||
X-RateLimit-Limit: 100
|
||||
X-RateLimit-Remaining: 95
|
||||
X-RateLimit-Reset: 1640995200
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- **[Authentication Guide](authentication.md)** - Learn about API authentication
|
||||
- **[Error Handling](error-handling.md)** - Understanding API errors
|
||||
- **[Rate Limiting](rate-limiting.md)** - Rate limiting details
|
||||
- **[Interactive Docs](http://localhost:8000/docs)** - Try the API live
|
||||
242
docs/getting-started/installation.md
Normal file
242
docs/getting-started/installation.md
Normal file
@@ -0,0 +1,242 @@
|
||||
# Installation Guide
|
||||
|
||||
This guide will help you set up the Letzshop Import application for development or production use.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before you begin, ensure you have the following installed:
|
||||
|
||||
- **Python 3.10 or higher**
|
||||
- **PostgreSQL 12 or higher**
|
||||
- **Git**
|
||||
- **Docker** (optional, for containerized deployment)
|
||||
|
||||
## Development Setup
|
||||
|
||||
### 1. Clone the Repository
|
||||
|
||||
```bash
|
||||
git clone https://github.com/yourusername/letzshop-import.git
|
||||
cd letzshop-import
|
||||
```
|
||||
|
||||
### 2. Create Virtual Environment
|
||||
|
||||
=== "Windows"
|
||||
```bash
|
||||
python -m venv venv
|
||||
venv\Scripts\activate
|
||||
```
|
||||
|
||||
=== "macOS/Linux"
|
||||
```bash
|
||||
python -m venv venv
|
||||
source venv/bin/activate
|
||||
```
|
||||
|
||||
### 3. Install Dependencies
|
||||
|
||||
```bash
|
||||
# Install main application dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Install development dependencies
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
# Install test dependencies
|
||||
pip install -r tests/requirements-test.txt
|
||||
|
||||
# Install documentation dependencies (optional)
|
||||
pip install -r requirements-docs.txt
|
||||
```
|
||||
|
||||
### 4. Database Setup
|
||||
|
||||
#### Option A: Local PostgreSQL
|
||||
|
||||
1. **Create Database**:
|
||||
```sql
|
||||
CREATE DATABASE letzshop_import;
|
||||
CREATE USER letzshop_user WITH PASSWORD 'your_password';
|
||||
GRANT ALL PRIVILEGES ON DATABASE letzshop_import TO letzshop_user;
|
||||
```
|
||||
|
||||
2. **Create Environment File**:
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
3. **Configure `.env` file**:
|
||||
```env
|
||||
# Database
|
||||
DATABASE_URL=postgresql://letzshop_user:your_password@localhost/letzshop_import
|
||||
|
||||
# Security
|
||||
SECRET_KEY=your-super-secret-key-here
|
||||
JWT_SECRET_KEY=your-jwt-secret-key-here
|
||||
|
||||
# Environment
|
||||
ENVIRONMENT=development
|
||||
DEBUG=True
|
||||
```
|
||||
|
||||
#### Option B: Docker PostgreSQL
|
||||
|
||||
```bash
|
||||
docker run --name letzshop-postgres \
|
||||
-e POSTGRES_DB=letzshop_import \
|
||||
-e POSTGRES_USER=letzshop_user \
|
||||
-e POSTGRES_PASSWORD=your_password \
|
||||
-p 5432:5432 \
|
||||
-d postgres:15
|
||||
```
|
||||
|
||||
### 5. Initialize Database
|
||||
|
||||
```bash
|
||||
# Run database migrations
|
||||
python -m alembic upgrade head
|
||||
|
||||
# Create initial admin user (optional)
|
||||
python scripts/create_admin.py
|
||||
```
|
||||
|
||||
### 6. Run the Application
|
||||
|
||||
```bash
|
||||
# Start development server
|
||||
uvicorn main:app --reload --host 0.0.0.0 --port 8000
|
||||
```
|
||||
|
||||
The application will be available at:
|
||||
- **API**: http://localhost:8000
|
||||
- **Interactive API Docs**: http://localhost:8000/docs
|
||||
- **Alternative API Docs**: http://localhost:8000/redoc
|
||||
|
||||
## Docker Setup
|
||||
|
||||
### Quick Start with Docker Compose
|
||||
|
||||
1. **Clone and navigate to project**:
|
||||
```bash
|
||||
git clone https://github.com/yourusername/letzshop-import.git
|
||||
cd letzshop-import
|
||||
```
|
||||
|
||||
2. **Start all services**:
|
||||
```bash
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
3. **Initialize database**:
|
||||
```bash
|
||||
docker-compose exec api python -m alembic upgrade head
|
||||
```
|
||||
|
||||
### Manual Docker Setup
|
||||
|
||||
1. **Build the image**:
|
||||
```bash
|
||||
docker build -t letzshop-import .
|
||||
```
|
||||
|
||||
2. **Run with environment variables**:
|
||||
```bash
|
||||
docker run -d \
|
||||
--name letzshop-api \
|
||||
-p 8000:8000 \
|
||||
-e DATABASE_URL="postgresql://user:pass@host/db" \
|
||||
-e SECRET_KEY="your-secret-key" \
|
||||
letzshop-import
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
### 1. Check Application Health
|
||||
|
||||
```bash
|
||||
curl http://localhost:8000/health
|
||||
```
|
||||
|
||||
Expected response:
|
||||
```json
|
||||
{
|
||||
"status": "healthy",
|
||||
"database": "connected",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Run Tests
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
pytest
|
||||
|
||||
# Run specific test types
|
||||
pytest -m unit
|
||||
pytest -m integration
|
||||
```
|
||||
|
||||
### 3. Access Documentation
|
||||
|
||||
- **Swagger UI**: http://localhost:8000/docs
|
||||
- **ReDoc**: http://localhost:8000/redoc
|
||||
- **This Documentation** (if running MkDocs): http://localhost:8001
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Description | Default | Required |
|
||||
|----------|-------------|---------|----------|
|
||||
| `DATABASE_URL` | PostgreSQL connection string | - | ✅ |
|
||||
| `SECRET_KEY` | Application secret key | - | ✅ |
|
||||
| `JWT_SECRET_KEY` | JWT token secret | - | ✅ |
|
||||
| `ENVIRONMENT` | Environment (dev/staging/prod) | `development` | ❌ |
|
||||
| `DEBUG` | Enable debug mode | `False` | ❌ |
|
||||
| `LOG_LEVEL` | Logging level | `INFO` | ❌ |
|
||||
| `CORS_ORIGINS` | Allowed CORS origins | `["*"]` | ❌ |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Database Connection Issues
|
||||
```bash
|
||||
# Check if PostgreSQL is running
|
||||
pg_isready -h localhost -p 5432
|
||||
|
||||
# Check database connectivity
|
||||
python -c "from app.core.database import engine; engine.connect()"
|
||||
```
|
||||
|
||||
#### Port Already in Use
|
||||
```bash
|
||||
# Find process using port 8000
|
||||
lsof -i :8000
|
||||
|
||||
# Kill the process
|
||||
kill -9 <PID>
|
||||
```
|
||||
|
||||
#### Permission Issues
|
||||
```bash
|
||||
# Fix file permissions
|
||||
chmod +x scripts/*.py
|
||||
|
||||
# Fix virtual environment permissions
|
||||
chmod -R 755 venv/
|
||||
```
|
||||
|
||||
### Getting Help
|
||||
|
||||
If you encounter issues:
|
||||
|
||||
1. Check the [Troubleshooting Guide](../development/troubleshooting.md)
|
||||
2. Review application logs: `docker-compose logs api`
|
||||
3. Open an [issue on GitHub](https://github.com/yourusername/letzshop-import/issues)
|
||||
|
||||
## Next Steps
|
||||
|
||||
- **[Quick Start Guide](quickstart.md)** - Get familiar with basic operations
|
||||
- **[Configuration Guide](configuration.md)** - Detailed configuration options
|
||||
- **[API Documentation](../api/index.md)** - Explore the API endpoints
|
||||
117
docs/index.md
Normal file
117
docs/index.md
Normal file
@@ -0,0 +1,117 @@
|
||||
# Letzshop Import Documentation
|
||||
|
||||
Welcome to the complete documentation for the Letzshop Import application - a comprehensive marketplace product import and management system built with FastAPI.
|
||||
|
||||
## What is Letzshop Import?
|
||||
|
||||
Letzshop Import is a powerful web application that enables:
|
||||
|
||||
- **Product Management**: Create, update, and manage product catalogs
|
||||
- **Shop Management**: Multi-shop support with individual configurations
|
||||
- **CSV Import**: Bulk import products from various marketplace formats
|
||||
- **Stock Management**: Track inventory across multiple locations
|
||||
- **User Management**: Role-based access control for different user types
|
||||
- **Marketplace Integration**: Import from various marketplace platforms
|
||||
|
||||
## Quick Navigation
|
||||
|
||||
### 🚀 Get Started
|
||||
- [**Installation Guide**](getting-started/installation.md) - Set up the application
|
||||
- [**Quick Start**](getting-started/quickstart.md) - Get running in minutes
|
||||
- [**Configuration**](getting-started/configuration.md) - Environment setup
|
||||
|
||||
### 📚 API Documentation
|
||||
- [**Interactive API Docs**](http://localhost:8000/docs) - Swagger UI for live testing
|
||||
- [**Alternative API Docs**](http://localhost:8000/redoc) - ReDoc interface
|
||||
- [**API Overview**](api/index.md) - High-level API concepts
|
||||
- [**Authentication Guide**](api/authentication.md) - Security and auth flows
|
||||
|
||||
### 📖 User Guides
|
||||
- [**User Management**](guides/user-management.md) - Managing users and roles
|
||||
- [**Product Management**](guides/product-management.md) - Working with products
|
||||
- [**CSV Import**](guides/csv-import.md) - Bulk import workflows
|
||||
- [**Shop Setup**](guides/shop-setup.md) - Configuring shops
|
||||
|
||||
### 🧪 Testing
|
||||
- [**Test Naming Conventions**](testing/test-naming-conventions.md) - Our testing standards
|
||||
- [**Running Tests**](testing/running-tests.md) - How to run the test suite
|
||||
|
||||
### 🔧 Development
|
||||
- [**Architecture**](development/architecture.md) - System design overview
|
||||
- [**Database Schema**](development/database-schema.md) - Data model documentation
|
||||
- [**Contributing**](development/contributing.md) - How to contribute
|
||||
|
||||
### 🚢 Deployment
|
||||
- [**Docker Deployment**](deployment/docker.md) - Containerized deployment
|
||||
- [**Production Setup**](deployment/production.md) - Production best practices
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
Client[Web Client/API Consumer]
|
||||
API[FastAPI Application]
|
||||
Auth[Authentication Service]
|
||||
Products[Product Service]
|
||||
Shops[Shop Service]
|
||||
Import[Import Service]
|
||||
DB[(PostgreSQL Database)]
|
||||
|
||||
Client --> API
|
||||
API --> Auth
|
||||
API --> Products
|
||||
API --> Shops
|
||||
API --> Import
|
||||
Auth --> DB
|
||||
Products --> DB
|
||||
Shops --> DB
|
||||
Import --> DB
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
=== "Product Management"
|
||||
- CRUD operations for products
|
||||
- GTIN validation and normalization
|
||||
- Price management with currency support
|
||||
- Category and attribute management
|
||||
- Bulk operations support
|
||||
|
||||
=== "Import System"
|
||||
- CSV file processing
|
||||
- Multiple marketplace format support
|
||||
- Validation and error reporting
|
||||
- Batch processing for large files
|
||||
- Import job tracking and status
|
||||
|
||||
=== "Multi-Shop Support"
|
||||
- Independent shop configurations
|
||||
- Shop-specific product associations
|
||||
- Inventory tracking per shop
|
||||
- Role-based shop access
|
||||
|
||||
=== "Security"
|
||||
- JWT-based authentication
|
||||
- Role-based access control (RBAC)
|
||||
- API key management
|
||||
- Input validation and sanitization
|
||||
- Rate limiting
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **Backend**: FastAPI, Python 3.10+
|
||||
- **Database**: PostgreSQL with SQLAlchemy ORM
|
||||
- **Authentication**: JWT tokens
|
||||
- **Testing**: pytest with comprehensive test suite
|
||||
- **Documentation**: MkDocs Material + FastAPI auto-docs
|
||||
- **Deployment**: Docker, Docker Compose
|
||||
|
||||
## Getting Help
|
||||
|
||||
- **Issues**: [GitHub Issues](https://github.com/yourusername/letzshop-import/issues)
|
||||
- **Discussions**: [GitHub Discussions](https://github.com/yourusername/letzshop-import/discussions)
|
||||
- **API Testing**: Use the [Swagger UI](http://localhost:8000/docs) for interactive testing
|
||||
|
||||
---
|
||||
|
||||
Ready to get started? Head over to the [Installation Guide](getting-started/installation.md)!
|
||||
383
docs/testing/test-naming-conventions.md
Normal file
383
docs/testing/test-naming-conventions.md
Normal file
@@ -0,0 +1,383 @@
|
||||
# Test Naming Conventions
|
||||
|
||||
This document outlines the naming conventions used in our test suite to ensure consistency, clarity, and maintainability across the project.
|
||||
|
||||
## Overview
|
||||
|
||||
Our test suite follows a hierarchical structure organized by test type and component, with clear naming patterns that make it easy to locate and understand test purposes.
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
tests/
|
||||
├── conftest.py # Core test configuration and fixtures
|
||||
├── pytest.ini # Pytest configuration
|
||||
├── fixtures/ # Shared test fixtures organized by domain
|
||||
├── unit/ # Fast, isolated component tests
|
||||
├── integration/ # Multi-component interaction tests
|
||||
├── performance/ # Performance and load tests
|
||||
├── system/ # End-to-end system behavior tests
|
||||
└── test_data/ # Test data files (CSV, JSON, etc.)
|
||||
```
|
||||
|
||||
## File Naming Conventions
|
||||
|
||||
### General Rule
|
||||
All test files must start with `test_` prefix for pytest auto-discovery.
|
||||
|
||||
**Pattern:** `test_{component/feature}.py`
|
||||
|
||||
### Unit Tests (`tests/unit/`)
|
||||
|
||||
Focus on testing individual components in isolation.
|
||||
|
||||
```
|
||||
tests/unit/
|
||||
├── models/
|
||||
│ ├── test_database_models.py # Database model tests
|
||||
│ ├── test_api_models.py # API model validation
|
||||
│ └── test_model_relationships.py # Model relationship tests
|
||||
├── utils/
|
||||
│ ├── test_data_processing.py # Data processing utilities
|
||||
│ ├── test_csv_processor.py # CSV processing utilities
|
||||
│ ├── test_validators.py # Validation utilities
|
||||
│ └── test_formatters.py # Data formatting utilities
|
||||
├── services/
|
||||
│ ├── test_admin_service.py # Admin service business logic
|
||||
│ ├── test_auth_service.py # Authentication service
|
||||
│ ├── test_product_service.py # Product management service
|
||||
│ ├── test_shop_service.py # Shop management service
|
||||
│ ├── test_stock_service.py # Stock management service
|
||||
│ ├── test_marketplace_service.py # Marketplace import service
|
||||
│ └── test_stats_service.py # Statistics service
|
||||
└── core/
|
||||
├── test_config.py # Configuration management
|
||||
├── test_database.py # Database utilities
|
||||
└── test_logging.py # Logging functionality
|
||||
```
|
||||
|
||||
### Integration Tests (`tests/integration/`)
|
||||
|
||||
Focus on testing interactions between multiple components.
|
||||
|
||||
```
|
||||
tests/integration/
|
||||
├── api/v1/
|
||||
│ ├── test_auth_endpoints.py # Authentication API endpoints
|
||||
│ ├── test_admin_endpoints.py # Admin API endpoints
|
||||
│ ├── test_product_endpoints.py # Product CRUD endpoints
|
||||
│ ├── test_shop_endpoints.py # Shop management endpoints
|
||||
│ ├── test_stock_endpoints.py # Stock management endpoints
|
||||
│ ├── test_marketplace_endpoints.py # Import endpoints
|
||||
│ ├── test_stats_endpoints.py # Statistics endpoints
|
||||
│ └── test_pagination.py # Pagination functionality
|
||||
├── database/
|
||||
│ ├── test_migrations.py # Database migration tests
|
||||
│ ├── test_transactions.py # Transaction handling
|
||||
│ └── test_constraints.py # Database constraints
|
||||
├── security/
|
||||
│ ├── test_authentication.py # Authentication mechanisms
|
||||
│ ├── test_authorization.py # Permission and role tests
|
||||
│ ├── test_input_validation.py # Input security validation
|
||||
│ ├── test_rate_limiting.py # Rate limiting middleware
|
||||
│ └── test_cors.py # CORS configuration
|
||||
└── workflows/
|
||||
├── test_product_import_workflow.py # Complete import process
|
||||
├── test_user_registration_flow.py # User registration process
|
||||
└── test_shop_setup_flow.py # Shop creation workflow
|
||||
```
|
||||
|
||||
### System Tests (`tests/system/`)
|
||||
|
||||
Focus on end-to-end application behavior.
|
||||
|
||||
```
|
||||
tests/system/
|
||||
├── test_application_startup.py # Application initialization
|
||||
├── test_error_handling.py # Global error handling
|
||||
├── test_health_checks.py # Health endpoint tests
|
||||
├── test_database_connectivity.py # Database connection tests
|
||||
└── test_external_dependencies.py # Third-party service tests
|
||||
```
|
||||
|
||||
### Performance Tests (`tests/performance/`)
|
||||
|
||||
Focus on performance benchmarks and load testing.
|
||||
|
||||
```
|
||||
tests/performance/
|
||||
├── test_api_performance.py # API endpoint performance
|
||||
├── test_database_performance.py # Database query performance
|
||||
├── test_import_performance.py # Large file import tests
|
||||
└── test_concurrent_users.py # Multi-user scenarios
|
||||
```
|
||||
|
||||
## Class Naming Conventions
|
||||
|
||||
Use descriptive class names that clearly indicate what is being tested:
|
||||
|
||||
### Pattern: `Test{ComponentName}{TestType}`
|
||||
|
||||
```python
|
||||
# Good examples
|
||||
class TestProductService: # Testing ProductService class
|
||||
class TestProductModel: # Testing Product model
|
||||
class TestProductEndpoints: # Testing product API endpoints
|
||||
class TestProductValidation: # Testing product validation logic
|
||||
class TestProductPermissions: # Testing product access control
|
||||
|
||||
# Avoid generic names
|
||||
class TestProduct: # Too vague - what aspect of Product?
|
||||
class Tests: # Too generic
|
||||
```
|
||||
|
||||
### Specialized Class Naming
|
||||
|
||||
```python
|
||||
class TestProductCRUD: # CRUD operations
|
||||
class TestProductSecurity: # Security-related tests
|
||||
class TestProductErrorHandling: # Error scenario tests
|
||||
class TestProductEdgeCases: # Boundary condition tests
|
||||
```
|
||||
|
||||
## Method Naming Conventions
|
||||
|
||||
Test method names should be descriptive and follow a clear pattern that explains:
|
||||
1. What is being tested
|
||||
2. The scenario/condition
|
||||
3. Expected outcome
|
||||
|
||||
### Pattern: `test_{action}_{scenario}_{expected_outcome}`
|
||||
|
||||
```python
|
||||
# Good examples - Clear and descriptive
|
||||
def test_create_product_with_valid_data_returns_product():
|
||||
def test_create_product_with_invalid_gtin_raises_validation_error():
|
||||
def test_get_product_by_id_when_not_found_returns_404():
|
||||
def test_update_product_without_permission_raises_forbidden():
|
||||
def test_delete_product_with_existing_stock_prevents_deletion():
|
||||
|
||||
# Acceptable shorter versions
|
||||
def test_create_product_success():
|
||||
def test_create_product_invalid_data():
|
||||
def test_create_product_unauthorized():
|
||||
def test_get_product_not_found():
|
||||
```
|
||||
|
||||
### Method Naming Patterns by Scenario
|
||||
|
||||
**Happy Path Tests:**
|
||||
```python
|
||||
def test_create_user_success():
|
||||
def test_login_valid_credentials():
|
||||
def test_import_csv_valid_format():
|
||||
```
|
||||
|
||||
**Error/Edge Case Tests:**
|
||||
```python
|
||||
def test_create_user_duplicate_email_fails():
|
||||
def test_login_invalid_credentials_rejected():
|
||||
def test_import_csv_malformed_data_raises_error():
|
||||
```
|
||||
|
||||
**Permission/Security Tests:**
|
||||
```python
|
||||
def test_admin_endpoint_requires_admin_role():
|
||||
def test_user_cannot_access_other_user_data():
|
||||
def test_api_key_required_for_marketplace_import():
|
||||
```
|
||||
|
||||
**Boundary/Edge Cases:**
|
||||
```python
|
||||
def test_pagination_with_zero_items():
|
||||
def test_price_with_maximum_decimal_places():
|
||||
def test_gtin_with_minimum_valid_length():
|
||||
```
|
||||
|
||||
## Marker Usage
|
||||
|
||||
Use pytest markers to categorize and run specific test types:
|
||||
|
||||
```python
|
||||
@pytest.mark.unit
|
||||
class TestProductService:
|
||||
"""Unit tests for ProductService business logic"""
|
||||
|
||||
@pytest.mark.integration
|
||||
@pytest.mark.api
|
||||
class TestProductEndpoints:
|
||||
"""Integration tests for Product API endpoints"""
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.performance
|
||||
class TestImportPerformance:
|
||||
"""Performance tests for large CSV imports"""
|
||||
```
|
||||
|
||||
### Available Markers
|
||||
|
||||
| Marker | Purpose |
|
||||
|--------|---------|
|
||||
| `@pytest.mark.unit` | Fast, isolated component tests |
|
||||
| `@pytest.mark.integration` | Multi-component interaction tests |
|
||||
| `@pytest.mark.system` | End-to-end system tests |
|
||||
| `@pytest.mark.performance` | Performance and load tests |
|
||||
| `@pytest.mark.slow` | Long-running tests |
|
||||
| `@pytest.mark.api` | API endpoint tests |
|
||||
| `@pytest.mark.database` | Tests requiring database |
|
||||
| `@pytest.mark.auth` | Authentication/authorization tests |
|
||||
| `@pytest.mark.admin` | Admin functionality tests |
|
||||
|
||||
## File Organization Best Practices
|
||||
|
||||
### Mirror Source Structure
|
||||
Test files should mirror the source code structure:
|
||||
|
||||
```
|
||||
app/services/product_service.py → tests/unit/services/test_product_service.py
|
||||
app/api/v1/admin.py → tests/integration/api/v1/test_admin_endpoints.py
|
||||
```
|
||||
|
||||
### Group Related Tests
|
||||
Keep related tests in the same file:
|
||||
|
||||
```python
|
||||
# test_product_service.py
|
||||
class TestProductCreation: # All product creation scenarios
|
||||
class TestProductValidation: # All validation scenarios
|
||||
class TestProductQueries: # All query scenarios
|
||||
```
|
||||
|
||||
### Separate Complex Workflows
|
||||
Break complex workflows into separate files:
|
||||
|
||||
```
|
||||
test_user_registration_flow.py # Complete registration process
|
||||
test_shop_setup_flow.py # Shop creation workflow
|
||||
test_product_import_workflow.py # CSV import end-to-end
|
||||
```
|
||||
|
||||
## Running Tests by Name Pattern
|
||||
|
||||
Use pytest's flexible test discovery:
|
||||
|
||||
```bash
|
||||
# Run all unit tests
|
||||
pytest tests/unit/ -v
|
||||
|
||||
# Run specific component tests
|
||||
pytest tests/ -k "product" -v
|
||||
|
||||
# Run by marker
|
||||
pytest -m "unit and not slow" -v
|
||||
|
||||
# Run specific test class
|
||||
pytest tests/unit/services/test_product_service.py::TestProductService -v
|
||||
|
||||
# Run specific test method
|
||||
pytest tests/unit/services/test_product_service.py::TestProductService::test_create_product_success -v
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Complete Test File Example
|
||||
|
||||
```python
|
||||
# tests/unit/services/test_product_service.py
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from app.services.product_service import ProductService
|
||||
from app.models.database_models import Product
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestProductService:
|
||||
"""Unit tests for ProductService business logic"""
|
||||
|
||||
def setup_method(self):
|
||||
"""Setup run before each test method"""
|
||||
self.service = ProductService()
|
||||
self.mock_db = Mock()
|
||||
|
||||
def test_create_product_with_valid_data_returns_product(self):
|
||||
"""Test successful product creation with valid input data"""
|
||||
# Arrange
|
||||
product_data = {
|
||||
"name": "Test Product",
|
||||
"gtin": "1234567890123",
|
||||
"price": "19.99"
|
||||
}
|
||||
|
||||
# Act
|
||||
result = self.service.create_product(product_data)
|
||||
|
||||
# Assert
|
||||
assert result is not None
|
||||
assert result.name == "Test Product"
|
||||
|
||||
def test_create_product_with_invalid_gtin_raises_validation_error(self):
|
||||
"""Test product creation fails with invalid GTIN format"""
|
||||
# Arrange
|
||||
product_data = {
|
||||
"name": "Test Product",
|
||||
"gtin": "invalid_gtin",
|
||||
"price": "19.99"
|
||||
}
|
||||
|
||||
# Act & Assert
|
||||
with pytest.raises(ValidationError, match="Invalid GTIN format"):
|
||||
self.service.create_product(product_data)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestProductValidation:
|
||||
"""Unit tests for product validation logic"""
|
||||
|
||||
def test_validate_gtin_with_valid_format_returns_true(self):
|
||||
"""Test GTIN validation accepts valid 13-digit GTIN"""
|
||||
assert ProductService.validate_gtin("1234567890123") is True
|
||||
|
||||
def test_validate_gtin_with_invalid_format_returns_false(self):
|
||||
"""Test GTIN validation rejects invalid format"""
|
||||
assert ProductService.validate_gtin("invalid") is False
|
||||
```
|
||||
|
||||
## Naming Anti-Patterns to Avoid
|
||||
|
||||
❌ **Avoid these patterns:**
|
||||
|
||||
```python
|
||||
# Too generic
|
||||
def test_product():
|
||||
def test_user():
|
||||
def test_api():
|
||||
|
||||
# Unclear purpose
|
||||
def test_function():
|
||||
def test_method():
|
||||
def test_endpoint():
|
||||
|
||||
# Non-descriptive
|
||||
def test_1():
|
||||
def test_a():
|
||||
def test_scenario():
|
||||
|
||||
# Inconsistent naming
|
||||
def testProductCreation(): # Wrong case
|
||||
def test_product_creation(): # Good
|
||||
def TestProductCreation(): # Wrong - this is for classes
|
||||
```
|
||||
|
||||
✅ **Use these patterns instead:**
|
||||
|
||||
```python
|
||||
# Clear, descriptive, consistent
|
||||
def test_create_product_with_valid_data_succeeds():
|
||||
def test_authenticate_user_with_invalid_token_fails():
|
||||
def test_get_products_endpoint_returns_paginated_results():
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Following these naming conventions will help maintain a clean, understandable, and maintainable test suite that scales with your project.
|
||||
Reference in New Issue
Block a user