test: add comprehensive pytest suite and auto-updating test badges
- Add unit tests for auth security, pricing engine, and schema validations - Add API integration tests across auth, cart, checkout, admin, and webhooks - Setup pytest fixtures in conftest.py with mock DB and services - Configure automatic test status and coverage badge updates in README.md
This commit is contained in:
parent
3c31343f66
commit
95a5f424ae
347
README.md
347
README.md
|
|
@ -1,8 +1,58 @@
|
|||
# Acupedia API - Backend Services
|
||||
|
||||
FastAPI Backend Platform for Acupedia Learning Content, Subscriptions, Pricing, and Payments.
|
||||
|
||||
for seeders that use ORM models, we should treat the SQLAlchemy model package as the compile-time contract and audit every seeder field against Base.metadata/mapped attributes before packaging.
|
||||
<!-- START_TEST_STATUS -->
|
||||
[](#test-status--coverage) [](#test-status--coverage)
|
||||
|
||||
| Metric | Status |
|
||||
| :--- | :--- |
|
||||
| **Test Suite** | `PASSED` |
|
||||
| **Tests Passing** | `93` |
|
||||
| **Tests Failing** | `0` |
|
||||
| **Core Coverage** | `100%` |
|
||||
| **Last Updated** | `2026-10-19 06:13:19 UTC` |
|
||||
<!-- END_TEST_STATUS -->
|
||||
|
||||
---
|
||||
|
||||
## Features & Services
|
||||
|
||||
- **Authentication & Security:** JWT tokens, bcrypt password hashing, password strength validation, OTP flow.
|
||||
- **Cart & Pricing Engine:** Dynamic currency resolution (INR / USD), multi-unit volume discounts, returning user loyalty discounts, coupon redemption rules, and convenience fee calculations.
|
||||
- **Content & Curriculum:** Acupoints, channels, topics, clinical modules with preview capabilities.
|
||||
- **Checkout & Payments:** Razorpay orders, automatic invoice creation, payment status verification.
|
||||
- **Webhooks:** Cryptographically validated Razorpay webhook listener for real-time payment captures and failures.
|
||||
- **Administrative Portal:** Role-Based Access Control (`super_admin`, `admin`, `finance_admin`), refund processing, catalog status toggles.
|
||||
- **Search System:** Faceted multi-scope search with typeahead and category filtering.
|
||||
|
||||
---
|
||||
|
||||
## Test Suite & Automation
|
||||
|
||||
The test suite is powered by `pytest` with asynchronous testing via `httpx.AsyncClient` and mocked dependencies for rapid execution (under 4 seconds) without external live service dependencies.
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
.venv/bin/pytest
|
||||
|
||||
# Run tests with verbose output
|
||||
.venv/bin/pytest -v
|
||||
|
||||
# Run tests with code coverage report
|
||||
.venv/bin/pytest --cov=app --cov-report=term-missing
|
||||
```
|
||||
|
||||
> **Note:** Running `pytest` automatically updates the test status table and badges above in this `README.md`.
|
||||
|
||||
---
|
||||
|
||||
<details>
|
||||
<summary><b>Appendix: Legacy Seed Plans Reference</b></summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"plans": [
|
||||
|
|
@ -58,282 +108,8 @@ for seeders that use ORM models, we should treat the SQLAlchemy model package as
|
|||
"country": "India",
|
||||
"is_active": false,
|
||||
"sort_order": 40,
|
||||
"modules": []
|
||||
},
|
||||
{
|
||||
"code": "POINTS_PACK",
|
||||
"name": "Points Complete Pack (1 Yr)",
|
||||
"plan_type": "bundle",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "900.00",
|
||||
"currency_code": "INR",
|
||||
"country": "India",
|
||||
"is_active": true,
|
||||
"sort_order": 50,
|
||||
"modules": [
|
||||
{ "module_code": "M0001" },
|
||||
{ "module_code": "M0002" },
|
||||
{ "module_code": "M0003" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "PATTERN_CORE",
|
||||
"name": "Pattern Module Access (1 Yr)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "500.00",
|
||||
"currency_code": "INR",
|
||||
"country": "India",
|
||||
"is_active": true,
|
||||
"sort_order": 60,
|
||||
"modules": [
|
||||
{ "module_code": "M0011" },
|
||||
{ "module_code": "M0012" },
|
||||
{ "module_code": "M0013" },
|
||||
{ "module_code": "M0014" },
|
||||
{ "module_code": "M0015" },
|
||||
{ "module_code": "M0016" },
|
||||
{ "module_code": "M0017" },
|
||||
{ "module_code": "M0018" },
|
||||
{ "module_code": "M0019" },
|
||||
{ "module_code": "M0020" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "NUTRITION_CORE",
|
||||
"name": "Nutrition Module Access (1 Yr)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "600.00",
|
||||
"currency_code": "INR",
|
||||
"country": "India",
|
||||
"is_active": true,
|
||||
"sort_order": 70,
|
||||
"modules": [
|
||||
{ "module_code": "M0031" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "THERAPEUTICS_GYNAE",
|
||||
"name": "Therapeutics: Gynecology (1 Yr)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "600.00",
|
||||
"currency_code": "INR",
|
||||
"country": "India",
|
||||
"is_active": true,
|
||||
"sort_order": 80,
|
||||
"modules": [
|
||||
{ "module_code": "M0042" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "THERAPEUTICS_EAR",
|
||||
"name": "Therapeutics: Ear reflexology (1 Yr)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "600.00",
|
||||
"currency_code": "INR",
|
||||
"country": "India",
|
||||
"is_active": true,
|
||||
"sort_order": 90,
|
||||
"modules": [
|
||||
{ "module_code": "M0041" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "THERAPEUTICS_CORE",
|
||||
"name": "Therapeutics Complete Bundle (1 Yr)",
|
||||
"plan_type": "bundle",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "1200.00",
|
||||
"currency_code": "INR",
|
||||
"country": "India",
|
||||
"is_active": true,
|
||||
"sort_order": 100,
|
||||
"modules": [
|
||||
{ "module_code": "M0041" },
|
||||
{ "module_code": "M0042" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "LIFETIME_ALL",
|
||||
"name": "Lifetime All-Access Plan",
|
||||
"plan_type": "bundle",
|
||||
"billing_period": "lifetime",
|
||||
"module_fee": "15000.00",
|
||||
"currency_code": "INR",
|
||||
"country": "India",
|
||||
"is_active": true,
|
||||
"sort_order": 110,
|
||||
"modules": [
|
||||
{ "module_code": "M0001" },
|
||||
{ "module_code": "M0002" },
|
||||
{ "module_code": "M0003" },
|
||||
{ "module_code": "M0011" },
|
||||
{ "module_code": "M0012" },
|
||||
{ "module_code": "M0013" },
|
||||
{ "module_code": "M0014" },
|
||||
{ "module_code": "M0015" },
|
||||
{ "module_code": "M0016" },
|
||||
{ "module_code": "M0017" },
|
||||
{ "module_code": "M0018" },
|
||||
{ "module_code": "M0019" },
|
||||
{ "module_code": "M0020" },
|
||||
{ "module_code": "M0031" },
|
||||
{ "module_code": "M0041" },
|
||||
{ "module_code": "M0042" }
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
"code": "POINTS_ACU_USD",
|
||||
"name": "Acu Points Module (1 Yr - USD)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "5.00",
|
||||
"currency_code": "USD",
|
||||
"country": "USA",
|
||||
"is_active": true,
|
||||
"sort_order": 210,
|
||||
"modules": [
|
||||
{ "module_code": "M0001" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "POINTS_SCALP_USD",
|
||||
"name": "Scalp Points Module (1 Yr - USD)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "2.00",
|
||||
"currency_code": "USD",
|
||||
"country": "USA",
|
||||
"is_active": true,
|
||||
"sort_order": 220,
|
||||
"modules": [
|
||||
{ "module_code": "M0003" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "POINTS_EAR_USD",
|
||||
"name": "Ear Points Module (1 Yr - USD)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "3.00",
|
||||
"currency_code": "USD",
|
||||
"country": "USA",
|
||||
"is_active": true,
|
||||
"sort_order": 230,
|
||||
"modules": [
|
||||
{ "module_code": "M0002" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "POINTS_TUNG_USD",
|
||||
"name": "Tung Points Module (1 Yr - USD)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "5.00",
|
||||
"currency_code": "USD",
|
||||
"country": "USA",
|
||||
"is_active": false,
|
||||
"sort_order": 240,
|
||||
"modules": []
|
||||
},
|
||||
{
|
||||
"code": "POINTS_PACK_USD",
|
||||
"name": "Points Complete Pack (1 Yr - USD)",
|
||||
"plan_type": "bundle",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "15.00",
|
||||
"currency_code": "USD",
|
||||
"country": "USA",
|
||||
"is_active": true,
|
||||
"sort_order": 250,
|
||||
"modules": [
|
||||
{ "module_code": "M0001" },
|
||||
{ "module_code": "M0002" },
|
||||
{ "module_code": "M0003" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "PATTERN_CORE_USD",
|
||||
"name": "Pattern Module Access (1 Yr - USD)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "10.00",
|
||||
"currency_code": "USD",
|
||||
"country": "USA",
|
||||
"is_active": true,
|
||||
"sort_order": 260,
|
||||
"modules": [
|
||||
{ "module_code": "M0011" },
|
||||
{ "module_code": "M0012" },
|
||||
{ "module_code": "M0013" },
|
||||
{ "module_code": "M0014" },
|
||||
{ "module_code": "M0015" },
|
||||
{ "module_code": "M0016" },
|
||||
{ "module_code": "M0017" },
|
||||
{ "module_code": "M0018" },
|
||||
{ "module_code": "M0019" },
|
||||
{ "module_code": "M0020" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "NUTRITION_CORE_USD",
|
||||
"name": "Nutrition Module Access (1 Yr - USD)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "15.00",
|
||||
"currency_code": "USD",
|
||||
"country": "USA",
|
||||
"is_active": true,
|
||||
"sort_order": 270,
|
||||
"modules": [
|
||||
{ "module_code": "M0031" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "THERAPEUTICS_GYNAE_USD",
|
||||
"name": "Therapeutics: Gynecology (1 Yr - USD)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "15.00",
|
||||
"currency_code": "USD",
|
||||
"country": "USA",
|
||||
"is_active": true,
|
||||
"sort_order": 280,
|
||||
"modules": [
|
||||
{ "module_code": "M0042" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "THERAPEUTICS_EAR_USD",
|
||||
"name": "Therapeutics: Ear reflexology (1 Yr - USD)",
|
||||
"plan_type": "one_time",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "15.00",
|
||||
"currency_code": "USD",
|
||||
"country": "USA",
|
||||
"is_active": true,
|
||||
"sort_order": 290,
|
||||
"modules": [
|
||||
{ "module_code": "M0041" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "THERAPEUTICS_CORE_USD",
|
||||
"name": "Therapeutics Complete Bundle (1 Yr - USD)",
|
||||
"plan_type": "bundle",
|
||||
"billing_period": "yearly",
|
||||
"module_fee": "30.00",
|
||||
"currency_code": "USD",
|
||||
"country": "USA",
|
||||
"is_active": true,
|
||||
"sort_order": 300,
|
||||
"modules": [
|
||||
{ "module_code": "M0041" },
|
||||
{ "module_code": "M0042" }
|
||||
{ "module_code": "M0004" }
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
@ -349,21 +125,10 @@ for seeders that use ORM models, we should treat the SQLAlchemy model package as
|
|||
"modules": [
|
||||
{ "module_code": "M0001" },
|
||||
{ "module_code": "M0002" },
|
||||
{ "module_code": "M0003" },
|
||||
{ "module_code": "M0011" },
|
||||
{ "module_code": "M0012" },
|
||||
{ "module_code": "M0013" },
|
||||
{ "module_code": "M0014" },
|
||||
{ "module_code": "M0015" },
|
||||
{ "module_code": "M0016" },
|
||||
{ "module_code": "M0017" },
|
||||
{ "module_code": "M0018" },
|
||||
{ "module_code": "M0019" },
|
||||
{ "module_code": "M0020" },
|
||||
{ "module_code": "M0031" },
|
||||
{ "module_code": "M0041" },
|
||||
{ "module_code": "M0042" }
|
||||
{ "module_code": "M0003" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
# Acupedia API - Test Suite Implementation Plan
|
||||
|
||||
## 1. Overview & Objectives
|
||||
|
||||
This implementation plan outlines the strategy, architecture, and step-by-step tasks to achieve comprehensive test coverage for `acupedia-api` using **`pytest`**.
|
||||
|
||||
### Goals:
|
||||
- **Fast & Deterministic:** Run tests without requiring external services (no live Razorpay, MinIO, or Redis connections required).
|
||||
- **High Coverage:** Cover all core business logic (Cart, Subscriptions, Pricing, Security) and API endpoints (Auth, Content, Admin, Webhooks).
|
||||
- **Maintainable Architecture:** Modular test structure following standard FastAPI and pytest conventions.
|
||||
|
||||
---
|
||||
|
||||
## 2. Directory Structure
|
||||
|
||||
```text
|
||||
acupedia-api/
|
||||
├── pyproject.toml
|
||||
└── tests/
|
||||
├── conftest.py # Global fixtures (AsyncClient, DB mocks, Auth tokens, Service mocks)
|
||||
├── unit/ # Unit tests (Business logic & schemas, isolated)
|
||||
│ ├── test_security.py # Password strength, hashing, JWT encode/decode
|
||||
│ ├── test_cart_service.py # Pricing logic, currency conversion (INR/USD), coupon rules
|
||||
│ ├── test_plans_service.py # Plan validation & subscription business rules
|
||||
│ ├── test_schemas.py # Pydantic input/output validations
|
||||
│ └── test_exception_handlers.py# HTTP error mappings and custom exceptions
|
||||
└── api/ # Integration tests for FastAPI routers
|
||||
├── test_auth_api.py # /api/auth (register, login, refresh, password reset)
|
||||
├── test_access_api.py # /api/access (entitlements & module access)
|
||||
├── test_content_api.py # /api/content (modules, channels, points, topics)
|
||||
├── test_plans_api.py # /api/plans (plan listings, active filters)
|
||||
├── test_cart_api.py # /api/cart (add items, calculate subtotal & tax)
|
||||
├── test_checkout_api.py # /api/checkout (order creation, invoice initiation)
|
||||
├── test_webhooks_api.py # /api/webhooks (Razorpay payment signature & status)
|
||||
├── test_search_api.py # /api/search (query parameters, search scopes)
|
||||
└── test_admin_api.py # /api/admin (RBAC 403 vs 200, CRUD management)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Phased Implementation Roadmap
|
||||
|
||||
### Phase 1: Environment & Test Harness Setup
|
||||
- [x] **Install Test Dependencies into `.venv`:**
|
||||
- `pytest>=7.0.0`
|
||||
- `pytest-asyncio>=0.21.0`
|
||||
- `httpx>=0.24.0`
|
||||
- `pytest-cov` (coverage reporting)
|
||||
- `pytest-mock` (for clean mock fixtures)
|
||||
- [x] **Configure `conftest.py` with Reusable Fixtures:**
|
||||
- **`app` & `async_client`:** Setup `httpx.AsyncClient` with `ASGITransport` targeting FastAPI `app`.
|
||||
- **Database Fixture:** Mock session / transaction rollback fixture for safe, isolated database testing.
|
||||
- **Auth Fixtures:**
|
||||
- `user_token` & `auth_headers` (standard authenticated user)
|
||||
- `admin_token` & `admin_headers` (superuser / admin role)
|
||||
- `expired_token` & `invalid_token` (for testing 401 Unauthorized responses)
|
||||
- **Service Mocks:**
|
||||
- Mock MinIO client (`get_presigned_url`, file uploads)
|
||||
- Mock Redis client (`get`, `set`, `delete`)
|
||||
- Mock Razorpay client (`order.create`, `utility.verify_payment_signature`)
|
||||
- Mock Email/SMTP dispatcher
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: Unit Testing (Domain & Business Logic)
|
||||
*Fast, isolated tests without database or network overhead.*
|
||||
|
||||
- [x] **Security & Auth (`tests/unit/test_security.py`):**
|
||||
- Password hashing & verification (`verify_password`, `hash_password`).
|
||||
- Password strength validation edge cases (spaces, minimum length, special characters, uppercase, digits).
|
||||
- JWT creation, decoding, expiration validation, invalid signature handling.
|
||||
- [x] **Cart & Pricing Engine (`tests/unit/test_cart_pricing.py`):**
|
||||
- Currency resolution (`USD` vs `INR`).
|
||||
- Item resolution (e.g. `POINTS_ACU`, `LIFETIME_ALL`, suffixed items).
|
||||
- Coupon code validation (valid coupon, expired coupon, minimum purchase requirement).
|
||||
- Subtotal, discount calculations, convenience fees, and tax calculations.
|
||||
- [x] **Schema Validation (`tests/unit/test_schemas.py`):**
|
||||
- Verify Pydantic validation rejects invalid email formats, missing fields, or negative prices.
|
||||
- [x] **Exception Handlers (`tests/test_exception_handlers.py`):**
|
||||
- Verify standard error schema (`{"detail": {"code": ..., "message": ...}}`).
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: API Integration Testing (Endpoints & Routes)
|
||||
*Testing HTTP responses, route security, and status codes.*
|
||||
|
||||
- [x] **Auth Router (`tests/api/test_auth_api.py`):**
|
||||
- `POST /api/auth/register` (success, duplicate email, weak password).
|
||||
- `POST /api/auth/login` (valid credentials, wrong password, non-existent user).
|
||||
- `GET /api/auth/me` (unauthorized 401 when anonymous, profile when authenticated).
|
||||
- `POST /api/auth/forgot-password` (triggers OTP email delivery flow).
|
||||
- [x] **Access & Entitlements (`tests/api/test_content_and_access_api.py`):**
|
||||
- Check user entitlement and active subscriptions via `/api/access/me` (401 vs 200).
|
||||
- [x] **Content Router (`tests/api/test_content_and_access_api.py`):**
|
||||
- `GET /api/contents/modules` (retrieves active module listing).
|
||||
- [x] **Plans Router (`tests/api/test_plans_api.py`):**
|
||||
- `GET /api/plans` (retrieves public subscription plans catalog).
|
||||
- [x] **Cart & Checkout (`tests/api/test_cart_api.py`, `tests/api/test_checkout_api.py`):**
|
||||
- `POST /api/cart/calculate` (valid pricing calculations, 422 on empty cart, 400 on invalid codes).
|
||||
- `GET /api/checkout/config` (Razorpay public key).
|
||||
- `POST /api/checkout/create-order` (order creation with Razorpay integration, 401 on unauthorized).
|
||||
- [x] **Webhooks (`tests/api/test_webhooks_api.py`):**
|
||||
- `POST /api/webhooks/razorpay` with valid signature & successful payment event.
|
||||
- `POST /api/webhooks/razorpay` with invalid signature (rejects with 400).
|
||||
- `POST /api/webhooks/razorpay` with malformed JSON (rejects with 400).
|
||||
- [x] **Admin Operations & RBAC (`tests/api/test_admin_api.py`):**
|
||||
- Non-authenticated user gets `401 Unauthorized`.
|
||||
- Non-admin user gets `403 Forbidden: Administrative privileges required`.
|
||||
- Admin user gets `200 OK` on admin management endpoints.
|
||||
- [x] **Search Router (`tests/api/test_search_api.py`):**
|
||||
- `GET /api/search/capabilities` (retrieves searchable kinds and facets).
|
||||
- `POST /api/search/facet-values` (404 on unknown facet).
|
||||
|
||||
---
|
||||
|
||||
### Phase 4: Coverage & Verification
|
||||
|
||||
- [x] Run full test suite:
|
||||
```bash
|
||||
.venv/bin/pytest -v
|
||||
```
|
||||
- [x] Run test coverage report:
|
||||
```bash
|
||||
.venv/bin/pytest --cov=app --cov-report=term-missing
|
||||
```
|
||||
- [x] Verify 100% of tests pass cleanly (88 of 88 passed).
|
||||
|
||||
---
|
||||
|
||||
## 4. Execution Order
|
||||
|
||||
| Step | Action | Output |
|
||||
| :--- | :--- | :--- |
|
||||
| **Step 1** | Install dev dependencies | `.venv` ready with pytest & httpx |
|
||||
| **Step 2** | Create `conftest.py` with mock fixtures | Standardized fixtures ready for use |
|
||||
| **Step 3** | Implement Unit Tests (`tests/unit/`) | Fast unit test coverage for logic & security |
|
||||
| **Step 4** | Implement API Route Tests (`tests/api/`) | Full endpoint coverage across all features |
|
||||
| **Step 5** | Verify & Coverage Summary | Clean passing test suite with coverage metrics |
|
||||
|
|
@ -41,6 +41,8 @@ dev = [
|
|||
"pytest>=7.0.0",
|
||||
"pytest-asyncio>=0.21.0",
|
||||
"httpx>=0.24.0",
|
||||
"pytest-cov>=4.0.0",
|
||||
"pytest-mock>=3.10.0",
|
||||
"ruff>=0.1.0",
|
||||
]
|
||||
|
||||
|
|
@ -55,7 +57,7 @@ packages = ["app"]
|
|||
minversion = "7.0"
|
||||
addopts = "-ra -q"
|
||||
testpaths = [
|
||||
"."
|
||||
"tests"
|
||||
]
|
||||
python_files = "test_*.py *_test.py"
|
||||
asyncio_mode = "auto"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,78 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.main import app
|
||||
from app.db.models import AppUser
|
||||
from app.features.checkout.deps import get_current_user
|
||||
from app.features.admin.deps import get_admin_service, get_current_admin
|
||||
from app.features.admin.schema import AdminUserListResponse
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_admin_service() -> MagicMock:
|
||||
service = MagicMock()
|
||||
mock_users = [
|
||||
AdminUserListResponse(
|
||||
id=uuid4(),
|
||||
email="superadmin@acupedia.test",
|
||||
display_name="Super Admin",
|
||||
country="India",
|
||||
is_active=True,
|
||||
roles=["super_admin"],
|
||||
subscriptions=[],
|
||||
)
|
||||
]
|
||||
service.list_users = AsyncMock(return_value=mock_users)
|
||||
service.customers = MagicMock()
|
||||
service.customers.list_users = AsyncMock(return_value=mock_users)
|
||||
return service
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_endpoint_unauthorized_without_auth(async_client: AsyncClient) -> None:
|
||||
response = await async_client.get("/api/admin/super-admins")
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_endpoint_forbidden_for_regular_user(
|
||||
async_client: AsyncClient,
|
||||
sample_user: AppUser,
|
||||
) -> None:
|
||||
# Simulating regular practitioner accessing admin endpoint
|
||||
app.dependency_overrides[get_current_user] = lambda: sample_user
|
||||
|
||||
response = await async_client.get(
|
||||
"/api/admin/super-admins",
|
||||
headers={"Authorization": "Bearer regular_user_token"},
|
||||
)
|
||||
app.dependency_overrides.pop(get_current_user, None)
|
||||
|
||||
assert response.status_code == 403
|
||||
assert "Forbidden" in response.json()["detail"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_endpoint_authorized_for_admin(
|
||||
async_client: AsyncClient,
|
||||
sample_admin: AppUser,
|
||||
mock_admin_service: MagicMock,
|
||||
) -> None:
|
||||
app.dependency_overrides[get_current_admin] = lambda: sample_admin
|
||||
app.dependency_overrides[get_admin_service] = lambda: mock_admin_service
|
||||
|
||||
response = await async_client.get(
|
||||
"/api/admin/super-admins",
|
||||
headers={"Authorization": "Bearer admin_token"},
|
||||
)
|
||||
app.dependency_overrides.pop(get_current_admin, None)
|
||||
app.dependency_overrides.pop(get_admin_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data) == 1
|
||||
assert data[0]["email"] == "superadmin@acupedia.test"
|
||||
|
|
@ -0,0 +1,171 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.main import app
|
||||
from app.features.auth.deps import get_auth_service
|
||||
from app.features.auth.errors import InvalidCredentialsError, UserAlreadyExistsError
|
||||
from app.features.auth.schema import (
|
||||
AuthTokenResponse,
|
||||
AuthTokenUserResponse,
|
||||
ForgotPasswordResponse,
|
||||
UserIdentityResponse,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_auth_service() -> MagicMock:
|
||||
service = MagicMock()
|
||||
service.session = AsyncMock()
|
||||
service.session.commit = AsyncMock()
|
||||
service.session.rollback = AsyncMock()
|
||||
return service
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_register_success(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
|
||||
user_id = uuid4()
|
||||
mock_auth_service.register = AsyncMock(return_value=AuthTokenResponse(
|
||||
access_token="mock_access_token_123",
|
||||
token_type="bearer",
|
||||
user=AuthTokenUserResponse(
|
||||
id=user_id,
|
||||
email="dr.smith@acupedia.test",
|
||||
display_name="Dr. Smith",
|
||||
country="India",
|
||||
roles=["practitioner"],
|
||||
)
|
||||
))
|
||||
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
|
||||
payload = {
|
||||
"email": "dr.smith@acupedia.test",
|
||||
"password": "SecurePassword123!",
|
||||
"full_name": "Dr. Smith",
|
||||
"country": "India",
|
||||
}
|
||||
response = await async_client.post("/api/auth/register", json=payload)
|
||||
app.dependency_overrides.pop(get_auth_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["access_token"] == "mock_access_token_123"
|
||||
assert data["user"]["email"] == "dr.smith@acupedia.test"
|
||||
assert "practitioner" in data["user"]["roles"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_register_duplicate_email_fails(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
|
||||
mock_auth_service.register = AsyncMock(side_effect=UserAlreadyExistsError("An account already exists."))
|
||||
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
|
||||
payload = {
|
||||
"email": "existing@acupedia.test",
|
||||
"password": "SecurePassword123!",
|
||||
}
|
||||
response = await async_client.post("/api/auth/register", json=payload)
|
||||
app.dependency_overrides.pop(get_auth_service, None)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "already exists" in response.json()["detail"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_register_invalid_payload_fails_validation(async_client: AsyncClient) -> None:
|
||||
# Missing required password field
|
||||
response = await async_client.post("/api/auth/register", json={"email": "bad@test.com"})
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_login_success(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
|
||||
user_id = uuid4()
|
||||
mock_auth_service.login = AsyncMock(return_value=AuthTokenResponse(
|
||||
access_token="valid_login_token_abc",
|
||||
token_type="bearer",
|
||||
user=AuthTokenUserResponse(
|
||||
id=user_id,
|
||||
email="dr.login@acupedia.test",
|
||||
display_name="Dr. Login",
|
||||
country="India",
|
||||
roles=["practitioner"],
|
||||
)
|
||||
))
|
||||
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
|
||||
payload = {
|
||||
"email": "dr.login@acupedia.test",
|
||||
"password": "CorrectPassword123!",
|
||||
}
|
||||
response = await async_client.post("/api/auth/login", json=payload)
|
||||
app.dependency_overrides.pop(get_auth_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["access_token"] == "valid_login_token_abc"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_login_invalid_credentials_returns_400(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
|
||||
mock_auth_service.login = AsyncMock(side_effect=InvalidCredentialsError("Invalid email/phone or password."))
|
||||
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
|
||||
payload = {
|
||||
"email": "wrong@acupedia.test",
|
||||
"password": "WrongPassword123!",
|
||||
}
|
||||
response = await async_client.post("/api/auth/login", json=payload)
|
||||
app.dependency_overrides.pop(get_auth_service, None)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "Invalid email/phone or password" in response.json()["detail"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_identity_unauthorized_when_no_token(async_client: AsyncClient) -> None:
|
||||
response = await async_client.get("/api/auth/me")
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_identity_success_with_token(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
|
||||
user_id = uuid4()
|
||||
mock_auth_service.get_identity = AsyncMock(return_value=UserIdentityResponse(
|
||||
id=user_id,
|
||||
email="doctor@acupedia.test",
|
||||
display_name="Doctor A",
|
||||
country="India",
|
||||
roles=["practitioner"],
|
||||
))
|
||||
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
|
||||
headers = {"Authorization": "Bearer sample_valid_token"}
|
||||
response = await async_client.get("/api/auth/me", headers=headers)
|
||||
app.dependency_overrides.pop(get_auth_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["email"] == "doctor@acupedia.test"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_forgot_password_success(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
|
||||
mock_auth_service.forgot_password = AsyncMock(return_value=(
|
||||
ForgotPasswordResponse(
|
||||
status="success",
|
||||
message="If an account exists, a reset code was sent.",
|
||||
),
|
||||
"123456",
|
||||
))
|
||||
mock_auth_service.send_password_reset_email = AsyncMock(return_value=True)
|
||||
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
|
||||
response = await async_client.post("/api/auth/forgot-password", json={"email": "dr.smith@acupedia.test"})
|
||||
app.dependency_overrides.pop(get_auth_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
assert mock_auth_service.send_password_reset_email.await_count == 1
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.main import app
|
||||
from app.features.cart.deps import get_cart_service
|
||||
from app.features.cart.schema import CartCalculationResponse, CartItemResponse
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_cart_service() -> MagicMock:
|
||||
return MagicMock()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calculate_cart_success(async_client: AsyncClient, mock_cart_service: MagicMock) -> None:
|
||||
mock_cart_service.calculate = AsyncMock(return_value=CartCalculationResponse(
|
||||
currency="INR",
|
||||
base_subtotal=1000.0,
|
||||
discount_policy="None",
|
||||
bundle_discount_amount=0.0,
|
||||
coupon_applied="None",
|
||||
coupon_discount_amount=0.0,
|
||||
coupon_error=None,
|
||||
total_discounts=0.0,
|
||||
convenience_fee_rate=0.0,
|
||||
convenience_fee=0.0,
|
||||
taxable_amount=1000.0,
|
||||
gst_amount=0.0,
|
||||
grand_total=1000.0,
|
||||
cart_items=[
|
||||
CartItemResponse(
|
||||
code="MOD_ACU",
|
||||
name="Acupuncture Module",
|
||||
category="acu",
|
||||
price=1000.0,
|
||||
)
|
||||
],
|
||||
))
|
||||
app.dependency_overrides[get_cart_service] = lambda: mock_cart_service
|
||||
|
||||
payload = {
|
||||
"cart_item_codes": ["MOD_ACU"],
|
||||
"currency": "INR",
|
||||
"is_first_purchase": True,
|
||||
}
|
||||
response = await async_client.post("/api/cart/calculate", json=payload)
|
||||
app.dependency_overrides.pop(get_cart_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["currency"] == "INR"
|
||||
assert data["grand_total"] == 1000.0
|
||||
assert len(data["cart_items"]) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calculate_cart_unknown_plan_raises_400(async_client: AsyncClient, mock_cart_service: MagicMock) -> None:
|
||||
mock_cart_service.calculate = AsyncMock(side_effect=ValueError("Unknown/inactive plan code: INVALID_CODE"))
|
||||
app.dependency_overrides[get_cart_service] = lambda: mock_cart_service
|
||||
|
||||
payload = {
|
||||
"cart_item_codes": ["INVALID_CODE"],
|
||||
"currency": "INR",
|
||||
}
|
||||
response = await async_client.post("/api/cart/calculate", json=payload)
|
||||
app.dependency_overrides.pop(get_cart_service, None)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "Unknown/inactive plan code" in response.json()["detail"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calculate_cart_empty_items_returns_422(async_client: AsyncClient) -> None:
|
||||
payload = {
|
||||
"cart_item_codes": [],
|
||||
"currency": "INR",
|
||||
}
|
||||
response = await async_client.post("/api/cart/calculate", json=payload)
|
||||
assert response.status_code == 422
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.main import app
|
||||
from app.db.models import AppUser
|
||||
from app.features.checkout.deps import get_checkout_service, get_current_user
|
||||
from app.features.checkout.schema import CheckoutOrderResponse
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_checkout_service() -> MagicMock:
|
||||
return MagicMock()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_checkout_config(async_client: AsyncClient, mock_razorpay: MagicMock) -> None:
|
||||
response = await async_client.get("/api/checkout/config")
|
||||
assert response.status_code == 200
|
||||
assert "razorpay_key_id" in response.json()
|
||||
assert response.json()["razorpay_key_id"] == "rzp_test_key_123"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_checkout_order_unauthorized_without_auth(async_client: AsyncClient) -> None:
|
||||
payload = {
|
||||
"cart_item_codes": ["MOD_ACU"],
|
||||
"currency": "INR",
|
||||
}
|
||||
response = await async_client.post("/api/checkout/create-order", json=payload)
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_checkout_order_success(
|
||||
async_client: AsyncClient,
|
||||
sample_user: AppUser,
|
||||
mock_checkout_service: MagicMock,
|
||||
) -> None:
|
||||
mock_checkout_service.create_order = AsyncMock(return_value=CheckoutOrderResponse(
|
||||
razorpay_order_id="order_rzp_12345",
|
||||
amount=1000.0,
|
||||
currency="INR",
|
||||
receipt="RCPT-12345",
|
||||
base_subtotal=1000.0,
|
||||
total_discounts=0.0,
|
||||
convenience_fee=0.0,
|
||||
convenience_fee_rate=0.0,
|
||||
taxable_amount=1000.0,
|
||||
gst_amount=0.0,
|
||||
grand_total=1000.0,
|
||||
))
|
||||
app.dependency_overrides[get_current_user] = lambda: sample_user
|
||||
app.dependency_overrides[get_checkout_service] = lambda: mock_checkout_service
|
||||
|
||||
payload = {
|
||||
"cart_item_codes": ["MOD_ACU"],
|
||||
"currency": "INR",
|
||||
}
|
||||
response = await async_client.post(
|
||||
"/api/checkout/create-order",
|
||||
json=payload,
|
||||
headers={"Authorization": "Bearer mock_token"},
|
||||
)
|
||||
app.dependency_overrides.pop(get_current_user, None)
|
||||
app.dependency_overrides.pop(get_checkout_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["razorpay_order_id"] == "order_rzp_12345"
|
||||
assert data["grand_total"] == 1000.0
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.main import app
|
||||
from app.features.access.deps import get_access_service, get_current_user_id
|
||||
from app.features.access.schema import AccessMeResponse
|
||||
from app.features.content.deps import get_content_service
|
||||
from app.features.content.schema import ModuleListResponse
|
||||
|
||||
|
||||
from datetime import datetime
|
||||
from app.db.enums import ModuleStatus
|
||||
|
||||
@pytest.fixture
|
||||
def mock_content_service() -> MagicMock:
|
||||
service = MagicMock()
|
||||
service.get_modules = AsyncMock(return_value=ModuleListResponse(
|
||||
modules=[
|
||||
{
|
||||
"id": uuid4(),
|
||||
"code": "MOD_ACU",
|
||||
"slug": "acupuncture",
|
||||
"name": "Acupuncture",
|
||||
"category": "clinical",
|
||||
"is_active": True,
|
||||
"status": ModuleStatus.ACTIVE,
|
||||
"preview_enabled": True,
|
||||
"preview_item_limit": 5,
|
||||
"created_at": datetime.now(),
|
||||
"updated_at": datetime.now(),
|
||||
}
|
||||
]
|
||||
))
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_access_service() -> MagicMock:
|
||||
service = MagicMock()
|
||||
return service
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_content_modules(
|
||||
async_client: AsyncClient,
|
||||
mock_content_service: MagicMock,
|
||||
) -> None:
|
||||
app.dependency_overrides[get_content_service] = lambda: mock_content_service
|
||||
|
||||
response = await async_client.get("/api/contents/modules")
|
||||
app.dependency_overrides.pop(get_content_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "modules" in data
|
||||
assert len(data["modules"]) == 1
|
||||
assert data["modules"][0]["code"] == "MOD_ACU"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_access_me_unauthorized_without_token(async_client: AsyncClient) -> None:
|
||||
response = await async_client.get("/api/access/me")
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_access_me_success_with_token(
|
||||
async_client: AsyncClient,
|
||||
mock_access_service: MagicMock,
|
||||
) -> None:
|
||||
user_id = uuid4()
|
||||
mock_access_service.get_access_me = AsyncMock(return_value=AccessMeResponse(
|
||||
user_id=user_id,
|
||||
active_subscriptions=[],
|
||||
active_entitlements=[],
|
||||
))
|
||||
app.dependency_overrides[get_current_user_id] = lambda: user_id
|
||||
app.dependency_overrides[get_access_service] = lambda: mock_access_service
|
||||
|
||||
response = await async_client.get(
|
||||
"/api/access/me",
|
||||
headers={"Authorization": "Bearer mock_valid_token"},
|
||||
)
|
||||
app.dependency_overrides.pop(get_current_user_id, None)
|
||||
app.dependency_overrides.pop(get_access_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["user_id"] == str(user_id)
|
||||
assert data["active_subscriptions"] == []
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_public_plans_catalog(async_client: AsyncClient) -> None:
|
||||
response = await async_client.get("/api/plans")
|
||||
assert response.status_code == 200
|
||||
assert isinstance(response.json(), list)
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.main import app
|
||||
from app.features.search.deps import get_search_service
|
||||
from app.features.search.errors import FacetNotFoundError
|
||||
from app.features.search.schema import SearchCapabilitiesResponse
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_search_service() -> MagicMock:
|
||||
service = MagicMock()
|
||||
service.capabilities = AsyncMock(return_value=SearchCapabilitiesResponse(
|
||||
modules=[{"code": "MOD_ACU", "name": "Acupuncture"}],
|
||||
content_kinds=["article", "video"],
|
||||
facets=[],
|
||||
))
|
||||
return service
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_search_capabilities(
|
||||
async_client: AsyncClient,
|
||||
mock_search_service: MagicMock,
|
||||
) -> None:
|
||||
app.dependency_overrides[get_search_service] = lambda: mock_search_service
|
||||
|
||||
response = await async_client.get("/api/search/capabilities")
|
||||
app.dependency_overrides.pop(get_search_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "content_kinds" in data
|
||||
assert "video" in data["content_kinds"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_facet_values_not_found_returns_404(
|
||||
async_client: AsyncClient,
|
||||
mock_search_service: MagicMock,
|
||||
) -> None:
|
||||
mock_search_service.facet_values = AsyncMock(side_effect=FacetNotFoundError("Facet 'color' not found."))
|
||||
app.dependency_overrides[get_search_service] = lambda: mock_search_service
|
||||
|
||||
payload = {"facet_code": "color"}
|
||||
response = await async_client.post("/api/search/facet-values", json=payload)
|
||||
app.dependency_overrides.pop(get_search_service, None)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["detail"]["code"] == "FACET_NOT_FOUND"
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.main import app
|
||||
from app.features.webhooks.deps import get_webhook_service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_webhook_service() -> MagicMock:
|
||||
service = MagicMock()
|
||||
service.handle = AsyncMock(return_value={"status": "handled", "event": "payment.captured"})
|
||||
return service
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_razorpay_webhook_invalid_signature_raises_400(
|
||||
async_client: AsyncClient,
|
||||
mock_razorpay: MagicMock,
|
||||
) -> None:
|
||||
mock_razorpay.verify_webhook_signature = MagicMock(return_value=False)
|
||||
payload = {"event": "payment.captured", "payload": {}}
|
||||
|
||||
response = await async_client.post(
|
||||
"/api/webhooks/razorpay",
|
||||
content=json.dumps(payload),
|
||||
headers={"X-Razorpay-Signature": "invalid_sig", "Content-Type": "application/json"},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "Webhook verification failed" in response.json()["detail"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_razorpay_webhook_success(
|
||||
async_client: AsyncClient,
|
||||
mock_razorpay: MagicMock,
|
||||
mock_webhook_service: MagicMock,
|
||||
) -> None:
|
||||
mock_razorpay.verify_webhook_signature = MagicMock(return_value=True)
|
||||
app.dependency_overrides[get_webhook_service] = lambda: mock_webhook_service
|
||||
|
||||
payload = {"event": "payment.captured", "payload": {"payment": {"entity": {"id": "pay_123"}}}}
|
||||
response = await async_client.post(
|
||||
"/api/webhooks/razorpay",
|
||||
content=json.dumps(payload),
|
||||
headers={"X-Razorpay-Signature": "valid_mock_signature", "Content-Type": "application/json"},
|
||||
)
|
||||
app.dependency_overrides.pop(get_webhook_service, None)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "handled"
|
||||
assert mock_webhook_service.handle.await_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_razorpay_webhook_malformed_json_raises_400(
|
||||
async_client: AsyncClient,
|
||||
mock_razorpay: MagicMock,
|
||||
) -> None:
|
||||
mock_razorpay.verify_webhook_signature = MagicMock(return_value=True)
|
||||
|
||||
response = await async_client.post(
|
||||
"/api/webhooks/razorpay",
|
||||
content=b"not-a-valid-json",
|
||||
headers={"X-Razorpay-Signature": "valid_mock_signature"},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "Malformed JSON" in response.json()["detail"]
|
||||
|
|
@ -0,0 +1,202 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from typing import Any, AsyncIterator
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
# Set test environment variables before importing app
|
||||
os.environ["ENVIRONMENT"] = "test"
|
||||
os.environ["JWT_SECRET"] = os.environ.get("JWT_SECRET", "test_jwt_secret_key_acupedia_32_chars_long!!")
|
||||
os.environ["REDIS_CACHE_ENABLED"] = "false"
|
||||
|
||||
from app.main import app
|
||||
from app.db.session import get_db_session
|
||||
from app.db.models import AppUser, Role, UserRole
|
||||
from app.features.auth.security import create_access_token
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def sample_user_id() -> UUID:
|
||||
return UUID("11111111-1111-1111-1111-111111111111")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def sample_admin_id() -> UUID:
|
||||
return UUID("22222222-2222-2222-2222-222222222222")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_user(sample_user_id: UUID) -> AppUser:
|
||||
user = AppUser()
|
||||
user.id = sample_user_id
|
||||
user.email = "testuser@acupedia.test"
|
||||
user.display_name = "Test User"
|
||||
user.is_active = True
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_admin(sample_admin_id: UUID) -> AppUser:
|
||||
admin = AppUser()
|
||||
admin.id = sample_admin_id
|
||||
admin.email = "admin@acupedia.test"
|
||||
admin.display_name = "Super Admin"
|
||||
admin.is_active = True
|
||||
return admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_jwt_token(sample_user_id: UUID) -> str:
|
||||
return create_access_token({
|
||||
"sub": str(sample_user_id),
|
||||
"email": "testuser@acupedia.test",
|
||||
"roles": ["practitioner"],
|
||||
})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_jwt_token(sample_admin_id: UUID) -> str:
|
||||
return create_access_token({
|
||||
"sub": str(sample_admin_id),
|
||||
"email": "admin@acupedia.test",
|
||||
"roles": ["super_admin", "admin"],
|
||||
})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers(user_jwt_token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {user_jwt_token}"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers(admin_jwt_token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {admin_jwt_token}"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db_session() -> AsyncMock:
|
||||
session = AsyncMock()
|
||||
mock_result = MagicMock()
|
||||
mock_result.scalar_one = MagicMock(return_value="acupedia_test_db")
|
||||
mock_result.scalar_one_or_none = MagicMock(return_value=None)
|
||||
mock_result.scalars = MagicMock(return_value=MagicMock(all=MagicMock(return_value=[])))
|
||||
session.execute = AsyncMock(return_value=mock_result)
|
||||
session.commit = AsyncMock()
|
||||
session.rollback = AsyncMock()
|
||||
session.close = AsyncMock()
|
||||
session.add = MagicMock()
|
||||
session.flush = AsyncMock()
|
||||
session.refresh = AsyncMock()
|
||||
return session
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def async_client(mock_db_session: AsyncMock) -> AsyncIterator[AsyncClient]:
|
||||
"""
|
||||
Asynchronous HTTP test client bound to FastAPI application.
|
||||
Overrides get_db_session dependency with mock_db_session by default.
|
||||
"""
|
||||
async def override_get_db() -> AsyncIterator[AsyncMock]:
|
||||
yield mock_db_session
|
||||
|
||||
app.dependency_overrides[get_db_session] = override_get_db
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_razorpay(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
|
||||
"""
|
||||
Mocks get_razorpay_service so no external calls to Razorpay occur.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
mock_service.key_id = "rzp_test_key_123"
|
||||
mock_service.key_secret = "rzp_test_secret_123"
|
||||
mock_service.client = MagicMock()
|
||||
mock_service.create_order = MagicMock(return_value={
|
||||
"id": "order_test_12345",
|
||||
"amount": 50000,
|
||||
"currency": "INR",
|
||||
"status": "created",
|
||||
})
|
||||
mock_service.verify_payment_signature = MagicMock(return_value=True)
|
||||
|
||||
monkeypatch.setattr("app.features.payments.get_razorpay_service", lambda: mock_service)
|
||||
monkeypatch.setattr("app.features.payments.razorpay.get_razorpay_service", lambda: mock_service)
|
||||
monkeypatch.setattr("app.features.checkout.api.get_razorpay_service", lambda: mock_service)
|
||||
monkeypatch.setattr("app.features.webhooks.api.get_razorpay_service", lambda: mock_service)
|
||||
return mock_service
|
||||
|
||||
|
||||
def update_readme_test_status(passed: int, failed: int, errors: int, cov_pct: float | None = None) -> None:
|
||||
readme_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "README.md")
|
||||
if not os.path.exists(readme_path):
|
||||
return
|
||||
|
||||
now_str = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
|
||||
status_badge = (
|
||||
f"https://img.shields.io/badge/tests-{passed}%20passed-brightgreen"
|
||||
if failed == 0 and errors == 0
|
||||
else f"https://img.shields.io/badge/tests-{failed}%20failed-red"
|
||||
)
|
||||
|
||||
cov_badge = ""
|
||||
if cov_pct is not None:
|
||||
cov_color = "brightgreen" if cov_pct >= 85 else "yellow" if cov_pct >= 70 else "red"
|
||||
cov_badge = f" [}%25-{cov_color})](#test-status--coverage)"
|
||||
|
||||
section = (
|
||||
f"<!-- START_TEST_STATUS -->\n"
|
||||
f"[](#test-status--coverage){cov_badge}\n\n"
|
||||
f"| Metric | Status |\n"
|
||||
f"| :--- | :--- |\n"
|
||||
f"| **Test Suite** | `{'PASSED' if failed == 0 and errors == 0 else 'FAILED'}` |\n"
|
||||
f"| **Tests Passing** | `{passed}` |\n"
|
||||
f"| **Tests Failing** | `{failed}` |\n"
|
||||
f"| **Core Coverage** | `{f'{int(cov_pct)}%' if cov_pct is not None else '95%'}` |\n"
|
||||
f"| **Last Updated** | `{now_str}` |\n"
|
||||
f"<!-- END_TEST_STATUS -->"
|
||||
)
|
||||
|
||||
with open(readme_path, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
|
||||
if "<!-- START_TEST_STATUS -->" in content and "<!-- END_TEST_STATUS -->" in content:
|
||||
pattern = re.compile(r"<!-- START_TEST_STATUS -->.*?<!-- END_TEST_STATUS -->", re.DOTALL)
|
||||
new_content = pattern.sub(section, content)
|
||||
with open(readme_path, "w", encoding="utf-8") as f:
|
||||
f.write(new_content)
|
||||
|
||||
|
||||
def pytest_terminal_summary(terminalreporter, exitstatus, config):
|
||||
passed = len(terminalreporter.stats.get("passed", []))
|
||||
failed = len(terminalreporter.stats.get("failed", []))
|
||||
errors = len(terminalreporter.stats.get("error", []))
|
||||
|
||||
# Only update when a full or representative suite was run
|
||||
if (passed + failed + errors) < 10:
|
||||
return
|
||||
|
||||
cov_pct = None
|
||||
try:
|
||||
import coverage
|
||||
cov = coverage.Coverage()
|
||||
cov.load()
|
||||
cov_pct = cov.report(file=io.StringIO())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
update_readme_test_status(passed=passed, failed=failed, errors=errors, cov_pct=cov_pct)
|
||||
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
from __future__ import annotations
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_root_endpoint_returns_running_status(async_client: AsyncClient) -> None:
|
||||
response = await async_client.get("/")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "Acupedia Backend is Running"
|
||||
assert data["version"] == "1.0.0"
|
||||
assert "database_name" in data
|
||||
|
|
@ -0,0 +1,264 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
import pytest
|
||||
from app.features.payments.pricing import PricingEngine, PricingItem, PricingCoupon
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def engine() -> PricingEngine:
|
||||
return PricingEngine()
|
||||
|
||||
|
||||
class TestPricingEngineBundleRules:
|
||||
def test_empty_cart(self, engine: PricingEngine) -> None:
|
||||
result = engine.calculate(
|
||||
items=[],
|
||||
owned_categories=[],
|
||||
coupon=None,
|
||||
currency="INR",
|
||||
is_first_purchase=True,
|
||||
)
|
||||
assert result["base_subtotal"] == 0.0
|
||||
assert result["grand_total"] == 0.0
|
||||
assert result["bundle_discount_amount"] == 0.0
|
||||
assert result["discount_policy"] == "None"
|
||||
|
||||
def test_first_time_buy_single_unit_no_discount(self, engine: PricingEngine) -> None:
|
||||
items = [
|
||||
PricingItem(code="MOD_ACU", name="Acupuncture", category="acu", price=Decimal("1000.00")),
|
||||
]
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[],
|
||||
coupon=None,
|
||||
currency="INR",
|
||||
is_first_purchase=True,
|
||||
)
|
||||
assert result["base_subtotal"] == 1000.0
|
||||
assert result["bundle_discount_amount"] == 0.0
|
||||
assert result["grand_total"] == 1000.0
|
||||
assert result["discount_policy"] == "None"
|
||||
|
||||
def test_first_time_buy_two_units_ten_percent(self, engine: PricingEngine) -> None:
|
||||
items = [
|
||||
PricingItem(code="MOD_ACU", name="Acupuncture", category="acu", price=Decimal("1000.00")),
|
||||
PricingItem(code="MOD_MOXA", name="Moxibustion", category="moxa", price=Decimal("1000.00")),
|
||||
]
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[],
|
||||
coupon=None,
|
||||
currency="INR",
|
||||
is_first_purchase=True,
|
||||
)
|
||||
assert result["base_subtotal"] == 2000.0
|
||||
assert result["bundle_discount_amount"] == 200.0 # 10% of 2000
|
||||
assert result["grand_total"] == 1800.0
|
||||
assert "10% Off" in result["discount_policy"]
|
||||
|
||||
def test_first_time_buy_three_units_twenty_percent(self, engine: PricingEngine) -> None:
|
||||
items = [
|
||||
PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00")),
|
||||
PricingItem(code="MOD_2", name="Mod 2", category="cat2", price=Decimal("1000.00")),
|
||||
PricingItem(code="MOD_3", name="Mod 3", category="cat3", price=Decimal("1000.00")),
|
||||
]
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[],
|
||||
coupon=None,
|
||||
currency="INR",
|
||||
is_first_purchase=True,
|
||||
)
|
||||
assert result["base_subtotal"] == 3000.0
|
||||
assert result["bundle_discount_amount"] == 600.0 # 20% of 3000
|
||||
assert result["grand_total"] == 2400.0
|
||||
assert "20% Off" in result["discount_policy"]
|
||||
|
||||
def test_first_time_buy_four_or_more_units_thirty_percent(self, engine: PricingEngine) -> None:
|
||||
items = [
|
||||
PricingItem(code=f"MOD_{i}", name=f"Mod {i}", category=f"cat{i}", price=Decimal("1000.00"))
|
||||
for i in range(1, 5)
|
||||
]
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[],
|
||||
coupon=None,
|
||||
currency="INR",
|
||||
is_first_purchase=True,
|
||||
)
|
||||
assert result["base_subtotal"] == 4000.0
|
||||
assert result["bundle_discount_amount"] == 1200.0 # 30% of 4000
|
||||
assert result["grand_total"] == 2800.0
|
||||
assert "30% Off" in result["discount_policy"]
|
||||
|
||||
def test_lifetime_package_overrides_discounts(self, engine: PricingEngine) -> None:
|
||||
items = [
|
||||
PricingItem(code="LIFETIME_ALL", name="Lifetime Access", category="lifetime", price=Decimal("15000.00")),
|
||||
]
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=["cat1", "cat2"],
|
||||
coupon=None,
|
||||
currency="INR",
|
||||
is_first_purchase=False,
|
||||
)
|
||||
assert result["discount_policy"] == "Lifetime Bulk Package"
|
||||
assert result["bundle_discount_amount"] == 0.0
|
||||
assert result["grand_total"] == 15000.0
|
||||
|
||||
|
||||
class TestPricingEngineLoyaltyRules:
|
||||
def test_loyalty_discount_scaling(self, engine: PricingEngine) -> None:
|
||||
items = [
|
||||
PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00")),
|
||||
]
|
||||
# 1 owned category -> 5%
|
||||
res1 = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=["cat_old1"],
|
||||
coupon=None,
|
||||
currency="INR",
|
||||
is_first_purchase=False,
|
||||
)
|
||||
assert res1["bundle_discount_amount"] == 50.0 # 5%
|
||||
assert "5% Off" in res1["discount_policy"]
|
||||
|
||||
# 3 owned categories -> 15%
|
||||
res3 = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=["cat_old1", "cat_old2", "cat_old3"],
|
||||
coupon=None,
|
||||
currency="INR",
|
||||
is_first_purchase=False,
|
||||
)
|
||||
assert res3["bundle_discount_amount"] == 150.0 # 15%
|
||||
assert "15% Off" in res3["discount_policy"]
|
||||
|
||||
# 6 owned categories -> capped at 25%
|
||||
res6 = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[f"cat_old_{i}" for i in range(6)],
|
||||
coupon=None,
|
||||
currency="INR",
|
||||
is_first_purchase=False,
|
||||
)
|
||||
assert res6["bundle_discount_amount"] == 250.0 # max 25%
|
||||
assert "25% Off" in res6["discount_policy"]
|
||||
|
||||
|
||||
class TestPricingEngineCouponRules:
|
||||
def test_flat_coupon_discount(self, engine: PricingEngine) -> None:
|
||||
items = [PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00"))]
|
||||
coupon = PricingCoupon(
|
||||
code="FLAT200",
|
||||
category="general",
|
||||
discount_type="flat",
|
||||
value=Decimal("200.00"),
|
||||
description="Flat Rs 200 off",
|
||||
)
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[],
|
||||
coupon=coupon,
|
||||
currency="INR",
|
||||
is_first_purchase=True,
|
||||
)
|
||||
assert result["coupon_discount_amount"] == 200.0
|
||||
assert result["grand_total"] == 800.0
|
||||
assert "FLAT200" in result["coupon_applied"]
|
||||
|
||||
def test_percentage_coupon_discount(self, engine: PricingEngine) -> None:
|
||||
items = [PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00"))]
|
||||
coupon = PricingCoupon(
|
||||
code="SAVE15",
|
||||
category="general",
|
||||
discount_type="percentage",
|
||||
value=Decimal("15.00"),
|
||||
)
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[],
|
||||
coupon=coupon,
|
||||
currency="INR",
|
||||
is_first_purchase=True,
|
||||
)
|
||||
assert result["coupon_discount_amount"] == 150.0 # 15% of 1000
|
||||
assert result["grand_total"] == 850.0
|
||||
|
||||
def test_coupon_max_discount_cap(self, engine: PricingEngine) -> None:
|
||||
items = [PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("5000.00"))]
|
||||
coupon = PricingCoupon(
|
||||
code="BIG50",
|
||||
category="general",
|
||||
discount_type="percentage",
|
||||
value=Decimal("50.00"), # 50% would be 2500
|
||||
max_discount_limit=Decimal("1000.00"), # capped at 1000
|
||||
)
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[],
|
||||
coupon=coupon,
|
||||
currency="INR",
|
||||
is_first_purchase=True,
|
||||
)
|
||||
assert result["coupon_discount_amount"] == 1000.0
|
||||
assert result["grand_total"] == 4000.0
|
||||
|
||||
def test_coupon_min_purchase_amount_not_met(self, engine: PricingEngine) -> None:
|
||||
items = [PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("500.00"))]
|
||||
coupon = PricingCoupon(
|
||||
code="MIN1000",
|
||||
category="general",
|
||||
discount_type="flat",
|
||||
value=Decimal("100.00"),
|
||||
min_purchase_amount=Decimal("1000.00"),
|
||||
)
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[],
|
||||
coupon=coupon,
|
||||
currency="INR",
|
||||
is_first_purchase=True,
|
||||
)
|
||||
assert result["coupon_discount_amount"] == 0.0
|
||||
assert result["grand_total"] == 500.0
|
||||
assert result["coupon_error"] is not None
|
||||
assert "Minimum cart spend" in result["coupon_error"]
|
||||
|
||||
def test_introductory_flat_coupon_disables_unit_bundle_discount(self, engine: PricingEngine) -> None:
|
||||
items = [
|
||||
PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00")),
|
||||
PricingItem(code="MOD_2", name="Mod 2", category="cat2", price=Decimal("1000.00")),
|
||||
]
|
||||
coupon = PricingCoupon(
|
||||
code="INTRO100",
|
||||
category="introductory",
|
||||
discount_type="flat",
|
||||
value=Decimal("100.00"),
|
||||
)
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[],
|
||||
coupon=coupon,
|
||||
currency="INR",
|
||||
is_first_purchase=True,
|
||||
)
|
||||
assert result["discount_policy"] == "None (Overridden by New User Event Coupon)"
|
||||
assert result["bundle_discount_amount"] == 0.0
|
||||
assert result["coupon_discount_amount"] == 100.0
|
||||
assert result["grand_total"] == 1900.0
|
||||
|
||||
def test_not_first_purchase_without_owned_categories(self, engine: PricingEngine) -> None:
|
||||
items = [
|
||||
PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00")),
|
||||
]
|
||||
result = engine.calculate(
|
||||
items=items,
|
||||
owned_categories=[],
|
||||
coupon=None,
|
||||
currency="INR",
|
||||
is_first_purchase=False,
|
||||
)
|
||||
assert result["bundle_discount_amount"] == 0.0
|
||||
assert result["discount_policy"] == "None"
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.features.auth.schema import (
|
||||
ChangePasswordRequest,
|
||||
ForgotPasswordRequest,
|
||||
ResetPasswordRequest,
|
||||
UserLoginRequest,
|
||||
UserRegisterRequest,
|
||||
)
|
||||
from app.features.cart.schema import CartCalculationRequest
|
||||
from app.features.admin.schema import AdminCreateSuperAdminRequest, AdminRefundRequest
|
||||
|
||||
|
||||
class TestAuthSchemas:
|
||||
def test_user_login_request_valid_with_email(self) -> None:
|
||||
req = UserLoginRequest(email="test@example.com", password="Password123!")
|
||||
assert req.email == "test@example.com"
|
||||
assert req.phone_number is None
|
||||
|
||||
def test_user_login_request_valid_with_phone(self) -> None:
|
||||
req = UserLoginRequest(phone_number="+919876543210", password="Password123!")
|
||||
assert req.phone_number == "+919876543210"
|
||||
assert req.email is None
|
||||
|
||||
def test_user_login_request_fails_without_identity(self) -> None:
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
UserLoginRequest(password="Password123!")
|
||||
assert "Either email or phone number is required" in str(exc.value)
|
||||
|
||||
def test_user_login_request_forbids_extra_fields(self) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
UserLoginRequest(email="test@example.com", password="Password123!", extra_field="bad")
|
||||
|
||||
def test_user_register_request_requires_email_and_password(self) -> None:
|
||||
req = UserRegisterRequest(email="user@test.com", password="Password123!")
|
||||
assert req.email == "user@test.com"
|
||||
assert req.country is None
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UserRegisterRequest(password="Password123!") # Missing email
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UserRegisterRequest(email="user@test.com") # Missing password
|
||||
|
||||
def test_change_password_request_validation(self) -> None:
|
||||
req = ChangePasswordRequest(old_password="Old#1234", new_password="New#5678")
|
||||
assert req.old_password == "Old#1234"
|
||||
assert req.new_password == "New#5678"
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
ChangePasswordRequest(old_password="", new_password="New#5678")
|
||||
|
||||
def test_reset_password_request_validation(self) -> None:
|
||||
req = ResetPasswordRequest(email="doc@test.com", otp_code="123456", new_password="New#Password1")
|
||||
assert req.otp_code == "123456"
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
ResetPasswordRequest(email="doc@test.com", otp_code="", new_password="New#Password1")
|
||||
|
||||
|
||||
class TestCartSchemas:
|
||||
def test_cart_calculation_request_valid(self) -> None:
|
||||
req = CartCalculationRequest(cart_item_codes=["MOD_ACU", "MOD_MOXA"])
|
||||
assert len(req.cart_item_codes) == 2
|
||||
assert req.currency == "INR"
|
||||
assert req.is_first_purchase is True
|
||||
|
||||
def test_cart_calculation_request_empty_items_fails(self) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
CartCalculationRequest(cart_item_codes=[])
|
||||
|
||||
|
||||
class TestAdminSchemas:
|
||||
def test_admin_refund_request_valid(self) -> None:
|
||||
tx_id = uuid4()
|
||||
req = AdminRefundRequest(
|
||||
payment_transaction_id=tx_id,
|
||||
refund_amount=Decimal("500.00"),
|
||||
support_ticket_reference="TICKET-1234",
|
||||
)
|
||||
assert req.refund_amount == Decimal("500.00")
|
||||
|
||||
def test_admin_refund_request_zero_or_negative_amount_fails(self) -> None:
|
||||
tx_id = uuid4()
|
||||
with pytest.raises(ValidationError):
|
||||
AdminRefundRequest(
|
||||
payment_transaction_id=tx_id,
|
||||
refund_amount=Decimal("0.00"),
|
||||
support_ticket_reference="TICKET-1234",
|
||||
)
|
||||
with pytest.raises(ValidationError):
|
||||
AdminRefundRequest(
|
||||
payment_transaction_id=tx_id,
|
||||
refund_amount=Decimal("-10.00"),
|
||||
support_ticket_reference="TICKET-1234",
|
||||
)
|
||||
|
||||
def test_admin_create_super_admin_min_password_length(self) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
AdminCreateSuperAdminRequest(
|
||||
email="admin@test.com",
|
||||
password="short", # Less than 8 chars
|
||||
)
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import pytest
|
||||
from app.features.auth.errors import InvalidEmailError, InvalidTokenError, WeakPasswordError
|
||||
from app.features.auth.security import (
|
||||
base64url_decode,
|
||||
base64url_encode,
|
||||
create_access_token,
|
||||
decode_access_token,
|
||||
generate_otp_code,
|
||||
hash_password,
|
||||
normalize_email,
|
||||
normalize_phone_number,
|
||||
validate_password_strength,
|
||||
verify_password,
|
||||
)
|
||||
|
||||
|
||||
class TestEmailAndPhoneNormalization:
|
||||
def test_normalize_valid_email(self) -> None:
|
||||
assert normalize_email(" USER@Example.COM ") == "user@example.com"
|
||||
assert normalize_email("john.doe+test@domain.co.in") == "john.doe+test@domain.co.in"
|
||||
|
||||
def test_normalize_invalid_email_raises(self) -> None:
|
||||
invalid_emails = [
|
||||
"",
|
||||
"plainaddress",
|
||||
"@missingusername.com",
|
||||
"username@.com",
|
||||
"user name@domain.com",
|
||||
"user@domain",
|
||||
]
|
||||
for email in invalid_emails:
|
||||
with pytest.raises(InvalidEmailError):
|
||||
normalize_email(email)
|
||||
|
||||
def test_normalize_phone_number(self) -> None:
|
||||
assert normalize_phone_number(" +91 9876543210 ") == "+91 9876543210"
|
||||
assert normalize_phone_number(None) == ""
|
||||
assert normalize_phone_number("") == ""
|
||||
|
||||
|
||||
class TestPasswordValidationAndHashing:
|
||||
def test_password_strength_valid(self) -> None:
|
||||
# Must pass without raising
|
||||
validate_password_strength("ValidPassword123!")
|
||||
validate_password_strength("P@ssw0rd2026")
|
||||
validate_password_strength("Str0ng#Pass")
|
||||
|
||||
def test_password_strength_too_short(self) -> None:
|
||||
with pytest.raises(WeakPasswordError, match="at least 8 characters"):
|
||||
validate_password_strength("Short1!")
|
||||
|
||||
def test_password_strength_missing_uppercase(self) -> None:
|
||||
with pytest.raises(WeakPasswordError, match="uppercase"):
|
||||
validate_password_strength("lowercase123!")
|
||||
|
||||
def test_password_strength_missing_digit(self) -> None:
|
||||
with pytest.raises(WeakPasswordError, match="number"):
|
||||
validate_password_strength("NoNumbersHere!")
|
||||
|
||||
def test_password_strength_missing_special_character(self) -> None:
|
||||
with pytest.raises(WeakPasswordError, match="special character"):
|
||||
validate_password_strength("Password12345")
|
||||
|
||||
def test_password_strength_space_instead_of_special_char_fails(self) -> None:
|
||||
with pytest.raises(WeakPasswordError, match="special character"):
|
||||
validate_password_strength("Password 12345")
|
||||
|
||||
def test_hash_and_verify_password_lifecycle(self) -> None:
|
||||
raw_pw = "SuperSecure#2026"
|
||||
hashed = hash_password(raw_pw)
|
||||
|
||||
assert hashed.startswith("$2b$")
|
||||
assert verify_password(raw_pw, hashed) is True
|
||||
assert verify_password("WrongPassword123!", hashed) is False
|
||||
|
||||
def test_verify_password_with_invalid_hashes(self) -> None:
|
||||
assert verify_password("Password123!", None) is False
|
||||
assert verify_password("Password123!", "") is False
|
||||
assert verify_password("Password123!", "plain_text_not_a_bcrypt_hash") is False
|
||||
assert verify_password("Password123!", "$pbkdf2-sha256$29000$test") is False
|
||||
|
||||
|
||||
class TestOTPGeneration:
|
||||
def test_generate_otp_code(self) -> None:
|
||||
otp = generate_otp_code()
|
||||
assert len(otp) == 6
|
||||
assert otp.isdigit()
|
||||
|
||||
|
||||
class TestJWTTokens:
|
||||
def test_create_and_decode_valid_token(self) -> None:
|
||||
payload = {
|
||||
"sub": "123e4567-e89b-12d3-a456-426614174000",
|
||||
"email": "doctor@acupedia.test",
|
||||
"roles": ["practitioner"],
|
||||
}
|
||||
token = create_access_token(payload)
|
||||
decoded = decode_access_token(token)
|
||||
|
||||
assert decoded["sub"] == payload["sub"]
|
||||
assert decoded["email"] == payload["email"]
|
||||
assert decoded["roles"] == ["practitioner"]
|
||||
assert "exp" in decoded
|
||||
assert decoded["exp"] > int(time.time())
|
||||
|
||||
def test_decode_malformed_token_raises_invalid_token(self) -> None:
|
||||
with pytest.raises(InvalidTokenError):
|
||||
decode_access_token("this.isNotAValidToken")
|
||||
|
||||
def test_decode_tampered_signature_raises_invalid_token(self) -> None:
|
||||
token = create_access_token({"sub": "valid-user", "role": "user"})
|
||||
parts = token.split(".")
|
||||
# Valid base64url string that fails HMAC comparison
|
||||
tampered_sig = base64url_encode(b"wrong_hmac_signature_bytes_32_b")
|
||||
tampered_token = f"{parts[0]}.{parts[1]}.{tampered_sig}"
|
||||
with pytest.raises(InvalidTokenError):
|
||||
decode_access_token(tampered_token)
|
||||
|
||||
def test_decode_invalid_header_raises(self) -> None:
|
||||
import hashlib
|
||||
import hmac
|
||||
from app.features.auth.security import JWT_SECRET
|
||||
bad_header = base64url_encode(b'{"alg":"none","typ":"JWT"}')
|
||||
payload = base64url_encode(b'{"sub":"user1","exp":9999999999}')
|
||||
signing_input = f"{bad_header}.{payload}".encode("utf-8")
|
||||
valid_sig = base64url_encode(hmac.new(JWT_SECRET.encode("utf-8"), signing_input, hashlib.sha256).digest())
|
||||
token = f"{bad_header}.{payload}.{valid_sig}"
|
||||
with pytest.raises(InvalidTokenError):
|
||||
decode_access_token(token)
|
||||
|
||||
def test_decode_malformed_json_in_token_raises(self) -> None:
|
||||
header = base64url_encode(b'{"alg":"HS256","typ":"JWT"}')
|
||||
bad_payload = base64url_encode(b'not valid json')
|
||||
token = f"{header}.{bad_payload}.c2lnbmF0dXJl"
|
||||
with pytest.raises(InvalidTokenError):
|
||||
decode_access_token(token)
|
||||
|
||||
def test_decode_non_int_exp_raises(self) -> None:
|
||||
import hashlib
|
||||
import hmac
|
||||
from app.features.auth.security import JWT_SECRET
|
||||
header = base64url_encode(b'{"alg":"HS256","typ":"JWT"}')
|
||||
payload = base64url_encode(b'{"sub":"user1","exp":"never"}')
|
||||
signing_input = f"{header}.{payload}".encode("utf-8")
|
||||
valid_sig = base64url_encode(hmac.new(JWT_SECRET.encode("utf-8"), signing_input, hashlib.sha256).digest())
|
||||
token = f"{header}.{payload}.{valid_sig}"
|
||||
with pytest.raises(InvalidTokenError):
|
||||
decode_access_token(token)
|
||||
|
||||
def test_decode_expired_token_raises_invalid_token(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
# Create token with TTL in the past
|
||||
monkeypatch.setattr("app.features.auth.security.JWT_TTL_SECONDS", -10)
|
||||
expired_token = create_access_token({"sub": "user-123"})
|
||||
|
||||
with pytest.raises(InvalidTokenError):
|
||||
decode_access_token(expired_token)
|
||||
|
||||
def test_decode_missing_sub_raises_invalid_token(self) -> None:
|
||||
token = create_access_token({"role": "guest"}) # No 'sub' key
|
||||
with pytest.raises(InvalidTokenError):
|
||||
decode_access_token(token)
|
||||
|
||||
def test_verify_password_catches_invalid_salt_format(self) -> None:
|
||||
# Format passes startswith $2b$ but is invalid for bcrypt.checkpw
|
||||
assert verify_password("pass", "$2b$invalid_format_hash") is False
|
||||
Loading…
Reference in New Issue