chore: update project documentation, audit reports, and initialize IDE configuration files
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 29s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 2m42s
Deploy / Build Web Image (push) Failing after 27s
Deploy / Build AI Services Image (push) Failing after 29s
E2E Tests / Playwright E2E (push) Failing after 43s
Deploy / Build API Image (push) Failing after 1m31s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 6s
Security Scanning / Trivy Scan — API Image (push) Failing after 5m35s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 3m45s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Deploy / Rollback Staging (push) Has been skipped
Deploy / Rollback Production (push) Has been skipped
Security Scanning / Trivy Scan — Web Image (push) Failing after 13m51s
Security Scanning / Trivy Filesystem Scan (push) Failing after 14m46s
Security Scanning / Security Gate (push) Has been cancelled
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 29s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 2m42s
Deploy / Build Web Image (push) Failing after 27s
Deploy / Build AI Services Image (push) Failing after 29s
E2E Tests / Playwright E2E (push) Failing after 43s
Deploy / Build API Image (push) Failing after 1m31s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 6s
Security Scanning / Trivy Scan — API Image (push) Failing after 5m35s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 3m45s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Deploy / Rollback Staging (push) Has been skipped
Deploy / Rollback Production (push) Has been skipped
Security Scanning / Trivy Scan — Web Image (push) Failing after 13m51s
Security Scanning / Trivy Filesystem Scan (push) Failing after 14m46s
Security Scanning / Security Gate (push) Has been cancelled
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
# MCP Module Exploration - GoodGo Platform
|
||||
|
||||
## 1. MODULE STRUCTURE & SOURCE FILES
|
||||
## 1. CẤU TRÚC MODULE & CÁC TỆP NGUỒN
|
||||
|
||||
### Directory Structure
|
||||
### Cấu trúc thư mục
|
||||
```
|
||||
apps/api/src/modules/mcp/
|
||||
├── index.ts
|
||||
@@ -13,184 +13,184 @@ apps/api/src/modules/mcp/
|
||||
└── mcp-transport.controller.spec.ts
|
||||
```
|
||||
|
||||
### All Source Files (4 files)
|
||||
### Tất cả tệp nguồn (4 tệp)
|
||||
|
||||
#### 1. **apps/api/src/modules/mcp/index.ts**
|
||||
- **Type**: Module entry point (exports)
|
||||
- **Purpose**: Exports the McpIntegrationModule
|
||||
- **Exports**: `{ McpIntegrationModule }`
|
||||
- **Loại**: Điểm vào của module (xuất khẩu)
|
||||
- **Mục đích**: Xuất khẩu McpIntegrationModule
|
||||
- **Xuất khẩu**: `{ McpIntegrationModule }`
|
||||
|
||||
#### 2. **apps/api/src/modules/mcp/mcp.module.ts**
|
||||
- **Type**: NestJS Module configuration (22 lines)
|
||||
- **Key Class**: `McpIntegrationModule implements OnModuleInit`
|
||||
- **Responsibility**:
|
||||
- Sets up MCP core module with configuration
|
||||
- Initializes TypesenseClient for MCP registry
|
||||
- Logs initialized server names on module init
|
||||
- **Dependencies Injected**:
|
||||
- `TypesenseClientService` (from SearchModule)
|
||||
- `McpRegistryService` (from @goodgo/mcp-servers)
|
||||
- `LoggerService` (from SharedModule)
|
||||
- **Imports**:
|
||||
- **Loại**: Cấu hình NestJS Module (22 dòng)
|
||||
- **Lớp chính**: `McpIntegrationModule implements OnModuleInit`
|
||||
- **Trách nhiệm**:
|
||||
- Thiết lập module MCP cốt lõi với cấu hình
|
||||
- Khởi tạo TypesenseClient cho registry MCP
|
||||
- Ghi log tên các server đã khởi tạo khi module được khởi động
|
||||
- **Phụ thuộc được tiêm**:
|
||||
- `TypesenseClientService` (từ SearchModule)
|
||||
- `McpRegistryService` (từ @goodgo/mcp-servers)
|
||||
- `LoggerService` (từ SharedModule)
|
||||
- **Nhập khẩu**:
|
||||
- `SearchModule`
|
||||
- `AuthModule`
|
||||
- `McpCoreModule.forRoot()` with config
|
||||
- `McpCoreModule.forRoot()` với cấu hình
|
||||
- **Controllers**: McpTransportController
|
||||
- **Lifecycle**: Implements `onModuleInit()`
|
||||
- **Vòng đời**: Triển khai `onModuleInit()`
|
||||
|
||||
#### 3. **apps/api/src/modules/mcp/presentation/mcp-transport.controller.ts**
|
||||
- **Type**: NestJS Controller (102 lines)
|
||||
- **Key Class**: `McpTransportController`
|
||||
- **Responsibility**: HTTP transport layer for MCP SSE connections
|
||||
- **Decorators Applied**:
|
||||
- **Loại**: NestJS Controller (102 dòng)
|
||||
- **Lớp chính**: `McpTransportController`
|
||||
- **Trách nhiệm**: Lớp truyền tải HTTP cho các kết nối MCP SSE
|
||||
- **Decorator được áp dụng**:
|
||||
- `@ApiTags('mcp')`
|
||||
- `@ApiBearerAuth('JWT')`
|
||||
- `@Controller('mcp')`
|
||||
- `@UseGuards(JwtAuthGuard)` - protects all endpoints
|
||||
- **Properties**:
|
||||
- `transports: Map<string, SSEServerTransport>` - active session management
|
||||
- **Injected Dependencies**:
|
||||
- `@UseGuards(JwtAuthGuard)` - bảo vệ tất cả các endpoint
|
||||
- **Thuộc tính**:
|
||||
- `transports: Map<string, SSEServerTransport>` - quản lý phiên hoạt động
|
||||
- **Phụ thuộc được tiêm**:
|
||||
- `registry: McpRegistryService`
|
||||
|
||||
**Endpoints:**
|
||||
**Các endpoint:**
|
||||
|
||||
1. **GET /mcp/servers** (line 27-34)
|
||||
- Summary: List available MCP servers
|
||||
- Throttle: 30 requests per 60s
|
||||
- Returns: `{ servers: string[] }`
|
||||
- Status: 200 (success), 401 (unauthorized)
|
||||
1. **GET /mcp/servers** (dòng 27-34)
|
||||
- Tóm tắt: Liệt kê các MCP server khả dụng
|
||||
- Throttle: 30 yêu cầu mỗi 60 giây
|
||||
- Trả về: `{ servers: string[] }`
|
||||
- Trạng thái: 200 (thành công), 401 (không được phép)
|
||||
|
||||
2. **GET /mcp/:serverName/sse** (line 36-68)
|
||||
- Summary: Open SSE connection to MCP server
|
||||
- Throttle: 5 requests per 60s (stricter)
|
||||
- Params: `serverName`
|
||||
- Returns: SSE stream
|
||||
- Response Handling:
|
||||
- Creates `SSEServerTransport` instance
|
||||
- Stores in map with `sessionId`
|
||||
- Connects to server via `server.connect(transport)`
|
||||
- Cleans up on request close
|
||||
- Status: 200 (stream), 404 (server not found), 401 (unauthorized)
|
||||
2. **GET /mcp/:serverName/sse** (dòng 36-68)
|
||||
- Tóm tắt: Mở kết nối SSE đến MCP server
|
||||
- Throttle: 5 yêu cầu mỗi 60 giây (chặt chẽ hơn)
|
||||
- Tham số: `serverName`
|
||||
- Trả về: Luồng SSE
|
||||
- Xử lý phản hồi:
|
||||
- Tạo instance `SSEServerTransport`
|
||||
- Lưu vào map với `sessionId`
|
||||
- Kết nối đến server qua `server.connect(transport)`
|
||||
- Dọn dẹp khi yêu cầu đóng
|
||||
- Trạng thái: 200 (luồng), 404 (không tìm thấy server), 401 (không được phép)
|
||||
|
||||
3. **POST /mcp/:serverName/messages** (line 70-102)
|
||||
- Summary: Send message to MCP server session
|
||||
- Throttle: 30 requests per 60s
|
||||
- Params: `serverName`
|
||||
- Query: `sessionId` (required)
|
||||
- Body: Message data passed to transport
|
||||
- Response Handling:
|
||||
- Validates sessionId exists
|
||||
- Delegates to `transport.handlePostMessage(req, res)`
|
||||
- Status: 200 (success), 400 (missing sessionId), 404 (session not found), 401 (unauthorized)
|
||||
3. **POST /mcp/:serverName/messages** (dòng 70-102)
|
||||
- Tóm tắt: Gửi tin nhắn đến phiên MCP server
|
||||
- Throttle: 30 yêu cầu mỗi 60 giây
|
||||
- Tham số: `serverName`
|
||||
- Query: `sessionId` (bắt buộc)
|
||||
- Body: Dữ liệu tin nhắn được truyền đến transport
|
||||
- Xử lý phản hồi:
|
||||
- Xác thực sessionId tồn tại
|
||||
- Ủy quyền cho `transport.handlePostMessage(req, res)`
|
||||
- Trạng thái: 200 (thành công), 400 (thiếu sessionId), 404 (không tìm thấy phiên), 401 (không được phép)
|
||||
|
||||
---
|
||||
|
||||
## 2. TEST FILES
|
||||
## 2. CÁC TỆP TEST
|
||||
|
||||
### Total Test Files: 1
|
||||
### Tổng số tệp test: 1
|
||||
|
||||
#### **apps/api/src/modules/mcp/presentation/__tests__/mcp-transport.controller.spec.ts** (174 lines)
|
||||
- **Testing Framework**: Vitest
|
||||
- **Subject**: `McpTransportController`
|
||||
- **Test Structure**: Describe blocks + beforeEach setup
|
||||
#### **apps/api/src/modules/mcp/presentation/__tests__/mcp-transport.controller.spec.ts** (174 dòng)
|
||||
- **Framework kiểm thử**: Vitest
|
||||
- **Đối tượng kiểm thử**: `McpTransportController`
|
||||
- **Cấu trúc test**: Các khối Describe + thiết lập beforeEach
|
||||
|
||||
**Test Suites (4 describe blocks):**
|
||||
**Bộ test (4 khối describe):**
|
||||
|
||||
1. **security decorators** (4 tests)
|
||||
- Verifies JwtAuthGuard is applied
|
||||
- Checks Throttle metadata on endpoints
|
||||
- Validates throttle limits (30, 5, 30)
|
||||
1. **security decorators** (4 test)
|
||||
- Xác minh JwtAuthGuard được áp dụng
|
||||
- Kiểm tra metadata Throttle trên các endpoint
|
||||
- Xác nhận giới hạn throttle (30, 5, 30)
|
||||
|
||||
2. **listServers** (2 tests)
|
||||
- Returns server list from registry
|
||||
- Handles empty server list
|
||||
2. **listServers** (2 test)
|
||||
- Trả về danh sách server từ registry
|
||||
- Xử lý danh sách server rỗng
|
||||
|
||||
3. **handleSse** (3 tests)
|
||||
- Throws NOT_FOUND when server doesn't exist
|
||||
- Creates transport and connects to server
|
||||
- Cleans up on connection close (transport removal)
|
||||
3. **handleSse** (3 test)
|
||||
- Ném NOT_FOUND khi server không tồn tại
|
||||
- Tạo transport và kết nối đến server
|
||||
- Dọn dẹp khi đóng kết nối (xóa transport)
|
||||
|
||||
4. **handleMessage** (2 tests)
|
||||
- Throws BAD_REQUEST when sessionId missing
|
||||
- Throws NOT_FOUND when session doesn't exist
|
||||
4. **handleMessage** (2 test)
|
||||
- Ném BAD_REQUEST khi thiếu sessionId
|
||||
- Ném NOT_FOUND khi phiên không tồn tại
|
||||
|
||||
**Mocking Patterns Used:**
|
||||
- `vi.mock()` for external modules (SSEServerTransport)
|
||||
- `vi.fn()` for service method mocks
|
||||
**Các mẫu Mock được sử dụng:**
|
||||
- `vi.mock()` cho các module ngoài (SSEServerTransport)
|
||||
- `vi.fn()` cho mock phương thức service
|
||||
- `mockReturnValue()`, `mockResolvedValue()`, `mockRejectValue()`
|
||||
- Manual mock objects for requests/responses
|
||||
- Reflection API for metadata checks (`Reflect.getMetadata()`)
|
||||
- Đối tượng mock thủ công cho request/response
|
||||
- Reflection API để kiểm tra metadata (`Reflect.getMetadata()`)
|
||||
|
||||
---
|
||||
|
||||
## 3. DDD LAYER STRUCTURE
|
||||
## 3. CẤU TRÚC LỚP DDD
|
||||
|
||||
**Current Status**: MCP module has a **SIMPLIFIED structure** (NOT full DDD yet):
|
||||
**Trạng thái hiện tại**: Module MCP có **cấu trúc ĐƠN GIẢN HÓA** (chưa áp dụng DDD đầy đủ):
|
||||
|
||||
### What EXISTS:
|
||||
- **Presentation Layer** ✅
|
||||
### Những gì ĐÃ TỒN TẠI:
|
||||
- **Lớp Presentation** ✅
|
||||
- `presentation/mcp-transport.controller.ts`
|
||||
- `presentation/__tests__/mcp-transport.controller.spec.ts`
|
||||
- HTTP endpoint definitions
|
||||
- Guard decorators (auth)
|
||||
- Throttle decorators
|
||||
- Swagger decorators
|
||||
- Định nghĩa HTTP endpoint
|
||||
- Decorator Guard (xác thực)
|
||||
- Decorator Throttle
|
||||
- Decorator Swagger
|
||||
|
||||
### What DOES NOT EXIST (yet):
|
||||
- **Domain Layer** ❌
|
||||
- No `domain/` directory
|
||||
- No entities, value objects, or domain events
|
||||
- No domain business logic
|
||||
### Những gì CHƯA TỒN TẠI:
|
||||
- **Lớp Domain** ❌
|
||||
- Không có thư mục `domain/`
|
||||
- Không có entity, value object hay domain event
|
||||
- Không có logic nghiệp vụ domain
|
||||
|
||||
- **Application Layer** ❌
|
||||
- No `application/` directory
|
||||
- No commands/handlers (CQRS pattern not used here)
|
||||
- No queries
|
||||
- No DTOs
|
||||
- **Lớp Application** ❌
|
||||
- Không có thư mục `application/`
|
||||
- Không có command/handler (chưa dùng mẫu CQRS)
|
||||
- Không có query
|
||||
- Không có DTO
|
||||
|
||||
- **Infrastructure Layer** ❌
|
||||
- No `infrastructure/` directory
|
||||
- No repositories
|
||||
- No external service adapters
|
||||
- No database access
|
||||
- **Lớp Infrastructure** ❌
|
||||
- Không có thư mục `infrastructure/`
|
||||
- Không có repository
|
||||
- Không có adapter dịch vụ ngoài
|
||||
- Không có truy cập cơ sở dữ liệu
|
||||
|
||||
### Architecture Notes:
|
||||
- The MCP module acts as an **integration wrapper**
|
||||
- Delegates to `@goodgo/mcp-servers` library (external dependency)
|
||||
- Simple **presentation-only controller** approach
|
||||
- Focuses on HTTP transport mechanism (SSE connections)
|
||||
- Session management via in-memory Map
|
||||
### Ghi chú kiến trúc:
|
||||
- Module MCP đóng vai trò là một **lớp tích hợp bọc ngoài**
|
||||
- Ủy quyền cho thư viện `@goodgo/mcp-servers` (phụ thuộc ngoài)
|
||||
- Cách tiếp cận **controller chỉ có presentation** đơn giản
|
||||
- Tập trung vào cơ chế truyền tải HTTP (kết nối SSE)
|
||||
- Quản lý phiên qua Map trong bộ nhớ
|
||||
|
||||
---
|
||||
|
||||
## 4. KEY CLASSES/HANDLERS NEEDING TESTS
|
||||
## 4. CÁC LỚP/HANDLER CHÍNH CẦN ĐƯỢC KIỂM THỬ
|
||||
|
||||
### Current Implementation:
|
||||
### Triển khai hiện tại:
|
||||
|
||||
1. **McpIntegrationModule** (mcp.module.ts)
|
||||
- **Status**: Partially tested (initialization logic)
|
||||
- **Methods needing tests**:
|
||||
- `constructor()` - dependency injection
|
||||
- `onModuleInit()` - initialization flow
|
||||
- **Test focus**: Module setup, service integration, logging
|
||||
- **Trạng thái**: Được kiểm thử một phần (logic khởi tạo)
|
||||
- **Các phương thức cần kiểm thử**:
|
||||
- `constructor()` - tiêm phụ thuộc
|
||||
- `onModuleInit()` - luồng khởi tạo
|
||||
- **Trọng tâm kiểm thử**: Thiết lập module, tích hợp service, ghi log
|
||||
|
||||
2. **McpTransportController** (mcp-transport.controller.ts)
|
||||
- **Status**: Well tested ✅ (174 lines of tests)
|
||||
- **Methods tested**:
|
||||
- `listServers()` - returns available servers
|
||||
- `handleSse()` - establishes SSE connection
|
||||
- `handleMessage()` - routes messages to session
|
||||
- **Test coverage**: Happy path + error cases + security decorators
|
||||
- **Trạng thái**: Được kiểm thử tốt ✅ (174 dòng test)
|
||||
- **Các phương thức được kiểm thử**:
|
||||
- `listServers()` - trả về các server khả dụng
|
||||
- `handleSse()` - thiết lập kết nối SSE
|
||||
- `handleMessage()` - định tuyến tin nhắn đến phiên
|
||||
- **Độ phủ kiểm thử**: Happy path + trường hợp lỗi + decorator bảo mật
|
||||
|
||||
---
|
||||
|
||||
## 5. TESTING PATTERNS FROM OTHER MODULES
|
||||
## 5. CÁC MẪU KIỂM THỬ TỪ CÁC MODULE KHÁC
|
||||
|
||||
### Pattern 1: Auth Module - Handler Testing (Simple)
|
||||
**File**: `apps/api/src/modules/auth/application/__tests__/login-user.handler.spec.ts`
|
||||
### Mẫu 1: Module Auth - Kiểm thử Handler (Đơn giản)
|
||||
**Tệp**: `apps/api/src/modules/auth/application/__tests__/login-user.handler.spec.ts`
|
||||
|
||||
```typescript
|
||||
// KEY PATTERNS:
|
||||
// CÁC MẪU CHÍNH:
|
||||
// 1. No explicit imports from vitest (globals enabled)
|
||||
// 2. beforeEach: Create handler with mocked dependencies
|
||||
// 3. vi.fn() for service mocks
|
||||
@@ -227,19 +227,19 @@ describe('LoginUserHandler', () => {
|
||||
});
|
||||
```
|
||||
|
||||
**Key Takeaways**:
|
||||
- ✅ Minimal setup, direct handler instantiation
|
||||
- ✅ Command objects for test input
|
||||
- ✅ Simple mock with typed object
|
||||
- ✅ Focus on behavior verification
|
||||
- ✅ Uses `as any` for type casting
|
||||
**Điểm chú ý chính**:
|
||||
- ✅ Thiết lập tối giản, khởi tạo handler trực tiếp
|
||||
- ✅ Đối tượng Command làm đầu vào kiểm thử
|
||||
- ✅ Mock đơn giản với đối tượng có kiểu
|
||||
- ✅ Tập trung vào xác minh hành vi
|
||||
- ✅ Dùng `as any` để ép kiểu
|
||||
|
||||
|
||||
### Pattern 2: Payments Module - Complex Handler Testing (Advanced)
|
||||
**File**: `apps/api/src/modules/payments/application/__tests__/create-payment.handler.spec.ts`
|
||||
### Mẫu 2: Module Payments - Kiểm thử Handler phức tạp (Nâng cao)
|
||||
**Tệp**: `apps/api/src/modules/payments/application/__tests__/create-payment.handler.spec.ts`
|
||||
|
||||
```typescript
|
||||
// KEY PATTERNS:
|
||||
// CÁC MẪU CHÍNH:
|
||||
// 1. Multiple mocked dependencies (repo, factory, gateway, event bus)
|
||||
// 2. Complex mock setup with multiple methods
|
||||
// 3. Tests for idempotency handling
|
||||
@@ -324,21 +324,21 @@ describe('CreatePaymentHandler', () => {
|
||||
});
|
||||
```
|
||||
|
||||
**Key Takeaways**:
|
||||
- ✅ Complex multi-dependency mocking
|
||||
- ✅ Mapped type for repository mocks `[K in keyof IPaymentRepository]`
|
||||
- ✅ Individual method mocks for each dependency
|
||||
- ✅ Tests for business rules (idempotency)
|
||||
- ✅ Error case testing with regex matching
|
||||
- ✅ Logger mock included
|
||||
- ✅ Verify multiple calls and interactions
|
||||
**Điểm chú ý chính**:
|
||||
- ✅ Mock nhiều phụ thuộc phức tạp
|
||||
- ✅ Kiểu ánh xạ cho mock repository `[K in keyof IPaymentRepository]`
|
||||
- ✅ Mock từng phương thức riêng lẻ cho mỗi phụ thuộc
|
||||
- ✅ Kiểm thử quy tắc nghiệp vụ (idempotency)
|
||||
- ✅ Kiểm thử trường hợp lỗi với khớp regex
|
||||
- ✅ Bao gồm mock logger
|
||||
- ✅ Xác minh nhiều lần gọi và tương tác
|
||||
|
||||
|
||||
### Pattern 3: Domain Entity Testing (DDD Style)
|
||||
**File**: `apps/api/src/modules/payments/domain/__tests__/payment.entity.spec.ts`
|
||||
### Mẫu 3: Kiểm thử Entity Domain (Phong cách DDD)
|
||||
**Tệp**: `apps/api/src/modules/payments/domain/__tests__/payment.entity.spec.ts`
|
||||
|
||||
```typescript
|
||||
// KEY PATTERNS:
|
||||
// CÁC MẪU CHÍNH:
|
||||
// 1. Explicit vitest imports at the top
|
||||
// 2. Complex entity with state transitions
|
||||
// 3. Tests for domain events
|
||||
@@ -417,22 +417,22 @@ describe('PaymentEntity', () => {
|
||||
});
|
||||
```
|
||||
|
||||
**Key Takeaways**:
|
||||
- ✅ Explicit vitest imports (explicit over implicit)
|
||||
- ✅ Helper factory method for complex setup
|
||||
- ✅ Tests for entity behavior (state transitions)
|
||||
- ✅ Tests for domain events
|
||||
- ✅ Tests for error handling (Result pattern)
|
||||
- ✅ No mocking - tests real entity logic
|
||||
- ✅ Value object usage (Money.create().unwrap())
|
||||
- ✅ Domain event verification
|
||||
**Điểm chú ý chính**:
|
||||
- ✅ Import vitest tường minh (tường minh hơn ngầm định)
|
||||
- ✅ Phương thức factory trợ giúp cho thiết lập phức tạp
|
||||
- ✅ Kiểm thử hành vi entity (chuyển đổi trạng thái)
|
||||
- ✅ Kiểm thử domain event
|
||||
- ✅ Kiểm thử xử lý lỗi (mẫu Result)
|
||||
- ✅ Không mock - kiểm thử logic entity thực tế
|
||||
- ✅ Sử dụng value object (Money.create().unwrap())
|
||||
- ✅ Xác minh domain event
|
||||
|
||||
|
||||
### Pattern 4: Infrastructure Service Testing (Crypto/External)
|
||||
**File**: `apps/api/src/modules/payments/infrastructure/__tests__/zalopay.service.spec.ts`
|
||||
### Mẫu 4: Kiểm thử Service Infrastructure (Crypto/Bên ngoài)
|
||||
**Tệp**: `apps/api/src/modules/payments/infrastructure/__tests__/zalopay.service.spec.ts`
|
||||
|
||||
```typescript
|
||||
// KEY PATTERNS:
|
||||
// CÁC MẪU CHÍNH:
|
||||
// 1. Explicit vitest imports
|
||||
// 2. External service simulation (payment gateway)
|
||||
// 3. Crypto/HMAC signature testing
|
||||
@@ -519,42 +519,42 @@ describe('ZalopayService', () => {
|
||||
});
|
||||
```
|
||||
|
||||
**Key Takeaways**:
|
||||
- ✅ Explicit vitest imports (import from 'vitest')
|
||||
- ✅ Tests for security-critical functionality (HMAC verification)
|
||||
- ✅ ConfigService mocking for environment variables
|
||||
- ✅ Helper function for complex test data generation
|
||||
- ✅ Tests for error conditions (invalid JSON, wrong MAC)
|
||||
- ✅ Tests for security edge cases (tampered data)
|
||||
- ✅ Uses Node.js crypto module directly
|
||||
- ✅ Real algorithm testing (SHA256 HMAC)
|
||||
**Điểm chú ý chính**:
|
||||
- ✅ Import vitest tường minh (import from 'vitest')
|
||||
- ✅ Kiểm thử chức năng quan trọng về bảo mật (xác minh HMAC)
|
||||
- ✅ Mock ConfigService cho biến môi trường
|
||||
- ✅ Hàm trợ giúp để tạo dữ liệu kiểm thử phức tạp
|
||||
- ✅ Kiểm thử các điều kiện lỗi (JSON không hợp lệ, MAC sai)
|
||||
- ✅ Kiểm thử các trường hợp biên về bảo mật (dữ liệu bị giả mạo)
|
||||
- ✅ Sử dụng module crypto của Node.js trực tiếp
|
||||
- ✅ Kiểm thử thuật toán thực (SHA256 HMAC)
|
||||
|
||||
---
|
||||
|
||||
## 6. TESTING CONVENTIONS SUMMARY
|
||||
## 6. TÓM TẮT QUY ƯỚC KIỂM THỬ
|
||||
|
||||
### Framework & Setup
|
||||
### Framework & Thiết lập
|
||||
- **Framework**: Vitest
|
||||
- **Environment**: Node.js
|
||||
- **Globals**: Enabled (`globals: true` in config)
|
||||
- **File Pattern**: `*.spec.ts` (not `.test.ts`)
|
||||
- **Test Organization**: `__tests__/` subdirectory
|
||||
- **Môi trường**: Node.js
|
||||
- **Globals**: Được bật (`globals: true` trong cấu hình)
|
||||
- **Mẫu tên tệp**: `*.spec.ts` (không phải `.test.ts`)
|
||||
- **Tổ chức test**: Thư mục con `__tests__/`
|
||||
|
||||
### Import Styles
|
||||
### Phong cách Import
|
||||
```typescript
|
||||
// Style 1: Using globals (in simple tests)
|
||||
// Phong cách 1: Dùng globals (trong các test đơn giản)
|
||||
describe('MyClass', () => {
|
||||
it('does something', () => {
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// Style 2: Explicit imports (in complex/domain tests)
|
||||
// Phong cách 2: Import tường minh (trong các test phức tạp/domain)
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
```
|
||||
|
||||
### Mocking Patterns
|
||||
1. **Service Mocks**
|
||||
### Các mẫu Mock
|
||||
1. **Mock Service**
|
||||
```typescript
|
||||
mockService = {
|
||||
method: vi.fn().mockResolvedValue(value),
|
||||
@@ -562,14 +562,14 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
};
|
||||
```
|
||||
|
||||
2. **Module Mocks**
|
||||
2. **Mock Module**
|
||||
```typescript
|
||||
vi.mock('@goodgo/mcp-servers', () => ({
|
||||
SSEServerTransport: class MockSSE { /* ... */ },
|
||||
}));
|
||||
```
|
||||
|
||||
3. **Configuration Mocks**
|
||||
3. **Mock Cấu hình**
|
||||
```typescript
|
||||
const mockConfig = {
|
||||
get: vi.fn((key) => env[key]),
|
||||
@@ -577,7 +577,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
};
|
||||
```
|
||||
|
||||
### Test Structure
|
||||
### Cấu trúc Test
|
||||
```typescript
|
||||
describe('ClassName', () => {
|
||||
let instance: ClassName;
|
||||
@@ -585,9 +585,9 @@ describe('ClassName', () => {
|
||||
let mockDep2: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
// Setup mocks
|
||||
// Thiết lập mock
|
||||
mockDep1 = { method: vi.fn() };
|
||||
// Instantiate with mocks
|
||||
// Khởi tạo với mock
|
||||
instance = new ClassName(mockDep1 as any, mockDep2 as any);
|
||||
});
|
||||
|
||||
@@ -615,59 +615,59 @@ describe('ClassName', () => {
|
||||
});
|
||||
```
|
||||
|
||||
### Common Assertions Used
|
||||
- `expect(x).toBe(value)` - strict equality
|
||||
- `expect(x).toEqual(object)` - deep equality
|
||||
- `expect(x).toHaveLength(n)` - array/string length
|
||||
- `expect(x).toBeInstanceOf(Class)` - instance check
|
||||
- `expect(fn).toHaveBeenCalled()` - called verification
|
||||
- `expect(fn).toHaveBeenCalledWith(args)` - call arguments
|
||||
- `expect(fn).toHaveBeenCalledTimes(n)` - call count
|
||||
- `expect(promise).rejects.toThrow(msg)` - error expectation
|
||||
### Các assertion thường dùng
|
||||
- `expect(x).toBe(value)` - so sánh bằng nghiêm ngặt
|
||||
- `expect(x).toEqual(object)` - so sánh bằng sâu
|
||||
- `expect(x).toHaveLength(n)` - độ dài mảng/chuỗi
|
||||
- `expect(x).toBeInstanceOf(Class)` - kiểm tra instance
|
||||
- `expect(fn).toHaveBeenCalled()` - xác minh đã được gọi
|
||||
- `expect(fn).toHaveBeenCalledWith(args)` - tham số khi gọi
|
||||
- `expect(fn).toHaveBeenCalledTimes(n)` - số lần gọi
|
||||
- `expect(promise).rejects.toThrow(msg)` - kỳ vọng lỗi
|
||||
|
||||
### Vitest-Specific Features Used
|
||||
- `vi.fn()` - create mock function
|
||||
- `vi.mock()` - module mocking
|
||||
- `mockResolvedValue()` - async return
|
||||
- `mockReturnValue()` - sync return
|
||||
- `mockRejectedValue()` - error simulation
|
||||
- `Reflect.getMetadata()` - decorator inspection (NestJS)
|
||||
### Các tính năng đặc trưng của Vitest được dùng
|
||||
- `vi.fn()` - tạo hàm mock
|
||||
- `vi.mock()` - mock module
|
||||
- `mockResolvedValue()` - giá trị trả về bất đồng bộ
|
||||
- `mockReturnValue()` - giá trị trả về đồng bộ
|
||||
- `mockRejectedValue()` - mô phỏng lỗi
|
||||
- `Reflect.getMetadata()` - kiểm tra decorator (NestJS)
|
||||
|
||||
---
|
||||
|
||||
## 7. RECOMMENDATIONS FOR MCP MODULE TESTING
|
||||
## 7. KHUYẾN NGHỊ CHO KIỂM THỬ MODULE MCP
|
||||
|
||||
### Current Coverage Status
|
||||
- ✅ Controller (presentation layer): Well tested
|
||||
- ⚠️ Module initialization: Basic (mocked)
|
||||
- ❌ Domain layer: Not implemented
|
||||
- ❌ Application layer: Not implemented
|
||||
- ❌ Infrastructure layer: Not implemented
|
||||
### Trạng thái độ phủ hiện tại
|
||||
- ✅ Controller (lớp presentation): Được kiểm thử tốt
|
||||
- ⚠️ Khởi tạo module: Cơ bản (được mock)
|
||||
- ❌ Lớp Domain: Chưa được triển khai
|
||||
- ❌ Lớp Application: Chưa được triển khai
|
||||
- ❌ Lớp Infrastructure: Chưa được triển khai
|
||||
|
||||
### Recommended Next Steps
|
||||
1. **Expand Controller Tests**
|
||||
- Integration tests with mock SSE connections
|
||||
- Test session lifecycle (open → message → close)
|
||||
- Test error recovery
|
||||
### Các bước tiếp theo được khuyến nghị
|
||||
1. **Mở rộng kiểm thử Controller**
|
||||
- Kiểm thử tích hợp với kết nối SSE được mock
|
||||
- Kiểm thử vòng đời phiên (mở → tin nhắn → đóng)
|
||||
- Kiểm thử phục hồi lỗi
|
||||
|
||||
2. **Add Module Tests**
|
||||
- Test `McpIntegrationModule.onModuleInit()`
|
||||
- Test registry initialization
|
||||
- Test service injection
|
||||
2. **Thêm kiểm thử Module**
|
||||
- Kiểm thử `McpIntegrationModule.onModuleInit()`
|
||||
- Kiểm thử khởi tạo registry
|
||||
- Kiểm thử tiêm service
|
||||
|
||||
3. **Consider Adding Domain Tests** (if business logic added)
|
||||
- Session entity tests
|
||||
- Connection state management
|
||||
- Event handling
|
||||
3. **Cân nhắc thêm kiểm thử Domain** (nếu có logic nghiệp vụ)
|
||||
- Kiểm thử entity phiên
|
||||
- Quản lý trạng thái kết nối
|
||||
- Xử lý sự kiện
|
||||
|
||||
### Test Command
|
||||
### Lệnh kiểm thử
|
||||
```bash
|
||||
# Run all MCP tests
|
||||
# Chạy tất cả test MCP
|
||||
pnpm test -- src/modules/mcp
|
||||
|
||||
# Run with coverage
|
||||
# Chạy với coverage
|
||||
pnpm test -- --coverage src/modules/mcp
|
||||
|
||||
# Watch mode
|
||||
# Chế độ watch
|
||||
pnpm test -- --watch src/modules/mcp
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user