source: update Base rule Agent
This commit is contained in:
@@ -1,54 +1,54 @@
|
||||
---
|
||||
name: GenerateGitHubActions
|
||||
description: Hướng dẫn tạo CI/CD pipeline tự động hóa Build, Test, Docker Build & Deploy bằng GitHub Actions.
|
||||
description: Guide to generating a CI/CD pipeline automating Build, Test, Docker Build & Deploy using GitHub Actions.
|
||||
---
|
||||
|
||||
# GenerateGitHubActions Skill
|
||||
|
||||
Khi user yêu cầu tạo CI/CD Pipelines (ví dụ: GitHub Actions, hoặc tương đương cho GitLab CI / Azure DevOps), bạn cần sinh ra file luồng tự động hóa theo các bước chuẩn sau đây.
|
||||
When a user requests the creation of CI/CD Pipelines (e.g., GitHub Actions, or its equivalent for GitLab CI / Azure DevOps), you must generate an automation workflow file following standard steps below.
|
||||
|
||||
## Mục đích
|
||||
- Tự động hóa quá trình kiểm tra mã nguồn (CI) và triển khai (CD).
|
||||
- Đảm bảo code push lên nhánh `main` luôn hoạt động đúng đắn và sẵn sàng lên production.
|
||||
## Purpose
|
||||
- Automate the source code testing (CI) and deployment (CD) process.
|
||||
- Ensure any code pushed to the `main` branch always functions correctly and is ready for production.
|
||||
|
||||
## Hướng dẫn sinh cấu hình (GitHub Actions)
|
||||
## Configuration Guide (GitHub Actions)
|
||||
|
||||
Tạo file luồng công việc Workflow cho GitHub Actions.
|
||||
Create a Workflow file for GitHub Actions.
|
||||
|
||||
### 1. Đường dẫn và tên file
|
||||
- **Đường dẫn**: `.github/workflows/ci-cd.yml`
|
||||
- (Hoặc theo định dạng của platform tương ứng: `.gitlab-ci.yml` cho GitLab, `azure-pipelines.yml` cho Azure DevOps).
|
||||
### 1. File Path and Name
|
||||
- **Path**: `.github/workflows/ci-cd.yml`
|
||||
- (Or corresponding platform format: `.gitlab-ci.yml` for GitLab, `azure-pipelines.yml` for Azure DevOps).
|
||||
|
||||
### 2. Các bước cấu hình bắt buộc trong file YAML
|
||||
### 2. Mandatory Configuration Steps in the YAML File
|
||||
|
||||
Workflow cần trải qua các luồng chính sau (mẫu dưới dây cho GitHub Actions):
|
||||
The workflow needs to progress through these main flows (example below is for GitHub Actions):
|
||||
|
||||
#### Phân đoạn 1: Build & Test (CI)
|
||||
- **Triggers**: Lắng nghe sự kiện `push` hoặc `pull_request` vào nhánh `main`.
|
||||
- **Setup môi trường**:
|
||||
- Checkout mã nguồn (ví dụ dùng `actions/checkout@v4`).
|
||||
- Cài đặt .NET SDK tương ứng với dự án (ví dụ `actions/setup-dotnet@v4` cho .NET 8.0). **Lưu ý: Bật tính năng cache Nuget để tăng tốc độ build.**
|
||||
#### Phase 1: Build & Test (CI)
|
||||
- **Triggers**: Listen for `push` or `pull_request` events on the `main` branch.
|
||||
- **Environment Setup**:
|
||||
- Checkout source code (e.g., using `actions/checkout@v4`).
|
||||
- Install the .NET SDK matching the project (e.g., `actions/setup-dotnet@v4` for .NET 8.0). **Note: Enable Nuget cache to speed up the build.**
|
||||
- **Run Tests**:
|
||||
- Chạy khối lệnh `dotnet restore`, `dotnet build --no-restore`.
|
||||
- Quan trọng nhất: Chạy `dotnet test --no-build --verbosity normal`. (Chỉ khi Test Xanh (Passed) thì các bước sau mới được chạy tiếp).
|
||||
- Execute `dotnet restore`, `dotnet build --no-restore`.
|
||||
- Most critically: Run `dotnet test --no-build --verbosity normal`. (Only if Tests go Green (Passed) should subsequent steps proceed).
|
||||
|
||||
#### Phân đoạn 2: Docker Build & Push (Bắt đầu CD)
|
||||
- **Cần điều kiện**: Chỉ chạy khi Job Build & Test thành công (`needs: build`).
|
||||
- **Đăng nhập Container Registry**:
|
||||
- Login vào Docker Hub hoặc Azure Container Registry (ACR) sử dụng System Secrets (ví dụ `DOCKER_USERNAME` và `DOCKER_PASSWORD`).
|
||||
#### Phase 2: Docker Build & Push (Start of CD)
|
||||
- **Prerequisite**: Only run if the Build & Test Job was successful (`needs: build`).
|
||||
- **Log into Container Registry**:
|
||||
- Login to Docker Hub or Azure Container Registry (ACR) using System Secrets (e.g., `DOCKER_USERNAME` and `DOCKER_PASSWORD`).
|
||||
- **Build & Push Image**:
|
||||
- Build Image từ Dockerfile (chú ý chỉ đường dẫn thư mục gốc nơi chứa dự án chính để `docker build` có thể truy cập qua các tầng thư mục Clean Architecture).
|
||||
- Gắn tag cho Image (ví dụ: `latest` hoặc theo Commit SHA/phiên bản).
|
||||
- Push Image lên Registry.
|
||||
- Build the Image from the Dockerfile (ensure it points to the root directory containing the main project so `docker build` can access the multiple layers of Clean Architecture).
|
||||
- Tag the Image (e.g., `latest` or via Commit SHA/version).
|
||||
- Push the Image to the Registry.
|
||||
|
||||
#### Phân đoạn 3: Deploy to Server (CD - Webhook / SSH)
|
||||
- Dùng thư viện `appleboy/ssh-action` (hoặc tương tự) để SSH vào Server đích.
|
||||
- Yêu cầu server pull file Image mới nhất từ Registry.
|
||||
- **Quan trọng:** Ưu tiên sử dụng `docker compose` để deploy (pull và up) nếu cấu trúc dự án của user có file `docker-compose.yml`, giúp khởi động lại toàn bộ stack (API, DB, Redis...) thay vì chỉ chạy `docker run` độc lập.
|
||||
#### Phase 3: Deploy to Server (CD - Webhook / SSH)
|
||||
- Use the `appleboy/ssh-action` library (or similar) to SSH into the target Server.
|
||||
- Instruct the server to pull the latest Image file from the Registry.
|
||||
- **Important:** Prioritize using `docker compose` to deploy (pull and up) if the user's project structure includes a `docker-compose.yml` file. This helps restart the entire stack (API, DB, Redis, etc.) rather than just running a standalone `docker run`.
|
||||
|
||||
## Mẫu File Mặc Định (`ci-cd.yml`)
|
||||
## Default Template File (`ci-cd.yml`)
|
||||
|
||||
Dưới đây là khung mẫu bạn cần căn cứ để thiết kế khi sinh file cho user:
|
||||
Below is the template framework you need to base your designs on when generating files for users:
|
||||
|
||||
```yaml
|
||||
name: CI/CD Pipeline
|
||||
@@ -68,7 +68,7 @@ jobs:
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
cache: true # Bật cache Nuget, lần sau build nhanh gấp đôi
|
||||
cache: true # Enable Nuget cache; subsequent builds will be twice as fast
|
||||
cache-dependency-path: '**/packages.lock.json'
|
||||
|
||||
- name: Restore dependencies
|
||||
@@ -100,7 +100,7 @@ jobs:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: true
|
||||
tags: ${{ secrets.DOCKER_USERNAME }}/chi-tiet-ten-project-lowercase:latest
|
||||
tags: ${{ secrets.DOCKER_USERNAME }}/detailed-project-name-lowercase:latest
|
||||
|
||||
deploy:
|
||||
needs: docker-build-push
|
||||
@@ -115,12 +115,12 @@ jobs:
|
||||
username: ${{ secrets.SERVER_USER }}
|
||||
key: ${{ secrets.SERVER_SSH_KEY }}
|
||||
script: |
|
||||
cd /path/to/your/project/on/server # Trỏ tới thư mục chứa docker-compose.yml
|
||||
docker compose pull # Kéo image mới nhất về (dựa theo file compose)
|
||||
docker compose up -d --build # Khởi động lại các service có sự thay đổi
|
||||
cd /path/to/your/project/on/server # Point to the directory containing docker-compose.yml
|
||||
docker compose pull # Pull the newest image (based on the compose file)
|
||||
docker compose up -d --build # Restart any services with modifications
|
||||
```
|
||||
|
||||
## Lưu ý cho AI Agent
|
||||
- Khi User yêu cầu sinh pipeline, hãy yêu cầu User xác nhận về tên tài khoản Docker Hub, Server Credentials và nhắc họ cấu hình đầy đủ `Secrets` trên GitHub sau khi sinh file.
|
||||
- **Hãy tự động thay thế chuỗi tên project (`chi-tiet-ten-project-lowercase` trong mẫu) bằng tên thật của Project / Repository mà User đang thao tác. Chuyển tất cả về chữ thường (lowercase) khi đặt tên Docker Image để tránh lỗi định dạng của Docker.**
|
||||
- **Nếu user có dùng `docker-compose`, hãy ưu tiên sinh lệnh `docker compose up -d` thay vì `docker run` thuần.**
|
||||
## Reminders for the AI Agent
|
||||
- When a User asks to generate a pipeline, ensure you ask the User to confirm their Docker Hub account name, Server Credentials, and remind them to fully configure `Secrets` on GitHub after the file is generated.
|
||||
- **Automatically replace the project name string (`detailed-project-name-lowercase` in the template) with the true name of the Project / Repository the User is working on. Convert everything to lowercase when naming the Docker Image to prevent Docker formatting errors.**
|
||||
- **If the user utilizes `docker-compose`, prioritize generating the `docker compose up -d` command over bare `docker run` commands.**
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
---
|
||||
name: GenerateCQRSFeature
|
||||
description: Hướng dẫn tạo một feature theo chuẩn CQRS sử dụng MediatR (bao gồm Entity, Command/Query, Handler, và Controller).
|
||||
description: Guide to generating a CQRS-based feature using MediatR (including Entity, Command/Query, Handler, and Controller).
|
||||
---
|
||||
|
||||
# GenerateCQRSFeature Skill
|
||||
|
||||
Khi user yêu cầu tạo một feature theo luồng **CQRS** với đầu vào bao gồm **Tên Feature** (VD: `Order`) và **Action** (VD: `Create`), bạn **BẮT BUỘC** phải thực hiện các bước sau để sinh ra code và file tương ứng:
|
||||
When a user requests to create a feature using the **CQRS** pattern, providing the **Feature Name** (e.g., `Order`) and **Action** (e.g., `Create`), you **MUST** follow these steps to generate the corresponding code and files:
|
||||
|
||||
## 1. Đầu ra thư mục và file (Outputs)
|
||||
## 1. Directory and File Outputs
|
||||
|
||||
Dựa trên {FeatureName} và {Action}, hãy tạo các file sau (nếu action thuộc loại Read/Get thì đổi 'Commands' thành 'Queries'):
|
||||
Based on the {FeatureName} and {Action}, create the following files (if the action is Read/Get, change 'Commands' to 'Queries'):
|
||||
|
||||
1. **Domain Entity**
|
||||
- **Đường dẫn**: `Domain/Entities/{FeatureName}.cs`
|
||||
- **Nội dung**: Lớp Entity cơ bản định nghĩa các thuộc tính.
|
||||
- **Path**: `Domain/Entities/{FeatureName}.cs`
|
||||
- **Content**: A basic Entity class defining the properties.
|
||||
|
||||
2. **Command / Query**
|
||||
- **Đường dẫn**: `Application/Features/{FeatureName}s/Commands/{Action}{FeatureName}/{Action}{FeatureName}Command.cs`
|
||||
- **Nội dung**: Input model kế thừa từ `IRequest<TResponse>` của MediatR.
|
||||
- **Path**: `Application/Features/{FeatureName}s/Commands/{Action}{FeatureName}/{Action}{FeatureName}Command.cs`
|
||||
- **Content**: An input model that implements MediatR's `IRequest<TResponse>`.
|
||||
|
||||
3. **Command / Query Handler**
|
||||
- **Đường dẫn**: `Application/Features/{FeatureName}s/Commands/{Action}{FeatureName}/{Action}{FeatureName}CommandHandler.cs`
|
||||
- **Nội dung**: Xử lý logic nghiệp vụ, implements `IRequestHandler<{Action}{FeatureName}Command, TResponse>`. Inject Repository hoặc service cần thiết vào đây.
|
||||
- **Path**: `Application/Features/{FeatureName}s/Commands/{Action}{FeatureName}/{Action}{FeatureName}CommandHandler.cs`
|
||||
- **Content**: Business logic processor that implements `IRequestHandler<{Action}{FeatureName}Command, TResponse>`. Inject any needed Repository or service here.
|
||||
|
||||
4. **WebAPI Controller**
|
||||
- **Đường dẫn**: `WebAPI/Controllers/{FeatureName}sController.cs` (Lưu ý thêm số nhiều cho tên Controller nếu cần thiết).
|
||||
- **Nội dung**: REST API endpoints. **Yêu cầu:** Nhận DI `IMediator` qua constructor để điều hướng Request (ví dụ gọi `await _mediator.Send(command)`).
|
||||
- **Path**: `WebAPI/Controllers/{FeatureName}sController.cs` (Remember to pluralize the Controller name if applicable).
|
||||
- **Content**: REST API endpoints. **Requirement:** Must receive `IMediator` via Dependency Injection in the constructor to dispatch requests (e.g., `await _mediator.Send(command)`).
|
||||
|
||||
## 2. Cấu hình Dependency Injection (KHÔNG CẦN LÀM)
|
||||
## 2. Dependency Injection Configuration (NOT REQUIRED)
|
||||
|
||||
⚠️ **Lưu ý:** Như nguyên tắc thiết lập project, luồng CQRS **KHÔNG CẦN** update file cấu hình Dependency Injection (DI configuration).
|
||||
⚠️ **Note:** As per project standards, the CQRS flow **DOES NOT REQUIRE** updating Dependency Injection configuration files.
|
||||
|
||||
Thư viện MediatR đã tự động quét (Auto-register) tất cả các lớp Handler kế thừa từ `IRequestHandler`, vì thế bạn **TUYỆT ĐỐI BỎ QUA** việc cập nhật các file config DI cho phần Handler này.
|
||||
The MediatR library automatically scans and registers all Handlers inheriting from `IRequestHandler`. Therefore, you **ABSOLUTELY MUST SKIP** updating the DI config files for Handlers.
|
||||
|
||||
@@ -1,40 +1,40 @@
|
||||
---
|
||||
name: GenerateNTierFeature
|
||||
description: Hướng dẫn tạo một feature theo chuẩn N-Tier (bao gồm Entity, Interface, Service, Controller và cấu hình Dependency Injection).
|
||||
description: Guide to generating an N-Tier architecture feature (including Entity, Interface, Service, Controller, and Dependency Injection configuration).
|
||||
---
|
||||
|
||||
# GenerateNTierFeature Skill
|
||||
|
||||
Khi user yêu cầu tạo một feature theo luồng **N-Tier** với đầu vào là **Tên Feature** (VD: `Category`), bạn **BẮT BUỘC** phải thực hiện các bước sau để sinh ra code và file tương ứng:
|
||||
When a user requests to create a feature using the **N-Tier** flow, providing the **Feature Name** (e.g., `Category`), you **MUST** follow these steps to generate the corresponding code and files:
|
||||
|
||||
## 1. Đầu ra thư mục và file (Outputs)
|
||||
## 1. Directory and File Outputs
|
||||
|
||||
Hãy tạo các file sau với nội dung phù hợp cho {FeatureName}:
|
||||
Create the following files with appropriate content for the {FeatureName}:
|
||||
|
||||
1. **Domain Entity**
|
||||
- **Đường dẫn**: `Domain/Entities/{FeatureName}.cs`
|
||||
- **Nội dung**: Lớp Entity cơ bản định nghĩa các thuộc tính.
|
||||
- **Path**: `Domain/Entities/{FeatureName}.cs`
|
||||
- **Content**: A basic Entity class defining the properties.
|
||||
|
||||
2. **Service Interface**
|
||||
- **Đường dẫn**: `Application/Interfaces/I{FeatureName}Service.cs`
|
||||
- **Nội dung**: Các interface định nghĩa hợp đồng hàm cho {FeatureName}.
|
||||
- **Path**: `Application/Interfaces/I{FeatureName}Service.cs`
|
||||
- **Content**: Interfaces defining the method contracts for {FeatureName}.
|
||||
|
||||
3. **Service Implementation**
|
||||
- **Đường dẫn**: `Application/Services/{FeatureName}Service.cs`
|
||||
- **Nội dung**: Lớp kế thừa từ `I{FeatureName}Service`. **Yêu cầu:** Nhận Dependency Injection (DI) thông qua constructor (ví dụ: `IRepository<{FeatureName}>`).
|
||||
- **Path**: `Application/Services/{FeatureName}Service.cs`
|
||||
- **Content**: A class that inherits from `I{FeatureName}Service`. **Requirement:** Use constructor Dependency Injection (DI) to receive instances (e.g., `IRepository<{FeatureName}>`).
|
||||
|
||||
4. **WebAPI Controller**
|
||||
- **Đường dẫn**: `WebAPI/Controllers/{FeatureName}sController.cs` (Lưu ý thêm số nhiều cho tên Controller).
|
||||
- **Nội dung**: Lớp Controller. **Yêu cầu:** Phải nhận DI `I{FeatureName}Service` thông qua constructor và định nghĩa các endpoint tương ứng.
|
||||
- **Path**: `WebAPI/Controllers/{FeatureName}sController.cs` (Remember to pluralize the Controller name).
|
||||
- **Content**: The Controller class. **Requirement:** Must receive `I{FeatureName}Service` via constructor DI and define the corresponding endpoints.
|
||||
|
||||
## 2. Cấu hình Dependency Injection (BƯỚC BẮT BUỘC THỰC HIỆN)
|
||||
## 2. Dependency Injection Configuration (MANDATORY STEP)
|
||||
|
||||
⚠️ **Quan trọng:** Không giống như CQRS với MediatR ở trên, luồng N-Tier **đòi hỏi** bạn phải chèn thủ công service mới tạo vào Container IoC.
|
||||
⚠️ **Important:** Unlike CQRS with MediatR mentioned above, the N-Tier flow **REQUIRES** you to manually register the newly created service into the IoC Container.
|
||||
|
||||
Bạn **BẮT BUỘC** phải sử dụng tool để mở file cấu hình DI của project (có thể là `DependencyInjection.cs` hoặc `ServiceCollectionExtensions.cs` tùy cấu trúc thư mục) và chèn đoạn mã sau vào hàm cấu hình service liên quan:
|
||||
You **MUST** use the appropriate tool to open the project's DI configuration file (could be `DependencyInjection.cs` or `ServiceCollectionExtensions.cs` depending on the directory structure) and inject the following code block into the relevant service configuration method:
|
||||
|
||||
```csharp
|
||||
services.AddScoped<I{FeatureName}Service, {FeatureName}Service>();
|
||||
```
|
||||
|
||||
Hãy đảm bảo bạn dùng công cụ sửa file chính xác (`replace_file_content` hoặc `multi_replace_file_content`) để không làm hỏng cú pháp của file DI.
|
||||
Make sure to use an accurate file editing tool (`replace_file_content` or `multi_replace_file_content`) to avoid breaking the DI file's syntax.
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
---
|
||||
name: GenerateArchitectureTest
|
||||
description: Hướng dẫn tạo Architecture Test sử dụng NetArchTest.Rules để bảo vệ kiến trúc Clean Architecture.
|
||||
description: Guide to creating an Architecture Test using NetArchTest.Rules to protect the Clean Architecture structure.
|
||||
---
|
||||
|
||||
# GenerateArchitectureTest Skill
|
||||
|
||||
Khi user yêu cầu kiểm tra hoặc khởi tạo **Architecture Test**, bạn cần sử dụng thư viện `NetArchTest.Rules` để sinh luận kiểm điểm nhằm bảo vệ chặt chẽ cấu trúc "Clean Architecture" của dự án.
|
||||
When a user requests to verify or create an **Architecture Test**, you must use the `NetArchTest.Rules` library to generate tests that strictly protect the project's "Clean Architecture" boundaries.
|
||||
|
||||
## Mục đích
|
||||
- Ngăn chặn Dev code ẩu, import sai library/module giữa các tầng (layer).
|
||||
- Nếu vi phạm (VD: import Entity Framework vào tầng Domain), bài test này sẽ báo ĐỎ ngay lập tức lúc build code. Bằng chứng thép giúp kiến trúc được bảo vệ tuyệt đối!
|
||||
## Purpose
|
||||
- Prevent developers from writing sloppy code by incorrectly importing libraries/modules across layers.
|
||||
- If a violation occurs (e.g., importing Entity Framework into the Domain layer), this test will immediately turn RED during the build process. It acts as solid proof to ensure the architecture is fully protected!
|
||||
|
||||
## Hướng dẫn viết Test Rules
|
||||
## Writing Test Rules Guide
|
||||
|
||||
Bạn cần viết các test method (dùng `[Fact]` với xUnit hoặc NUnit) sử dụng Fluent API của `NetArchTest.Rules`. Dưới đây là các luật phổ biến bắt buộc:
|
||||
You need to write test methods (using `[Fact]` with xUnit or NUnit) that utilize the Fluent API of `NetArchTest.Rules`. Below are the mandatory common rules:
|
||||
|
||||
1. **Domain Layer Rules (Luật tầng Domain):**
|
||||
- Domain không được phụ thuộc vào bất cứ thứ gì từ Infrastructure, Application hay WebAPI.
|
||||
1. **Domain Layer Rules:**
|
||||
- The Domain must not depend on anything from Infrastructure, Application, or WebAPI.
|
||||
```csharp
|
||||
[Fact]
|
||||
public void DomainLayer_ShouldNot_HaveDependencyOn_OtherLayers()
|
||||
@@ -34,16 +34,16 @@ Bạn cần viết các test method (dùng `[Fact]` với xUnit hoặc NUnit) s
|
||||
}
|
||||
```
|
||||
|
||||
2. **Application Layer Rules (Luật tầng Application):**
|
||||
- Application Layer chỉ được phép giao tiếp với Domain, KHÔNG ĐƯỢC có dependency vào `Infrastructure` hoặc `WebAPI`.
|
||||
2. **Application Layer Rules:**
|
||||
- The Application Layer is only allowed to communicate with the Domain. It MUST NOT have dependencies on `Infrastructure` or `WebAPI`.
|
||||
|
||||
3. **Controller Rules (Luật đặt tên/vị trí API):**
|
||||
- Controller bắt buộc phải kế thừa class BaseAPIController, và có hậu tố là "Controller".
|
||||
- Không được phép truy vấn Database trực tiếp từ Controller (ngăn không cho Inject `DbContext` hay `IRepository` vào Controller, kiểm duyệt dependencies của Constructor).
|
||||
3. **Controller Rules (Naming/API Location):**
|
||||
- Controllers must inherit from the BaseAPIController class and have the suffix "Controller".
|
||||
- Direct database queries from the Controller are strictly prohibited (prevent the injection of `DbContext` or `IRepository` into the Controller; verify Constructor dependencies).
|
||||
|
||||
4. **Handler Rules (CQRS):**
|
||||
- Các Handler xử lý logic phải implements interface `IRequestHandler` và kết thúc bằng `CommandHandler` hoặc `QueryHandler`. Nó chỉ nằm ở Application Layer.
|
||||
- Business logic Handlers must implement the `IRequestHandler` interface and end with `CommandHandler` or `QueryHandler`. They must solely reside in the Application Layer.
|
||||
|
||||
## Định dạng file đầu ra
|
||||
- **Đường dẫn:** Chứa trong test project như `tests/MyNewProjectName.ArchitectureTests/`.
|
||||
- **Tên file:** Thường đặt tên theo phạm vi test như `LayerTests.cs`, `DesignConventionTests.cs`, `NamingRulesTests.cs`, v.v.
|
||||
## Output File Format
|
||||
- **Path:** Placed within the test project, e.g., `tests/MyNewProjectName.ArchitectureTests/`.
|
||||
- **File Name:** Usually named after the test scope, such as `LayerTests.cs`, `DesignConventionTests.cs`, `NamingRulesTests.cs`, etc.
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
---
|
||||
name: GenerateIntegrationTest
|
||||
description: Hướng dẫn tạo Integration Test (người thật việc thật) sử dụng WebApplicationFactory và Testcontainers.
|
||||
description: Guide to creating Integration Tests (end-to-end) using WebApplicationFactory and Testcontainers.
|
||||
---
|
||||
|
||||
# GenerateIntegrationTest Skill
|
||||
|
||||
Khi user yêu cầu tạo **Integration Test** để kiểm tra API endpoint từ đầu đến cuối, bạn cần sinh ra code theo hướng dẫn sau:
|
||||
When a user requests to create an **Integration Test** to verify API endpoints from start to finish, you need to generate the code according to the following guidelines:
|
||||
|
||||
## Mục đích
|
||||
- Test xem các mảnh ghép lắp vào ghép với nhau có chạy đúng không.
|
||||
- Flow: Client gọi API -> Middleware -> Controller -> CQRS Handler/Service -> Ghi/Đọc Database thật.
|
||||
## Purpose
|
||||
- Test whether the assembled components work correctly together.
|
||||
- Flow: Client calls API -> Middleware -> Controller -> CQRS Handler/Service -> Read/Write to a real Database.
|
||||
|
||||
## Hướng dẫn thực hiện
|
||||
## Implementation Guide
|
||||
1. **Setup WebApplicationFactory:**
|
||||
- Tự động setup `WebApplicationFactory<Program>` (tạo một test server ngay trong RAM của .NET).
|
||||
- Override cấu hình ứng dụng nếu cần thiết (ví dụ thay đổi ConnectionString trỏ sang test container).
|
||||
- Automatically setup `WebApplicationFactory<Program>` (to create an in-memory test server in .NET).
|
||||
- Override application configurations if necessary (e.g., changing the ConnectionString to point to a test container).
|
||||
|
||||
2. **Setup Testcontainers (Real Database):**
|
||||
- Sử dụng thư viện `Testcontainers` (hoặc cấu hình tương tự) để tự động spin up một Docker container chứa Database thật (ví dụ: PostgreSQL, SQL Server).
|
||||
- Đảm bảo database container này được start trước khi chạy test và tự động xóa (dispose) sau khi test xong. Tránh dùng SQLite in-memory vì hay bị lỗi vặt và không tương đương với database production.
|
||||
- Use the `Testcontainers` library (or similar configuration) to automatically spin up a Docker container containing a real Database (e.g., PostgreSQL, SQL Server).
|
||||
- Ensure this database container starts before the tests run and is automatically disposed of after the tests complete. Avoid using in-memory SQLite because it often causes minor bugs and does not accurately mimic a production database.
|
||||
|
||||
3. **Viết kịch bản Test gọi API (Arrange - Act - Assert):**
|
||||
- Tạo đối tượng `HttpClient` từ `WebApplicationFactory.CreateClient()`.
|
||||
- **Arrange:** Chuẩn bị payload data dạng JSON objects hoặc tạo trước data base records nếu là API GET/PUT/DELETE.
|
||||
- **Act:** Gọi thẳng vào API endpoint tương ứng bằng code. VD: `await client.PostAsJsonAsync("/api/v1/samples", payload);`.
|
||||
- **Assert:** Kiểm tra kết quả trả về:
|
||||
- Check HTTP Status: có phải `200 OK` hay `400 Bad Request` không.
|
||||
- Deserialize response body để check chính xác object.
|
||||
- (Tùy chọn) Query thẳng vào database container xem bản ghi đã được sinh ra/cập nhật thật chưa.
|
||||
3. **Write API Test Scenarios (Arrange - Act - Assert):**
|
||||
- Create an `HttpClient` object from `WebApplicationFactory.CreateClient()`.
|
||||
- **Arrange:** Prepare payload data as JSON objects or prepopulate database records for GET/PUT/DELETE APIs.
|
||||
- **Act:** Call the corresponding API endpoint directly via code. E.g.: `await client.PostAsJsonAsync("/api/v1/samples", payload);`.
|
||||
- **Assert:** Verify the returned results:
|
||||
- Check HTTP Status: is it `200 OK` or `400 Bad Request`?
|
||||
- Deserialize the response body to check the exact object data.
|
||||
- (Optional) Query the database container directly to confirm the record was actually created/updated.
|
||||
|
||||
## Định dạng file đầu ra
|
||||
- **Đường dẫn:** Chứa trong project test tương ứng như `tests/MyNewProjectName.IntegrationTests/Controllers/...`.
|
||||
- **Tên file:** `[ControllerName]Tests.cs` (ví dụ: `OrdersControllerTests.cs`).
|
||||
## Output File Format
|
||||
- **Path:** Placed in the corresponding test project, such as `tests/MyNewProjectName.IntegrationTests/Controllers/...`.
|
||||
- **File Name:** `[ControllerName]Tests.cs` (e.g., `OrdersControllerTests.cs`).
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
---
|
||||
name: GenerateUnitTest
|
||||
description: Hướng dẫn tạo Unit Test cô lập (tốc độ cao) sử dụng Mocking (Moq hoặc NSubstitute).
|
||||
description: Guide to creating isolated Unit Tests (high speed) using Mocking (Moq or NSubstitute).
|
||||
---
|
||||
|
||||
# GenerateUnitTest Skill
|
||||
|
||||
Khi user yêu cầu tạo **Unit Test** cho một class/method, bạn cần tuân thủ các nguyên tắc sau để sinh ra code test:
|
||||
When a user requests a **Unit Test** for a class/method, you must adhere to the following principles to generate the test code:
|
||||
|
||||
## Mục đích
|
||||
- Chỉ test duy nhất 1 class/method.
|
||||
- Bỏ qua hoàn toàn Database thật, Redis hay HTTP.
|
||||
- Tốc độ chạy cực nhanh.
|
||||
## Purpose
|
||||
- Test solely one class/method in isolation.
|
||||
- Completely ignore real Databases, Redis, or HTTP calls.
|
||||
- Extremely fast execution speed.
|
||||
|
||||
## 1. Với CQRS Handlers hoặc Services
|
||||
- **Nhận diện Dependencies:** Tự động nhận diện các Interface (ví dụ: `IRepository`, `IUnitOfWork`, `ILogger`, `IMediator`) được inject vào constructor.
|
||||
- **Tạo Mock Object:** Sử dụng thư viện Mocking (như `Moq` hoặc `NSubstitute`) để tạo instance giả của các Interface này.
|
||||
- **Kịch bản Test (Arrange - Act - Assert):**
|
||||
- **Arrange:** Cấp data giả (Mock data) cho các hàm của Interface.
|
||||
- **Act:** Gọi hàm thực thi (ví dụ `Handle()` của CQRS hoặc các method của Service).
|
||||
- **Assert:** Kiểm tra kết quả trả về, HOẶC verify xem một method của Mock object có được gọi đúng số lần không (ví dụ kiểm tra xem `_repository.AddAsync()` có được gọi không), HOẶC kiểm tra xem nó có ném ra `ValidationException` khi input sai không.
|
||||
## 1. For CQRS Handlers or Services
|
||||
- **Identify Dependencies:** Automatically identify the Interfaces (e.g., `IRepository`, `IUnitOfWork`, `ILogger`, `IMediator`) injected into the constructor.
|
||||
- **Create Mock Objects:** Use a Mocking library (like `Moq` or `NSubstitute`) to create fake instances of these Interfaces.
|
||||
- **Test Scenario (Arrange - Act - Assert):**
|
||||
- **Arrange:** Provide fake data (Mock data) for the Interface methods.
|
||||
- **Act:** Call the method being executed (e.g., `Handle()` in CQRS or Service methods).
|
||||
- **Assert:** Check the returned result, OR verify if a Mock object's method was called the correct number of times (e.g., checking if `_repository.AddAsync()` was called), OR verify if it throws a `ValidationException` given invalid input.
|
||||
|
||||
## 2. Với Domain Entities
|
||||
- **Mục tiêu:** Kiểm tra các logic kinh doanh, tính toán nội bộ của Entity.
|
||||
- **Kịch bản:**
|
||||
- Khởi tạo Entity với các trạng thái cụ thể.
|
||||
- Gọi method thay đổi trạng thái hoặc tính toán (ví dụ: `Order.CalculateTotal()`).
|
||||
- Kiểm tra xem giá trị biến đổi có đúng với quy tắc nghiệp vụ không (ví dụ: `Total` phải bằng `Price * Quantity`).
|
||||
## 2. For Domain Entities
|
||||
- **Goal:** Verify internal business logic and calculations of the Entity.
|
||||
- **Scenario:**
|
||||
- Initialize the Entity with specific states.
|
||||
- Call a method that alters the state or performs a calculation (e.g., `Order.CalculateTotal()`).
|
||||
- Verify if the modified value adheres to business rules (e.g., `Total` must equal `Price * Quantity`).
|
||||
|
||||
## Định dạng file đầu ra
|
||||
- **Đường dẫn:** Đặt trong project `tests/MyNewProjectName.UnitTests/...` (tương ứng với thư mục gốc của class bị test).
|
||||
- **Tên file:** `[ClassName]Tests.cs` (ví dụ: `CreateOrderCommandHandlerTests.cs`).
|
||||
## Output File Format
|
||||
- **Path:** Placed in the `tests/MyNewProjectName.UnitTests/...` project (corresponding to the tested class's root directory).
|
||||
- **File Name:** `[ClassName]Tests.cs` (e.g., `CreateOrderCommandHandlerTests.cs`).
|
||||
|
||||
Reference in New Issue
Block a user