mirror of
https://github.com/affaan-m/everything-claude-code.git
synced 2026-06-14 04:01:30 +08:00
translate properly docs/
This commit is contained in:
@@ -1,29 +1,27 @@
|
||||
---
|
||||
name: quarkus-patterns
|
||||
description: Quarkus 3.x LTS architecture patterns with Camel for messaging, RESTful API design, CDI services, data access with Panache, and async processing. Use for Java Quarkus backend work with event-driven architectures.
|
||||
description: Quarkus 3.x LTSアーキテクチャパターン、Camelメッセージング、RESTful API設計、CDIサービス、Panacheデータアクセス、非同期処理。イベント駆動アーキテクチャを持つJava Quarkusバックエンド作業に使用。
|
||||
origin: ECC
|
||||
---
|
||||
|
||||
> **Note / 注意**: このファイルはまだ日本語に翻訳されていません。現在は英語の原文です。翻訳PRを歓迎します。
|
||||
# Quarkus 開発パターン
|
||||
|
||||
# Quarkus Development Patterns
|
||||
Apache Camelを使用したクラウドネイティブなイベント駆動サービスのためのQuarkus 3.xアーキテクチャとAPIパターン。
|
||||
|
||||
Quarkus 3.x architecture and API patterns for cloud-native, event-driven services with Apache Camel.
|
||||
## いつアクティブにするか
|
||||
|
||||
## When to Activate
|
||||
- JAX-RSまたはRESTEasy ReactiveでREST APIを構築する
|
||||
- リソース → サービス → リポジトリレイヤーを構造化する
|
||||
- Apache CamelとRabbitMQでイベント駆動パターンを実装する
|
||||
- Hibernate Panache、キャッシング、またはリアクティブストリームを構成する
|
||||
- バリデーション、例外マッピング、またはページネーションを追加する
|
||||
- dev/staging/production環境のプロファイルを設定する(YAML構成)
|
||||
- LogContextとLogback/Logstashエンコーダーでカスタムロギング
|
||||
- CompletableFutureで非同期操作を行う
|
||||
- 条件付きフロー処理を実装する
|
||||
- GraalVMネイティブコンパイルで作業する
|
||||
|
||||
- Building REST APIs with JAX-RS or RESTEasy Reactive
|
||||
- Structuring resource → service → repository layers
|
||||
- Implementing event-driven patterns with Apache Camel and RabbitMQ
|
||||
- Configuring Hibernate Panache, caching, or reactive streams
|
||||
- Adding validation, exception mapping, or pagination
|
||||
- Setting up profiles for dev/staging/production environments (YAML config)
|
||||
- Custom logging with LogContext and Logback/Logstash encoder
|
||||
- Working with CompletableFuture for async operations
|
||||
- Implementing conditional flow processing
|
||||
- Working with GraalVM native compilation
|
||||
|
||||
## Service Layer with Multiple Dependencies (Lombok)
|
||||
## 複数依存関係を持つサービスレイヤー(Lombok)
|
||||
|
||||
```java
|
||||
@Slf4j
|
||||
@@ -43,7 +41,7 @@ public class As2ProcessingService {
|
||||
|
||||
String structureIdPartner = logContext.get(As2Constants.STRUCTURE_ID);
|
||||
|
||||
// Conditional flow logic
|
||||
// 条件付きフローロジック
|
||||
boolean isChorusFlow = Boolean.parseBoolean(logContext.get(As2Constants.CHORUS_FLOW));
|
||||
log.info("Is CHORUS_FLOW message: {}", isChorusFlow);
|
||||
|
||||
@@ -62,7 +60,7 @@ public class As2ProcessingService {
|
||||
|
||||
log.info("Invoice validation completed. Message is valid");
|
||||
|
||||
// CompletableFuture async operation
|
||||
// CompletableFuture非同期操作
|
||||
try(InputStream inputStream = Files.newInputStream(filePath)) {
|
||||
CompletableFuture<StoredDocumentInfo> documentInfoCompletableFuture =
|
||||
fileStorageService.uploadOriginalFile(inputStream,
|
||||
@@ -85,7 +83,7 @@ public class As2ProcessingService {
|
||||
documentInfo, originalFileName, structureIdPartner,
|
||||
flowProfile, invoiceValidationResult.getDocumentHash());
|
||||
|
||||
// Async Camel publishing
|
||||
// 非同期Camelパブリッシング
|
||||
businessRulesPublisher.publishAsync(payload);
|
||||
this.eventService.createSuccessEvent(payload, "BUSINESS_RULES_MESSAGE_SENT");
|
||||
}
|
||||
@@ -94,16 +92,16 @@ public class As2ProcessingService {
|
||||
}
|
||||
```
|
||||
|
||||
**Key Patterns:**
|
||||
- `@RequiredArgsConstructor` for constructor injection via Lombok
|
||||
- `@Slf4j` for Logback logging
|
||||
- Scoped LogContext with try-with-resources
|
||||
- Conditional flow logic based on runtime parameters
|
||||
- CompletableFuture with `.join()` for async operations
|
||||
- Event tracking for success/error scenarios
|
||||
- Async Camel message publishing
|
||||
**主要パターン:**
|
||||
- Lombokによるコンストラクタインジェクション用の`@RequiredArgsConstructor`
|
||||
- Logbackロギング用の`@Slf4j`
|
||||
- try-with-resourcesによるスコープ付きLogContext
|
||||
- ランタイムパラメータに基づく条件付きフローロジック
|
||||
- 非同期操作用の`.join()`付きCompletableFuture
|
||||
- 成功/エラーシナリオのイベントトラッキング
|
||||
- 非同期Camelメッセージパブリッシング
|
||||
|
||||
## Custom Logging Context Pattern (Logback)
|
||||
## カスタムロギングコンテキストパターン(Logback)
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -112,14 +110,14 @@ public class ProcessingService {
|
||||
public void processDocument(Document doc) {
|
||||
LogContext logContext = CustomLog.getCurrentContext();
|
||||
try (SafeAutoCloseable ignored = CustomLog.startScope(logContext)) {
|
||||
// Add context to all log statements
|
||||
// すべてのログステートメントにコンテキストを追加
|
||||
logContext.put("documentId", doc.getId().toString());
|
||||
logContext.put("documentType", doc.getType());
|
||||
logContext.put("userId", SecurityContext.getUserId());
|
||||
|
||||
log.info("Starting document processing");
|
||||
|
||||
// All logs within this scope inherit the context
|
||||
// このスコープ内のすべてのログはコンテキストを継承
|
||||
processInternal(doc);
|
||||
|
||||
log.info("Document processing completed");
|
||||
@@ -131,7 +129,7 @@ public class ProcessingService {
|
||||
}
|
||||
```
|
||||
|
||||
**Logback Configuration (logback.xml):**
|
||||
**Logback構成(logback.xml):**
|
||||
|
||||
```xml
|
||||
<configuration>
|
||||
@@ -149,7 +147,7 @@ public class ProcessingService {
|
||||
</configuration>
|
||||
```
|
||||
|
||||
## Event Service Pattern
|
||||
## イベントサービスパターン
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -181,13 +179,13 @@ public class EventService {
|
||||
}
|
||||
|
||||
private String serializePayload(Object payload) {
|
||||
// JSON serialization
|
||||
// JSONシリアライゼーション
|
||||
return objectMapper.writeValueAsString(payload);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Camel Message Publishing (RabbitMQ)
|
||||
## Camelメッセージパブリッシング(RabbitMQ)
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -215,7 +213,7 @@ public class BusinessRulesPublisher {
|
||||
}
|
||||
```
|
||||
|
||||
**Camel Route Configuration:**
|
||||
**Camelルート構成:**
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -242,7 +240,7 @@ public class BusinessRulesRoute extends RouteBuilder {
|
||||
}
|
||||
```
|
||||
|
||||
## Camel Direct Routes (In-Memory)
|
||||
## Camel Directルート(インメモリ)
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -250,13 +248,13 @@ public class DocumentProcessingRoute extends RouteBuilder {
|
||||
|
||||
@Override
|
||||
public void configure() {
|
||||
// Error handling
|
||||
// エラーハンドリング
|
||||
onException(ValidationException.class)
|
||||
.handled(true)
|
||||
.to("direct:validation-error-handler")
|
||||
.log("Validation error: ${exception.message}");
|
||||
|
||||
// Main processing route
|
||||
// メイン処理ルート
|
||||
from("direct:process-document")
|
||||
.routeId("document-processing")
|
||||
.log("Processing document: ${header.documentId}")
|
||||
@@ -278,7 +276,7 @@ public class DocumentProcessingRoute extends RouteBuilder {
|
||||
}
|
||||
```
|
||||
|
||||
## Camel File Processing
|
||||
## Camelファイル処理
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -308,7 +306,7 @@ public class FileMonitoringRoute extends RouteBuilder {
|
||||
}
|
||||
```
|
||||
|
||||
## Camel Bean Invocation
|
||||
## Camel Bean呼び出し
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -328,7 +326,7 @@ public class InvoiceRoute extends RouteBuilder {
|
||||
}
|
||||
```
|
||||
|
||||
## REST API Structure
|
||||
## REST API構造
|
||||
|
||||
```java
|
||||
@Path("/api/documents")
|
||||
@@ -367,7 +365,7 @@ public class DocumentResource {
|
||||
}
|
||||
```
|
||||
|
||||
## Repository Pattern (Panache Repository)
|
||||
## リポジトリパターン(Panache Repository)
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -389,7 +387,7 @@ public class DocumentRepository implements PanacheRepository<Document> {
|
||||
}
|
||||
```
|
||||
|
||||
## Service Layer with Transactions
|
||||
## トランザクション付きサービスレイヤー
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -425,7 +423,7 @@ public class DocumentService {
|
||||
}
|
||||
```
|
||||
|
||||
## DTOs and Validation
|
||||
## DTOとバリデーション
|
||||
|
||||
```java
|
||||
public record CreateDocumentRequest(
|
||||
@@ -442,7 +440,7 @@ public record DocumentResponse(Long id, String referenceNumber, DocumentStatus s
|
||||
}
|
||||
```
|
||||
|
||||
## Exception Mapping
|
||||
## 例外マッピング
|
||||
|
||||
```java
|
||||
@Provider
|
||||
@@ -473,7 +471,7 @@ public class GenericExceptionMapper implements ExceptionMapper<Exception> {
|
||||
}
|
||||
```
|
||||
|
||||
## CompletableFuture Async Operations
|
||||
## CompletableFuture非同期操作
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -512,7 +510,7 @@ public class FileStorageService {
|
||||
}
|
||||
```
|
||||
|
||||
## Caching
|
||||
## キャッシング
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -533,7 +531,7 @@ public class DocumentCacheService {
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration as YAML
|
||||
## YAML構成
|
||||
|
||||
```yaml
|
||||
# application.yml
|
||||
@@ -580,7 +578,7 @@ public class DocumentCacheService {
|
||||
username: ${RABBITMQ_USER}
|
||||
password: ${RABBITMQ_PASSWORD}
|
||||
|
||||
# Camel configuration
|
||||
# Camel構成
|
||||
camel:
|
||||
rabbitmq:
|
||||
queue:
|
||||
@@ -588,7 +586,7 @@ camel:
|
||||
invoice-processing: invoice-processing-queue
|
||||
```
|
||||
|
||||
## Health Checks
|
||||
## ヘルスチェック
|
||||
|
||||
```java
|
||||
@Readiness
|
||||
@@ -626,7 +624,7 @@ public class CamelHealthCheck implements HealthCheck {
|
||||
}
|
||||
```
|
||||
|
||||
## Dependencies (Maven)
|
||||
## 依存関係(Maven)
|
||||
|
||||
```xml
|
||||
<properties>
|
||||
@@ -657,7 +655,7 @@ public class CamelHealthCheck implements HealthCheck {
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<!-- Quarkus Core -->
|
||||
<!-- Quarkusコア -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-arc</artifactId>
|
||||
@@ -667,7 +665,7 @@ public class CamelHealthCheck implements HealthCheck {
|
||||
<artifactId>quarkus-config-yaml</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Camel Extensions -->
|
||||
<!-- Camelエクステンション -->
|
||||
<dependency>
|
||||
<groupId>org.apache.camel.quarkus</groupId>
|
||||
<artifactId>camel-quarkus-spring-rabbitmq</artifactId>
|
||||
@@ -689,7 +687,7 @@ public class CamelHealthCheck implements HealthCheck {
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Logging -->
|
||||
<!-- ロギング -->
|
||||
<dependency>
|
||||
<groupId>io.quarkiverse.logging.logback</groupId>
|
||||
<artifactId>quarkus-logging-logback</artifactId>
|
||||
@@ -701,56 +699,56 @@ public class CamelHealthCheck implements HealthCheck {
|
||||
</dependencies>
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
## ベストプラクティス
|
||||
|
||||
### Architecture
|
||||
- Use `@RequiredArgsConstructor` with Lombok for constructor injection
|
||||
- Keep service layer thin; delegate complex logic to specialized classes
|
||||
- Use Camel routes for message routing and integration patterns
|
||||
- Prefer Panache Repository pattern for data access
|
||||
### アーキテクチャ
|
||||
- コンストラクタインジェクション用にLombokの`@RequiredArgsConstructor`を使用
|
||||
- サービスレイヤーは薄く保ち、複雑なロジックは専門クラスに委譲
|
||||
- メッセージルーティングと統合パターンにCamelルートを使用
|
||||
- データアクセスにはPanache Repositoryパターンを優先
|
||||
|
||||
### Event-Driven
|
||||
- Always track operations with EventService (success/error events)
|
||||
- Use Camel `direct:` endpoints for in-memory routing
|
||||
- Use `spring-rabbitmq` component for RabbitMQ integration
|
||||
- Implement async publishing with `ProducerTemplate.asyncSendBody()`
|
||||
### イベント駆動
|
||||
- 常にEventServiceで操作をトラッキング(成功/エラーイベント)
|
||||
- インメモリルーティングにCamelの`direct:`エンドポイントを使用
|
||||
- RabbitMQ統合に`spring-rabbitmq`コンポーネントを使用
|
||||
- `ProducerTemplate.asyncSendBody()`で非同期パブリッシングを実装
|
||||
|
||||
### Logging
|
||||
- Use Logback with Logstash encoder for structured logging
|
||||
- Propagate LogContext through service calls with `SafeAutoCloseable`
|
||||
- Add contextual information to LogContext for request tracing
|
||||
- Use `@Slf4j` instead of manual logger instantiation
|
||||
### ロギング
|
||||
- 構造化ロギング用にLogstashエンコーダー付きLogbackを使用
|
||||
- `SafeAutoCloseable`でサービスコール間でLogContextを伝播
|
||||
- リクエストトレーシング用にLogContextにコンテキスト情報を追加
|
||||
- 手動ロガーインスタンス化の代わりに`@Slf4j`を使用
|
||||
|
||||
### Async Operations
|
||||
- Use CompletableFuture for non-blocking I/O operations
|
||||
- Call `.join()` when you need to wait for completion
|
||||
- Handle exceptions from CompletableFuture properly
|
||||
- Pass LogContext to async operations for tracing
|
||||
### 非同期操作
|
||||
- ノンブロッキングI/O操作にCompletableFutureを使用
|
||||
- 完了を待つ必要がある場合は`.join()`を呼び出す
|
||||
- CompletableFutureからの例外を適切にハンドリング
|
||||
- トレーシング用に非同期操作にLogContextを渡す
|
||||
|
||||
### Configuration
|
||||
- Use YAML configuration (`quarkus-config-yaml`)
|
||||
- Profile-aware configuration for dev/test/prod environments
|
||||
- Externalize sensitive configuration to environment variables
|
||||
- Use `@ConfigProperty` for type-safe config injection
|
||||
### 構成
|
||||
- YAML構成を使用(`quarkus-config-yaml`)
|
||||
- dev/test/prod環境のプロファイル対応構成
|
||||
- 機密構成を環境変数に外部化
|
||||
- 型安全な構成インジェクション用に`@ConfigProperty`を使用
|
||||
|
||||
### Validation
|
||||
- Validate at resource layer with `@Valid`
|
||||
- Use Bean Validation annotations on DTOs
|
||||
- Map exceptions to proper HTTP responses with `@Provider`
|
||||
### バリデーション
|
||||
- リソースレイヤーで`@Valid`によるバリデーション
|
||||
- DTOにBean Validationアノテーションを使用
|
||||
- `@Provider`で例外を適切なHTTPレスポンスにマッピング
|
||||
|
||||
### Transactions
|
||||
- Use `@Transactional` on service methods that modify data
|
||||
- Keep transactions short and focused
|
||||
- Avoid calling async operations within transactions
|
||||
### トランザクション
|
||||
- データを変更するサービスメソッドに`@Transactional`を使用
|
||||
- トランザクションは短く焦点を絞る
|
||||
- トランザクション内で非同期操作を呼び出さない
|
||||
|
||||
### Testing
|
||||
- Use `camel-quarkus-junit5` for route testing
|
||||
- Use AssertJ for assertions
|
||||
- Mock all external dependencies
|
||||
- Test conditional flow logic thoroughly
|
||||
### テスト
|
||||
- ルートテストに`camel-quarkus-junit5`を使用
|
||||
- アサーションにAssertJを使用
|
||||
- すべての外部依存関係をモック
|
||||
- 条件付きフローロジックを徹底的にテスト
|
||||
|
||||
### Quarkus-Specific
|
||||
- Stay on latest LTS version (3.x)
|
||||
- Use Quarkus dev mode for hot reload
|
||||
- Add health checks for production readiness
|
||||
- Test native compilation compatibility periodically
|
||||
### Quarkus固有
|
||||
- 最新のLTSバージョン(3.x)を維持
|
||||
- ホットリロード用にQuarkus devモードを使用
|
||||
- 本番準備のためにヘルスチェックを追加
|
||||
- ネイティブコンパイル互換性を定期的にテスト
|
||||
|
||||
@@ -1,32 +1,29 @@
|
||||
---
|
||||
name: quarkus-security
|
||||
description: Quarkus Security best practices for authentication, authorization, JWT/OIDC, RBAC, input validation, CSRF, secrets management, and dependency security.
|
||||
description: Quarkusセキュリティのベストプラクティス:認証、認可、JWT/OIDC、RBAC、入力バリデーション、CSRF、シークレット管理、依存関係セキュリティ。
|
||||
origin: ECC
|
||||
---
|
||||
|
||||
> **Note / 注意**: このファイルはまだ日本語に翻訳されていません。現在は英語の原文です。翻訳PRを歓迎します。
|
||||
# Quarkus セキュリティレビュー
|
||||
|
||||
# Quarkus Security Review
|
||||
認証、認可、入力バリデーションによるQuarkusアプリケーションのセキュリティベストプラクティス。
|
||||
|
||||
Best practices for securing Quarkus applications with authentication, authorization, and input validation.
|
||||
## いつアクティブにするか
|
||||
|
||||
## When to Activate
|
||||
- 認証の追加(JWT、OIDC、Basic Auth)
|
||||
- @RolesAllowedまたはSecurityIdentityによる認可の実装
|
||||
- ユーザー入力のバリデーション(Bean Validation、カスタムバリデータ)
|
||||
- CORSまたはセキュリティヘッダーの構成
|
||||
- シークレット管理(Vault、環境変数、構成ソース)
|
||||
- レート制限またはブルートフォース保護の追加
|
||||
- 依存関係のCVEスキャン
|
||||
- MicroProfile JWTまたはSmallRye JWTの使用
|
||||
|
||||
- Adding authentication (JWT, OIDC, Basic Auth)
|
||||
- Implementing authorization with @RolesAllowed or SecurityIdentity
|
||||
- Validating user input (Bean Validation, custom validators)
|
||||
- Configuring CORS or security headers
|
||||
- Managing secrets (Vault, environment variables, config sources)
|
||||
- Adding rate limiting or brute-force protection
|
||||
- Scanning dependencies for CVEs
|
||||
- Working with MicroProfile JWT or SmallRye JWT
|
||||
## 認証
|
||||
|
||||
## Authentication
|
||||
|
||||
### JWT Authentication
|
||||
### JWT認証
|
||||
|
||||
```java
|
||||
// Resource protected with JWT
|
||||
@Path("/api/protected")
|
||||
@Authenticated
|
||||
public class ProtectedResource {
|
||||
@@ -50,7 +47,7 @@ public class ProtectedResource {
|
||||
}
|
||||
```
|
||||
|
||||
Configuration (application.properties):
|
||||
構成(application.properties):
|
||||
```properties
|
||||
mp.jwt.verify.publickey.location=publicKey.pem
|
||||
mp.jwt.verify.issuer=https://auth.example.com
|
||||
@@ -61,7 +58,7 @@ quarkus.oidc.client-id=backend-service
|
||||
quarkus.oidc.credentials.secret=${OIDC_SECRET}
|
||||
```
|
||||
|
||||
### Custom Authentication Filter
|
||||
### カスタム認証フィルター
|
||||
|
||||
```java
|
||||
@Provider
|
||||
@@ -77,7 +74,6 @@ public class CustomAuthFilter implements ContainerRequestFilter {
|
||||
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
// Validate token and set SecurityIdentity
|
||||
if (!validateToken(token)) {
|
||||
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
|
||||
}
|
||||
@@ -85,15 +81,15 @@ public class CustomAuthFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
private boolean validateToken(String token) {
|
||||
// Token validation logic
|
||||
// トークンバリデーションロジック
|
||||
return true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Authorization
|
||||
## 認可
|
||||
|
||||
### Role-Based Access Control
|
||||
### ロールベースアクセス制御
|
||||
|
||||
```java
|
||||
@Path("/api/admin")
|
||||
@@ -125,7 +121,7 @@ public class UserResource {
|
||||
@Path("/{id}")
|
||||
@RolesAllowed("USER")
|
||||
public Response getUser(@PathParam("id") Long id) {
|
||||
// Check ownership
|
||||
// オーナーシップチェック
|
||||
if (!securityIdentity.hasRole("ADMIN") &&
|
||||
!isOwner(id, securityIdentity.getPrincipal().getName())) {
|
||||
return Response.status(Response.Status.FORBIDDEN).build();
|
||||
@@ -139,7 +135,7 @@ public class UserResource {
|
||||
}
|
||||
```
|
||||
|
||||
### Programmatic Security
|
||||
### プログラマティックセキュリティ
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -163,18 +159,18 @@ public class SecurityService {
|
||||
}
|
||||
```
|
||||
|
||||
## Input Validation
|
||||
## 入力バリデーション
|
||||
|
||||
### Bean Validation
|
||||
|
||||
```java
|
||||
// BAD: No validation
|
||||
// BAD: バリデーションなし
|
||||
@POST
|
||||
public Response createUser(UserDto dto) {
|
||||
return Response.ok(userService.create(dto)).build();
|
||||
}
|
||||
|
||||
// GOOD: Validated DTO
|
||||
// GOOD: バリデーション付きDTO
|
||||
public record CreateUserDto(
|
||||
@NotBlank @Size(max = 100) String name,
|
||||
@NotBlank @Email String email,
|
||||
@@ -190,7 +186,7 @@ public Response createUser(@Valid CreateUserDto dto) {
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Validators
|
||||
### カスタムバリデータ
|
||||
|
||||
```java
|
||||
@Target({ElementType.FIELD, ElementType.PARAMETER})
|
||||
@@ -209,36 +205,30 @@ public class UsernameValidator implements ConstraintValidator<ValidUsername, Str
|
||||
return value.matches("^[a-zA-Z0-9_-]{3,20}$");
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
public record CreateUserDto(
|
||||
@ValidUsername String username,
|
||||
@NotBlank @Email String email
|
||||
) {}
|
||||
```
|
||||
|
||||
## SQL Injection Prevention
|
||||
## SQLインジェクション防止
|
||||
|
||||
### Panache Active Record (Safe by Default)
|
||||
### Panache Active Record(デフォルトで安全)
|
||||
|
||||
```java
|
||||
// GOOD: Parameterized queries with Panache
|
||||
// GOOD: Panacheによるパラメータ化クエリ
|
||||
List<User> users = User.list("email = ?1 and active = ?2", email, true);
|
||||
|
||||
Optional<User> user = User.find("username", username).firstResultOptional();
|
||||
|
||||
// GOOD: Named parameters
|
||||
// GOOD: 名前付きパラメータ
|
||||
List<User> users = User.list("email = :email and age > :minAge",
|
||||
Parameters.with("email", email).and("minAge", 18));
|
||||
```
|
||||
|
||||
### Native Queries (Use Parameters)
|
||||
### ネイティブクエリ(パラメータを使用)
|
||||
|
||||
```java
|
||||
// BAD: String concatenation
|
||||
// BAD: 文字列連結
|
||||
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)
|
||||
|
||||
// GOOD: Parameterized native query
|
||||
// GOOD: パラメータ化ネイティブクエリ
|
||||
@Entity
|
||||
public class User extends PanacheEntity {
|
||||
public static List<User> findByEmailNative(String email) {
|
||||
@@ -250,7 +240,7 @@ public class User extends PanacheEntity {
|
||||
}
|
||||
```
|
||||
|
||||
## Password Hashing
|
||||
## パスワードハッシュ
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -264,33 +254,9 @@ public class PasswordService {
|
||||
return BcryptUtil.matches(plainPassword, hashedPassword);
|
||||
}
|
||||
}
|
||||
|
||||
// In service
|
||||
@ApplicationScoped
|
||||
public class UserService {
|
||||
@Inject
|
||||
PasswordService passwordService;
|
||||
|
||||
@Transactional
|
||||
public User register(CreateUserDto dto) {
|
||||
String hashedPassword = passwordService.hash(dto.password());
|
||||
User user = new User();
|
||||
user.email = dto.email();
|
||||
user.password = hashedPassword;
|
||||
user.persist();
|
||||
return user;
|
||||
}
|
||||
|
||||
public boolean authenticate(String email, String password) {
|
||||
return User.find("email", email)
|
||||
.firstResultOptional()
|
||||
.map(u -> passwordService.verify(password, u.password))
|
||||
.orElse(false);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## CORS Configuration
|
||||
## CORS構成
|
||||
|
||||
```properties
|
||||
# application.properties
|
||||
@@ -303,37 +269,22 @@ quarkus.http.cors.access-control-max-age=24H
|
||||
quarkus.http.cors.access-control-allow-credentials=true
|
||||
```
|
||||
|
||||
## Secrets Management
|
||||
## シークレット管理
|
||||
|
||||
```properties
|
||||
# application.properties - NO SECRETS HERE
|
||||
# application.properties — ここにシークレットを置かない
|
||||
|
||||
# Use environment variables
|
||||
# 環境変数を使用
|
||||
quarkus.datasource.username=${DB_USER}
|
||||
quarkus.datasource.password=${DB_PASSWORD}
|
||||
quarkus.oidc.credentials.secret=${OIDC_CLIENT_SECRET}
|
||||
|
||||
# Or use Vault
|
||||
# またはVaultを使用
|
||||
quarkus.vault.url=https://vault.example.com
|
||||
quarkus.vault.authentication.kubernetes.role=my-role
|
||||
```
|
||||
|
||||
### HashiCorp Vault Integration
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
public class SecretService {
|
||||
|
||||
@ConfigProperty(name = "api-key")
|
||||
String apiKey; // Fetched from Vault
|
||||
|
||||
public String getSecret(String key) {
|
||||
return ConfigProvider.getConfig().getValue(key, String.class);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Rate Limiting
|
||||
## レート制限
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -344,7 +295,7 @@ public class RateLimitFilter implements ContainerRequestFilter {
|
||||
public void filter(ContainerRequestContext requestContext) {
|
||||
String clientId = getClientIdentifier(requestContext);
|
||||
RateLimiter limiter = limiters.computeIfAbsent(clientId,
|
||||
k -> RateLimiter.create(100.0)); // 100 requests per second
|
||||
k -> RateLimiter.create(100.0)); // 1秒あたり100リクエスト
|
||||
|
||||
if (!limiter.tryAcquire()) {
|
||||
requestContext.abortWith(
|
||||
@@ -356,13 +307,13 @@ public class RateLimitFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
private String getClientIdentifier(ContainerRequestContext ctx) {
|
||||
// Use IP, API key, or user ID
|
||||
// IP、APIキー、またはユーザーIDを使用
|
||||
return ctx.getHeaderString("X-Forwarded-For");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Security Headers
|
||||
## セキュリティヘッダー
|
||||
|
||||
```java
|
||||
@Provider
|
||||
@@ -372,10 +323,10 @@ public class SecurityHeadersFilter implements ContainerResponseFilter {
|
||||
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
|
||||
MultivaluedMap<String, Object> headers = response.getHeaders();
|
||||
|
||||
// Prevent clickjacking
|
||||
// クリックジャッキング防止
|
||||
headers.putSingle("X-Frame-Options", "DENY");
|
||||
|
||||
// XSS protection
|
||||
// XSS保護
|
||||
headers.putSingle("X-Content-Type-Options", "nosniff");
|
||||
headers.putSingle("X-XSS-Protection", "1; mode=block");
|
||||
|
||||
@@ -389,7 +340,7 @@ public class SecurityHeadersFilter implements ContainerResponseFilter {
|
||||
}
|
||||
```
|
||||
|
||||
## Audit Logging
|
||||
## 監査ロギング
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -408,23 +359,9 @@ public class AuditService {
|
||||
user, action, resource, Instant.now());
|
||||
}
|
||||
}
|
||||
|
||||
// Usage in resource
|
||||
@Path("/api/sensitive")
|
||||
public class SensitiveResource {
|
||||
@Inject
|
||||
AuditService auditService;
|
||||
|
||||
@GET
|
||||
@RolesAllowed("ADMIN")
|
||||
public Response getData() {
|
||||
auditService.logAccess("sensitive-data", "READ");
|
||||
return Response.ok(data).build();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Dependency Security Scanning
|
||||
## 依存関係セキュリティスキャン
|
||||
|
||||
```bash
|
||||
# Maven
|
||||
@@ -433,23 +370,23 @@ mvn org.owasp:dependency-check-maven:check
|
||||
# Gradle
|
||||
./gradlew dependencyCheckAnalyze
|
||||
|
||||
# Check Quarkus extensions
|
||||
# Quarkusエクステンション確認
|
||||
quarkus extension list --installable
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
## ベストプラクティス
|
||||
|
||||
- Always use HTTPS in production
|
||||
- Enable JWT or OIDC for stateless authentication
|
||||
- Use `@RolesAllowed` for declarative authorization
|
||||
- Validate all input with Bean Validation
|
||||
- Hash passwords with BCrypt (never plaintext)
|
||||
- Store secrets in Vault or environment variables
|
||||
- Use parameterized queries to prevent SQL injection
|
||||
- Add security headers to all responses
|
||||
- Implement rate limiting for public endpoints
|
||||
- Audit sensitive operations
|
||||
- Keep dependencies updated and scan for CVEs
|
||||
- Use SecurityIdentity for programmatic checks
|
||||
- Set appropriate CORS policies
|
||||
- Test authentication and authorization paths
|
||||
- 本番環境では常にHTTPSを使用
|
||||
- ステートレス認証にJWTまたはOIDCを有効化
|
||||
- 宣言的認可に`@RolesAllowed`を使用
|
||||
- Bean Validationですべての入力をバリデーション
|
||||
- BCryptでパスワードをハッシュ(平文禁止)
|
||||
- シークレットはVaultまたは環境変数に保存
|
||||
- SQLインジェクション防止にパラメータ化クエリを使用
|
||||
- すべてのレスポンスにセキュリティヘッダーを追加
|
||||
- パブリックエンドポイントにレート制限を実装
|
||||
- 機密操作を監査
|
||||
- 依存関係を最新に保ちCVEをスキャン
|
||||
- プログラマティックチェックにSecurityIdentityを使用
|
||||
- 適切なCORSポリシーを設定
|
||||
- 認証・認可パスをテスト
|
||||
|
||||
@@ -1,36 +1,34 @@
|
||||
---
|
||||
name: quarkus-tdd
|
||||
description: Test-driven development for Quarkus 3.x LTS using JUnit 5, Mockito, REST Assured, Camel testing, and JaCoCo. Use when adding features, fixing bugs, or refactoring event-driven services.
|
||||
description: Quarkus 3.x LTS向けテスト駆動開発。JUnit 5、Mockito、REST Assured、Camelテスト、JaCoCoを使用。機能追加、バグ修正、イベント駆動サービスのリファクタリングに使用。
|
||||
origin: ECC
|
||||
---
|
||||
|
||||
> **Note / 注意**: このファイルはまだ日本語に翻訳されていません。現在は英語の原文です。翻訳PRを歓迎します。
|
||||
# Quarkus TDDワークフロー
|
||||
|
||||
# Quarkus TDD Workflow
|
||||
80%以上のカバレッジ(ユニット+統合)を目指すQuarkus 3.xサービスのTDDガイダンス。Apache Camelによるイベント駆動アーキテクチャに最適化。
|
||||
|
||||
TDD guidance for Quarkus 3.x services with 80%+ coverage (unit + integration). Optimized for event-driven architectures with Apache Camel.
|
||||
## いつ使用するか
|
||||
|
||||
## When to Use
|
||||
- 新機能またはRESTエンドポイント
|
||||
- バグ修正またはリファクタリング
|
||||
- データアクセスロジック、セキュリティルール、またはリアクティブストリームの追加
|
||||
- Apache Camelルートとイベントハンドラーのテスト
|
||||
- RabbitMQによるイベント駆動サービスのテスト
|
||||
- 条件付きフローロジックのテスト
|
||||
- CompletableFuture非同期操作のバリデーション
|
||||
- LogContext伝播のテスト
|
||||
|
||||
- New features or REST endpoints
|
||||
- Bug fixes or refactors
|
||||
- Adding data access logic, security rules, or reactive streams
|
||||
- Testing Apache Camel routes and event handlers
|
||||
- Testing event-driven services with RabbitMQ
|
||||
- Testing conditional flow logic
|
||||
- Validating CompletableFuture async operations
|
||||
- Testing LogContext propagation
|
||||
## ワークフロー
|
||||
|
||||
## Workflow
|
||||
1. まずテストを書く(失敗するはず)
|
||||
2. テストを通過する最小限のコードを実装
|
||||
3. テストがグリーンの状態でリファクタリング
|
||||
4. JaCoCoでカバレッジを強制(80%以上が目標)
|
||||
|
||||
1. Write tests first (they should fail)
|
||||
2. Implement minimal code to pass
|
||||
3. Refactor with tests green
|
||||
4. Enforce coverage with JaCoCo (80%+ target)
|
||||
## @Nestedによるユニットテスト構成
|
||||
|
||||
## Unit Tests with @Nested Organization
|
||||
|
||||
Follow this structured approach for comprehensive, readable tests:
|
||||
包括的で読みやすいテストのための構造化アプローチ:
|
||||
|
||||
```java
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -62,7 +60,7 @@ class As2ProcessingServiceTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// ARRANGE - Common test data
|
||||
// ARRANGE - 共通テストデータ
|
||||
testFilePath = Path.of("/tmp/test-invoice.xml");
|
||||
|
||||
testLogContext = new LogContext();
|
||||
@@ -119,48 +117,9 @@ class As2ProcessingServiceTest {
|
||||
|
||||
verify(eventService).createSuccessEvent(any(StoredDocumentInfo.class),
|
||||
eq("PERSISTENCE_BLOB_EVENT_TYPE"));
|
||||
verify(eventService).createSuccessEvent(any(BusinessRulesPayload.class),
|
||||
eq("BUSINESS_RULES_MESSAGE_SENT"));
|
||||
verify(businessRulesPublisher).publishAsync(any(BusinessRulesPayload.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should bypass schematron validation for CHORUS_FLOW")
|
||||
void givenChorusFlow_whenProcessFile_thenSchematronBypassed() throws Exception {
|
||||
// ARRANGE
|
||||
testLogContext.put(As2Constants.CHORUS_FLOW, "true");
|
||||
CustomLog.setCurrentContext(testLogContext);
|
||||
|
||||
when(invoiceFlowValidator.validateFlowWithConfig(
|
||||
eq(testFilePath),
|
||||
eq(ValidationFlowConfig.xsdOnly()),
|
||||
eq(EInvoiceSyntaxFormat.UBL),
|
||||
any(LogContext.class)))
|
||||
.thenReturn(validationResult);
|
||||
|
||||
when(fileStorageService.uploadOriginalFile(any(), anyLong(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(documentInfo));
|
||||
|
||||
when(documentJobService.createDocumentAndJobEntities(any(), any(), any(),
|
||||
eq(FlowProfile.EXTENDED_CTC_FR), any()))
|
||||
.thenReturn(new BusinessRulesPayload());
|
||||
|
||||
// ACT
|
||||
assertDoesNotThrow(() -> as2ProcessingService.processFile(testFilePath));
|
||||
|
||||
// ASSERT
|
||||
verify(invoiceFlowValidator).validateFlowWithConfig(
|
||||
eq(testFilePath),
|
||||
eq(ValidationFlowConfig.xsdOnly()),
|
||||
eq(EInvoiceSyntaxFormat.UBL),
|
||||
any(LogContext.class));
|
||||
|
||||
verify(documentJobService).createDocumentAndJobEntities(
|
||||
any(), any(), any(),
|
||||
eq(FlowProfile.EXTENDED_CTC_FR),
|
||||
any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should create error event when file upload fails")
|
||||
void givenUploadFailure_whenProcessFile_thenErrorEventCreated() throws Exception {
|
||||
@@ -174,7 +133,7 @@ class As2ProcessingServiceTest {
|
||||
when(invoiceFlowValidator.computeFlowProfile(any(), any()))
|
||||
.thenReturn(FlowProfile.BASIC);
|
||||
|
||||
documentInfo.setPath(""); // Blank path triggers error
|
||||
documentInfo.setPath(""); // 空パスでエラーをトリガー
|
||||
when(fileStorageService.uploadOriginalFile(any(), anyLong(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(documentInfo));
|
||||
|
||||
@@ -187,71 +146,26 @@ class As2ProcessingServiceTest {
|
||||
assertThat(exception.getMessage())
|
||||
.contains("File path is empty after upload");
|
||||
|
||||
verify(eventService).createErrorEvent(
|
||||
eq(documentInfo),
|
||||
eq("FILE_UPLOAD_FAILED"),
|
||||
contains("File path is empty"));
|
||||
|
||||
verify(businessRulesPublisher, never()).publishAsync(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle CompletableFuture.join() failure")
|
||||
void givenAsyncUploadFailure_whenProcessFile_thenExceptionThrown() throws Exception {
|
||||
// ARRANGE
|
||||
testLogContext.put(As2Constants.CHORUS_FLOW, "false");
|
||||
CustomLog.setCurrentContext(testLogContext);
|
||||
|
||||
when(invoiceFlowValidator.validateFlowWithConfig(any(), any(), any(), any()))
|
||||
.thenReturn(validationResult);
|
||||
|
||||
when(invoiceFlowValidator.computeFlowProfile(any(), any()))
|
||||
.thenReturn(FlowProfile.BASIC);
|
||||
|
||||
CompletableFuture<StoredDocumentInfo> failedFuture =
|
||||
CompletableFuture.failedFuture(new StorageException("S3 connection failed"));
|
||||
when(fileStorageService.uploadOriginalFile(any(), anyLong(), any(), any()))
|
||||
.thenReturn(failedFuture);
|
||||
|
||||
// ACT & ASSERT
|
||||
assertThrows(
|
||||
CompletionException.class,
|
||||
() -> as2ProcessingService.processFile(testFilePath)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should throw exception when file path is null")
|
||||
void givenNullFilePath_whenProcessFile_thenThrowsException() {
|
||||
// ARRANGE
|
||||
Path nullPath = null;
|
||||
|
||||
// ACT & ASSERT
|
||||
NullPointerException exception = assertThrows(
|
||||
NullPointerException.class,
|
||||
() -> as2ProcessingService.processFile(nullPath)
|
||||
);
|
||||
|
||||
verify(invoiceFlowValidator, never()).validateFlowWithConfig(any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Key Testing Patterns
|
||||
### 主要テストパターン
|
||||
|
||||
1. **@Nested Classes**: Group tests by method being tested
|
||||
2. **@DisplayName**: Provide readable test descriptions for test reports
|
||||
3. **Naming Convention**: `givenX_whenY_thenZ` for clarity
|
||||
4. **AAA Pattern**: Explicit `// ARRANGE`, `// ACT`, `// ASSERT` comments
|
||||
5. **@BeforeEach**: Setup common test data to reduce duplication
|
||||
6. **assertDoesNotThrow**: Test success scenarios without catching exceptions
|
||||
7. **assertThrows**: Test exception scenarios with message validation using AssertJ
|
||||
8. **Comprehensive Coverage**: Test happy paths, null inputs, edge cases, exceptions
|
||||
9. **Verify Interactions**: Use Mockito `verify()` to ensure methods are called correctly
|
||||
10. **Never Verify**: Use `never()` to ensure methods are NOT called in error scenarios
|
||||
1. **@Nestedクラス**: テスト対象メソッドごとにテストをグループ化
|
||||
2. **@DisplayName**: テストレポート用の読みやすい説明
|
||||
3. **命名規則**: 明確さのために`givenX_whenY_thenZ`
|
||||
4. **AAAパターン**: 明示的な`// ARRANGE`、`// ACT`、`// ASSERT`コメント
|
||||
5. **@BeforeEach**: 重複削減のための共通テストデータセットアップ
|
||||
6. **assertDoesNotThrow**: 例外をキャッチせずに成功シナリオをテスト
|
||||
7. **assertThrows**: メッセージバリデーション付きの例外シナリオテスト
|
||||
8. **包括的カバレッジ**: ハッピーパス、null入力、エッジケース、例外をテスト
|
||||
9. **インタラクション検証**: Mockitoの`verify()`でメソッドが正しく呼ばれることを確認
|
||||
10. **Never検証**: エラーシナリオでメソッドが呼ばれないことを`never()`で確認
|
||||
|
||||
## Testing Camel Routes
|
||||
## Camelルートのテスト
|
||||
|
||||
```java
|
||||
@QuarkusTest
|
||||
@@ -267,338 +181,30 @@ class BusinessRulesRouteTest {
|
||||
@InjectMock
|
||||
EventService eventService;
|
||||
|
||||
private BusinessRulesPayload testPayload;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// ARRANGE - Test data
|
||||
testPayload = new BusinessRulesPayload();
|
||||
testPayload.setDocumentId(1L);
|
||||
testPayload.setFlowProfile(FlowProfile.BASIC);
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for business-rules-publisher route")
|
||||
class BusinessRulesPublisher {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should successfully publish message to RabbitMQ")
|
||||
void givenValidPayload_whenPublish_thenMessageSentToQueue() throws Exception {
|
||||
// ARRANGE
|
||||
MockEndpoint mockRabbitMQ = camelContext.getEndpoint("mock:rabbitmq", MockEndpoint.class);
|
||||
mockRabbitMQ.expectedMessageCount(1);
|
||||
mockRabbitMQ.expectedBodiesReceived(testPayload);
|
||||
|
||||
// Replace real endpoint with mock for testing
|
||||
camelContext.getRouteController().stopRoute("business-rules-publisher");
|
||||
AdviceWith.adviceWith(camelContext, "business-rules-publisher", advice -> {
|
||||
advice.replaceFromWith("direct:business-rules-publisher");
|
||||
advice.weaveByToString(".*spring-rabbitmq.*").replace().to("mock:rabbitmq");
|
||||
});
|
||||
camelContext.getRouteController().startRoute("business-rules-publisher");
|
||||
|
||||
// ACT
|
||||
producerTemplate.sendBody("direct:business-rules-publisher", testPayload);
|
||||
|
||||
// ASSERT
|
||||
mockRabbitMQ.assertIsSatisfied(5000);
|
||||
|
||||
assertThat(mockRabbitMQ.getExchanges()).hasSize(1);
|
||||
assertThat(mockRabbitMQ.getExchanges().get(0).getIn().getBody(BusinessRulesPayload.class))
|
||||
.isEqualTo(testPayload);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle marshalling to JSON")
|
||||
void givenPayload_whenPublish_thenMarshalledToJson() throws Exception {
|
||||
// ARRANGE
|
||||
MockEndpoint mockMarshal = new MockEndpoint("mock:marshal");
|
||||
camelContext.addEndpoint("mock:marshal", mockMarshal);
|
||||
mockMarshal.expectedMessageCount(1);
|
||||
|
||||
camelContext.getRouteController().stopRoute("business-rules-publisher");
|
||||
AdviceWith.adviceWith(camelContext, "business-rules-publisher", advice -> {
|
||||
advice.weaveAddLast().to("mock:marshal");
|
||||
});
|
||||
camelContext.getRouteController().startRoute("business-rules-publisher");
|
||||
|
||||
// ACT
|
||||
producerTemplate.sendBody("direct:business-rules-publisher", testPayload);
|
||||
|
||||
// ASSERT
|
||||
mockMarshal.assertIsSatisfied(5000);
|
||||
|
||||
String body = mockMarshal.getExchanges().get(0).getIn().getBody(String.class);
|
||||
assertThat(body).contains("\"documentId\":1");
|
||||
assertThat(body).contains("\"flowProfile\":\"BASIC\"");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for document-processing route")
|
||||
class DocumentProcessing {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should route invoice to correct processor")
|
||||
void givenInvoiceType_whenProcess_thenRoutesToInvoiceProcessor() throws Exception {
|
||||
// ARRANGE
|
||||
MockEndpoint mockInvoice = camelContext.getEndpoint("mock:invoice", MockEndpoint.class);
|
||||
mockInvoice.expectedMessageCount(1);
|
||||
|
||||
camelContext.getRouteController().stopRoute("document-processing");
|
||||
AdviceWith.adviceWith(camelContext, "document-processing", advice -> {
|
||||
advice.weaveByToString(".*direct:process-invoice.*").replace().to("mock:invoice");
|
||||
});
|
||||
camelContext.getRouteController().startRoute("document-processing");
|
||||
|
||||
// ACT
|
||||
producerTemplate.sendBodyAndHeader("direct:process-document",
|
||||
testPayload, "documentType", "INVOICE");
|
||||
|
||||
// ASSERT
|
||||
mockInvoice.assertIsSatisfied(5000);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle validation errors gracefully")
|
||||
void givenValidationError_whenProcess_thenRoutesToErrorHandler() throws Exception {
|
||||
// ARRANGE
|
||||
MockEndpoint mockError = camelContext.getEndpoint("mock:error", MockEndpoint.class);
|
||||
mockError.expectedMessageCount(1);
|
||||
|
||||
camelContext.getRouteController().stopRoute("document-processing");
|
||||
AdviceWith.adviceWith(camelContext, "document-processing", advice -> {
|
||||
advice.weaveByToString(".*direct:validation-error-handler.*")
|
||||
.replace().to("mock:error");
|
||||
});
|
||||
camelContext.getRouteController().startRoute("document-processing");
|
||||
|
||||
// Mock validator to throw exception
|
||||
when(eventService.validate(any())).thenThrow(new ValidationException("Invalid document"));
|
||||
|
||||
// ACT
|
||||
producerTemplate.sendBody("direct:process-document", testPayload);
|
||||
|
||||
// ASSERT
|
||||
mockError.assertIsSatisfied(5000);
|
||||
|
||||
Exception exception = mockError.getExchanges().get(0).getException();
|
||||
assertThat(exception).isInstanceOf(ValidationException.class);
|
||||
assertThat(exception.getMessage()).contains("Invalid document");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Event Services
|
||||
|
||||
```java
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@DisplayName("EventService Unit Tests")
|
||||
class EventServiceTest {
|
||||
|
||||
@Mock
|
||||
private EventRepository eventRepository;
|
||||
|
||||
@Mock
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@InjectMocks
|
||||
private EventService eventService;
|
||||
|
||||
private BusinessRulesPayload testPayload;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@Test
|
||||
@DisplayName("Should successfully publish message to RabbitMQ")
|
||||
void givenValidPayload_whenPublish_thenMessageSentToQueue() throws Exception {
|
||||
// ARRANGE
|
||||
testPayload = new BusinessRulesPayload();
|
||||
testPayload.setDocumentId(1L);
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for createSuccessEvent")
|
||||
class CreateSuccessEvent {
|
||||
MockEndpoint mockRabbitMQ = camelContext.getEndpoint("mock:rabbitmq", MockEndpoint.class);
|
||||
mockRabbitMQ.expectedMessageCount(1);
|
||||
|
||||
@Test
|
||||
@DisplayName("Should create success event with correct attributes")
|
||||
void givenValidPayload_whenCreateSuccessEvent_thenEventPersisted() throws Exception {
|
||||
// ARRANGE
|
||||
when(objectMapper.writeValueAsString(testPayload)).thenReturn("{\"documentId\":1}");
|
||||
|
||||
// ACT
|
||||
assertDoesNotThrow(() ->
|
||||
eventService.createSuccessEvent(testPayload, "DOCUMENT_PROCESSED"));
|
||||
|
||||
// ASSERT
|
||||
verify(eventRepository).persist(argThat(event ->
|
||||
event.getType().equals("DOCUMENT_PROCESSED") &&
|
||||
event.getStatus() == EventStatus.SUCCESS &&
|
||||
event.getPayload().equals("{\"documentId\":1}") &&
|
||||
event.getTimestamp() != null
|
||||
));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should throw exception when payload is null")
|
||||
void givenNullPayload_whenCreateSuccessEvent_thenThrowsException() {
|
||||
// ARRANGE
|
||||
Object nullPayload = null;
|
||||
|
||||
// ACT & ASSERT
|
||||
IllegalArgumentException exception = assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> eventService.createSuccessEvent(nullPayload, "EVENT_TYPE")
|
||||
);
|
||||
|
||||
assertThat(exception.getMessage()).isEqualTo("Payload cannot be null");
|
||||
verify(eventRepository, never()).persist(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for createErrorEvent")
|
||||
class CreateErrorEvent {
|
||||
camelContext.getRouteController().stopRoute("business-rules-publisher");
|
||||
AdviceWith.adviceWith(camelContext, "business-rules-publisher", advice -> {
|
||||
advice.replaceFromWith("direct:business-rules-publisher");
|
||||
advice.weaveByToString(".*spring-rabbitmq.*").replace().to("mock:rabbitmq");
|
||||
});
|
||||
camelContext.getRouteController().startRoute("business-rules-publisher");
|
||||
|
||||
@Test
|
||||
@DisplayName("Should create error event with error message")
|
||||
void givenError_whenCreateErrorEvent_thenEventPersistedWithMessage() throws Exception {
|
||||
// ARRANGE
|
||||
String errorMessage = "Processing failed";
|
||||
when(objectMapper.writeValueAsString(testPayload)).thenReturn("{\"documentId\":1}");
|
||||
|
||||
// ACT
|
||||
assertDoesNotThrow(() ->
|
||||
eventService.createErrorEvent(testPayload, "PROCESSING_ERROR", errorMessage));
|
||||
|
||||
// ASSERT
|
||||
verify(eventRepository).persist(argThat(event ->
|
||||
event.getType().equals("PROCESSING_ERROR") &&
|
||||
event.getStatus() == EventStatus.ERROR &&
|
||||
event.getErrorMessage().equals(errorMessage) &&
|
||||
event.getPayload().equals("{\"documentId\":1}")
|
||||
));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@DisplayName("Should reject invalid error messages")
|
||||
@ValueSource(strings = {"", " "})
|
||||
void givenBlankErrorMessage_whenCreateErrorEvent_thenThrowsException(String blankMessage) {
|
||||
// ACT & ASSERT
|
||||
IllegalArgumentException exception = assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> eventService.createErrorEvent(testPayload, "ERROR", blankMessage)
|
||||
);
|
||||
|
||||
assertThat(exception.getMessage()).contains("Error message cannot be blank");
|
||||
}
|
||||
// ACT
|
||||
producerTemplate.sendBody("direct:business-rules-publisher", testPayload);
|
||||
|
||||
// ASSERT
|
||||
mockRabbitMQ.assertIsSatisfied(5000);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Testing CompletableFuture
|
||||
|
||||
```java
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@DisplayName("FileStorageService Unit Tests")
|
||||
class FileStorageServiceTest {
|
||||
|
||||
@Mock
|
||||
private S3Client s3Client;
|
||||
|
||||
@Mock
|
||||
private ExecutorService executorService;
|
||||
|
||||
@InjectMocks
|
||||
private FileStorageService fileStorageService;
|
||||
|
||||
private InputStream testInputStream;
|
||||
private LogContext testLogContext;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// ARRANGE
|
||||
testInputStream = new ByteArrayInputStream("test content".getBytes());
|
||||
testLogContext = new LogContext();
|
||||
testLogContext.put("traceId", "trace-123");
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for uploadOriginalFile")
|
||||
class UploadOriginalFile {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should successfully upload file and return document info")
|
||||
void givenValidFile_whenUpload_thenReturnsDocumentInfo() throws Exception {
|
||||
// ARRANGE
|
||||
when(executorService.submit(any(Callable.class))).thenAnswer(invocation -> {
|
||||
Callable<?> callable = invocation.getArgument(0);
|
||||
return CompletableFuture.completedFuture(callable.call());
|
||||
});
|
||||
|
||||
when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class)))
|
||||
.thenReturn(PutObjectResponse.builder().build());
|
||||
|
||||
// ACT
|
||||
CompletableFuture<StoredDocumentInfo> future =
|
||||
fileStorageService.uploadOriginalFile(testInputStream, 1024L,
|
||||
testLogContext, InvoiceFormat.UBL);
|
||||
|
||||
StoredDocumentInfo result = future.join();
|
||||
|
||||
// ASSERT
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.getPath()).isNotBlank();
|
||||
assertThat(result.getSize()).isEqualTo(1024L);
|
||||
assertThat(result.getUploadedAt()).isNotNull();
|
||||
|
||||
verify(s3Client).putObject(any(PutObjectRequest.class), any(RequestBody.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle S3 upload failure")
|
||||
void givenS3Failure_whenUpload_thenCompletableFutureFails() {
|
||||
// ARRANGE
|
||||
when(executorService.submit(any(Callable.class))).thenAnswer(invocation -> {
|
||||
return CompletableFuture.failedFuture(new StorageException("S3 unavailable"));
|
||||
});
|
||||
|
||||
// ACT
|
||||
CompletableFuture<StoredDocumentInfo> future =
|
||||
fileStorageService.uploadOriginalFile(testInputStream, 1024L,
|
||||
testLogContext, InvoiceFormat.UBL);
|
||||
|
||||
// ASSERT
|
||||
assertThatThrownBy(() -> future.join())
|
||||
.isInstanceOf(CompletionException.class)
|
||||
.hasCauseInstanceOf(StorageException.class)
|
||||
.hasMessageContaining("S3 unavailable");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should propagate LogContext to async operation")
|
||||
void givenLogContext_whenUpload_thenContextPropagated() throws Exception {
|
||||
// ARRANGE
|
||||
AtomicReference<LogContext> capturedContext = new AtomicReference<>();
|
||||
|
||||
when(executorService.submit(any(Callable.class))).thenAnswer(invocation -> {
|
||||
Callable<?> callable = invocation.getArgument(0);
|
||||
capturedContext.set(CustomLog.getCurrentContext());
|
||||
return CompletableFuture.completedFuture(callable.call());
|
||||
});
|
||||
|
||||
// ACT
|
||||
fileStorageService.uploadOriginalFile(testInputStream, 1024L,
|
||||
testLogContext, InvoiceFormat.UBL).join();
|
||||
|
||||
// ASSERT
|
||||
assertThat(capturedContext.get()).isNotNull();
|
||||
assertThat(capturedContext.get().get("traceId")).isEqualTo("trace-123");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Resource Layer Tests (REST Assured)
|
||||
## リソースレイヤーテスト(REST Assured)
|
||||
|
||||
```java
|
||||
@QuarkusTest
|
||||
@@ -608,27 +214,6 @@ class DocumentResourceTest {
|
||||
@InjectMock
|
||||
DocumentService documentService;
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for GET /api/documents")
|
||||
class ListDocuments {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return list of documents")
|
||||
void givenDocumentsExist_whenList_thenReturnsOk() {
|
||||
// ARRANGE
|
||||
List<Document> documents = List.of(createDocument(1L, "DOC-001"));
|
||||
when(documentService.list(0, 20)).thenReturn(documents);
|
||||
|
||||
// ACT & ASSERT
|
||||
given()
|
||||
.when().get("/api/documents")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("$.size()", is(1))
|
||||
.body("[0].referenceNumber", equalTo("DOC-001"));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for POST /api/documents")
|
||||
class CreateDocument {
|
||||
@@ -654,14 +239,12 @@ class DocumentResourceTest {
|
||||
.when().post("/api/documents")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.header("Location", containsString("/api/documents/1"))
|
||||
.body("referenceNumber", equalTo("DOC-001"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return 400 for invalid input")
|
||||
void givenInvalidRequest_whenCreate_thenReturns400() {
|
||||
// ACT & ASSERT
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
@@ -675,58 +258,12 @@ class DocumentResourceTest {
|
||||
.statusCode(400);
|
||||
}
|
||||
}
|
||||
|
||||
private Document createDocument(Long id, String referenceNumber) {
|
||||
Document document = new Document();
|
||||
document.setId(id);
|
||||
document.setReferenceNumber(referenceNumber);
|
||||
document.setStatus(DocumentStatus.PENDING);
|
||||
return document;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Integration Tests with Real Database
|
||||
## JaCoCoカバレッジ
|
||||
|
||||
```java
|
||||
@QuarkusTest
|
||||
@TestProfile(IntegrationTestProfile.class)
|
||||
@DisplayName("Document Integration Tests")
|
||||
class DocumentIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@DisplayName("Should create and retrieve document via API")
|
||||
void givenNewDocument_whenCreateAndRetrieve_thenSuccessful() {
|
||||
// ACT - Create via API
|
||||
Long id = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{
|
||||
"referenceNumber": "INT-001",
|
||||
"description": "Integration test",
|
||||
"validUntil": "2030-01-01T00:00:00Z",
|
||||
"categories": ["test"]
|
||||
}
|
||||
""")
|
||||
.when().post("/api/documents")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract().path("id");
|
||||
|
||||
// ASSERT - Retrieve via API
|
||||
given()
|
||||
.when().get("/api/documents/" + id)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("referenceNumber", equalTo("INT-001"));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Coverage with JaCoCo
|
||||
|
||||
### Maven Configuration (Complete)
|
||||
### Maven構成
|
||||
|
||||
```xml
|
||||
<plugin>
|
||||
@@ -734,29 +271,18 @@ class DocumentIntegrationTest {
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>0.8.13</version>
|
||||
<executions>
|
||||
<!-- Prepare agent for test execution -->
|
||||
<execution>
|
||||
<id>prepare-agent</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
<goals><goal>prepare-agent</goal></goals>
|
||||
</execution>
|
||||
|
||||
<!-- Generate coverage report -->
|
||||
<execution>
|
||||
<id>report</id>
|
||||
<phase>verify</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<goals><goal>report</goal></goals>
|
||||
</execution>
|
||||
|
||||
<!-- Enforce coverage thresholds -->
|
||||
<execution>
|
||||
<id>check</id>
|
||||
<goals>
|
||||
<goal>check</goal>
|
||||
</goals>
|
||||
<goals><goal>check</goal></goals>
|
||||
<configuration>
|
||||
<rules>
|
||||
<rule>
|
||||
@@ -767,11 +293,6 @@ class DocumentIntegrationTest {
|
||||
<value>COVEREDRATIO</value>
|
||||
<minimum>0.80</minimum>
|
||||
</limit>
|
||||
<limit>
|
||||
<counter>BRANCH</counter>
|
||||
<value>COVEREDRATIO</value>
|
||||
<minimum>0.70</minimum>
|
||||
</limit>
|
||||
</limits>
|
||||
</rule>
|
||||
</rules>
|
||||
@@ -781,20 +302,19 @@ class DocumentIntegrationTest {
|
||||
</plugin>
|
||||
```
|
||||
|
||||
Run tests with coverage:
|
||||
カバレッジ付きテスト実行:
|
||||
```bash
|
||||
mvn clean test
|
||||
mvn jacoco:report
|
||||
mvn jacoco:check
|
||||
|
||||
# Report at: target/site/jacoco/index.html
|
||||
# レポート: target/site/jacoco/index.html
|
||||
```
|
||||
|
||||
## Test Dependencies
|
||||
## テスト依存関係
|
||||
|
||||
```xml
|
||||
<dependencies>
|
||||
<!-- Quarkus Testing -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-junit5</artifactId>
|
||||
@@ -805,30 +325,17 @@ mvn jacoco:check
|
||||
<artifactId>quarkus-junit5-mockito</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Mockito -->
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- AssertJ (preferred over JUnit assertions) -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.24.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- REST Assured -->
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Camel Testing -->
|
||||
<dependency>
|
||||
<groupId>org.apache.camel.quarkus</groupId>
|
||||
<artifactId>camel-quarkus-junit5</artifactId>
|
||||
@@ -837,74 +344,33 @@ mvn jacoco:check
|
||||
</dependencies>
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
## ベストプラクティス
|
||||
|
||||
### Test Organization
|
||||
- Use `@Nested` classes to group tests by method being tested
|
||||
- Use `@DisplayName` for readable test descriptions visible in reports
|
||||
- Follow `givenX_whenY_thenZ` naming convention for test methods
|
||||
- Use `@BeforeEach` for common test data setup to reduce duplication
|
||||
### テスト構成
|
||||
- テスト対象メソッドごとに`@Nested`クラスでグループ化
|
||||
- レポートに表示される読みやすい説明に`@DisplayName`を使用
|
||||
- テストメソッドに`givenX_whenY_thenZ`命名規則を使用
|
||||
|
||||
### Test Structure
|
||||
- Follow AAA pattern with explicit comments (`// ARRANGE`, `// ACT`, `// ASSERT`)
|
||||
- Use `assertDoesNotThrow` for success scenarios
|
||||
- Use `assertThrows` for exception scenarios with message validation
|
||||
- Verify exception messages match expected values using AssertJ `contains()` or `isEqualTo()`
|
||||
### テスト構造
|
||||
- 明示的コメント付きAAAパターン(`// ARRANGE`、`// ACT`、`// ASSERT`)
|
||||
- 成功シナリオに`assertDoesNotThrow`を使用
|
||||
- メッセージバリデーション付き例外シナリオに`assertThrows`を使用
|
||||
|
||||
### Test Coverage
|
||||
- Test happy paths for all public methods
|
||||
- Test null input handling
|
||||
- Test edge cases (empty collections, boundary values, negative IDs, blank strings)
|
||||
- Test exception scenarios comprehensively
|
||||
- Mock all external dependencies (repositories, services, Camel endpoints)
|
||||
- Aim for 80%+ line coverage, 70%+ branch coverage
|
||||
### アサーション
|
||||
- JUnitアサーションの代わりに**常にAssertJ**(`assertThat`)を使用
|
||||
- 読みやすさのためにAssertJのfluent APIを使用
|
||||
- 例外: `assertThatThrownBy(() -> ...).isInstanceOf(...).hasMessageContaining(...)`
|
||||
|
||||
### Assertions
|
||||
- **Always use AssertJ** (`assertThat`) instead of JUnit assertions
|
||||
- Use fluent AssertJ API for readability: `assertThat(list).hasSize(3).contains(item)`
|
||||
- For exceptions: `assertThatThrownBy(() -> ...).isInstanceOf(...).hasMessageContaining(...)`
|
||||
- For collections: `extracting()`, `filteredOn()`, `containsExactly()`
|
||||
### イベント駆動テスト
|
||||
- `AdviceWith`と`MockEndpoint`でCamelルートをテスト
|
||||
- メッセージコンテンツ、ヘッダー、ルーティングロジックを検証
|
||||
- エラーハンドリングルートを個別にテスト
|
||||
- ユニットテストで外部システム(RabbitMQ、S3、データベース)をモック
|
||||
|
||||
### Testing Integration
|
||||
- Use `@QuarkusTest` for integration tests
|
||||
- Use `@InjectMock` to mock dependencies in Quarkus tests
|
||||
- Prefer REST Assured for API testing
|
||||
- Use `@TestProfile` for test-specific configuration
|
||||
### Quarkus固有
|
||||
- 最新のLTSバージョン(Quarkus 3.x)を維持
|
||||
- ネイティブコンパイル互換性を定期的にテスト
|
||||
- 異なるシナリオにQuarkusテストプロファイルを使用
|
||||
- `@MockBean`の代わりに`@InjectMock`を使用(Quarkus固有)
|
||||
|
||||
### Event-Driven Testing
|
||||
- Test Camel routes with `AdviceWith` and `MockEndpoint`
|
||||
- Use `@CamelQuarkusTest` annotation (if using standalone Camel tests)
|
||||
- Verify message content, headers, and routing logic
|
||||
- Test error handling routes separately
|
||||
- Mock external systems (RabbitMQ, S3, databases) in unit tests
|
||||
|
||||
### Camel Route Testing
|
||||
- Use `MockEndpoint` for asserting message flow
|
||||
- Use `AdviceWith` to modify routes for testing (replace endpoints with mocks)
|
||||
- Test message transformation and marshalling
|
||||
- Test exception handling and dead letter queues
|
||||
|
||||
### Testing Async Operations
|
||||
- Test CompletableFuture success and failure scenarios
|
||||
- Use `.join()` in tests to wait for async completion
|
||||
- Test exception propagation from CompletableFuture
|
||||
- Verify LogContext propagation to async operations
|
||||
|
||||
### Performance
|
||||
- Keep tests fast and isolated
|
||||
- Run tests in continuous mode: `mvn quarkus:test`
|
||||
- Use parameterized tests (`@ParameterizedTest`) for input variations
|
||||
- Build reusable test data builders or factory methods
|
||||
|
||||
### Quarkus-Specific
|
||||
- Stay on latest LTS version (Quarkus 3.x)
|
||||
- Test native compilation compatibility periodically
|
||||
- Use Quarkus test profiles for different scenarios
|
||||
- Leverage Quarkus dev services for local testing
|
||||
- Use `@InjectMock` instead of `@MockBean` (Quarkus-specific)
|
||||
|
||||
### Verification Best Practices
|
||||
- Always verify interactions on mocked dependencies
|
||||
- Use `verify(mock, never())` to ensure methods are NOT called in error scenarios
|
||||
- Use `argThat()` for complex argument matching
|
||||
- Verify the order of calls when it matters: `InOrder` from Mockito
|
||||
**覚えておいてください**: テストは高速、分離、決定的に保ちます。実装の詳細ではなく動作をテストしてください。
|
||||
|
||||
@@ -1,25 +1,23 @@
|
||||
---
|
||||
name: quarkus-verification
|
||||
description: "Verification loop for Quarkus projects: build, static analysis, tests with coverage, security scans, native compilation, and diff review before release or PR."
|
||||
description: "Quarkusプロジェクトの検証ループ: ビルド、静的解析、カバレッジ付きテスト、セキュリティスキャン、ネイティブコンパイル、リリースまたはPR前のdiffレビュー。"
|
||||
origin: ECC
|
||||
---
|
||||
|
||||
> **Note / 注意**: このファイルはまだ日本語に翻訳されていません。現在は英語の原文です。翻訳PRを歓迎します。
|
||||
# Quarkus 検証ループ
|
||||
|
||||
# Quarkus Verification Loop
|
||||
PR前、大きな変更後、デプロイ前に実行。
|
||||
|
||||
Run before PRs, after major changes, and pre-deploy.
|
||||
## いつアクティブにするか
|
||||
|
||||
## When to Activate
|
||||
- Quarkusサービスのプルリクエストを開く前
|
||||
- 大規模なリファクタリングまたは依存関係アップグレード後
|
||||
- ステージングまたは本番のデプロイ前検証
|
||||
- 完全なビルド → lint → テスト → セキュリティスキャン → ネイティブコンパイルパイプラインの実行
|
||||
- テストカバレッジが閾値を満たしていることの検証(80%以上)
|
||||
- ネイティブイメージ互換性のテスト
|
||||
|
||||
- Before opening a pull request for a Quarkus service
|
||||
- After major refactoring or dependency upgrades
|
||||
- Pre-deployment verification for staging or production
|
||||
- Running full build → lint → test → security scan → native compilation pipeline
|
||||
- Validating test coverage meets thresholds (80%+)
|
||||
- Testing native image compatibility
|
||||
|
||||
## Phase 1: Build
|
||||
## フェーズ1: ビルド
|
||||
|
||||
```bash
|
||||
# Maven
|
||||
@@ -29,17 +27,17 @@ mvn clean verify -DskipTests
|
||||
./gradlew clean assemble -x test
|
||||
```
|
||||
|
||||
If build fails, stop and fix compilation errors.
|
||||
ビルドが失敗した場合、停止してコンパイルエラーを修正。
|
||||
|
||||
## Phase 2: Static Analysis
|
||||
## フェーズ2: 静的解析
|
||||
|
||||
### Checkstyle, PMD, SpotBugs (Maven)
|
||||
### Checkstyle、PMD、SpotBugs(Maven)
|
||||
|
||||
```bash
|
||||
mvn checkstyle:check pmd:check spotbugs:check
|
||||
```
|
||||
|
||||
### SonarQube (if configured)
|
||||
### SonarQube(構成されている場合)
|
||||
|
||||
```bash
|
||||
mvn sonar:sonar \
|
||||
@@ -48,33 +46,33 @@ mvn sonar:sonar \
|
||||
-Dsonar.login=${SONAR_TOKEN}
|
||||
```
|
||||
|
||||
### Common Issues to Address
|
||||
### 対処すべき一般的な問題
|
||||
|
||||
- Unused imports or variables
|
||||
- Complex methods (high cyclomatic complexity)
|
||||
- Potential null pointer dereferences
|
||||
- Security issues flagged by SpotBugs
|
||||
- 未使用のimportまたは変数
|
||||
- 複雑なメソッド(高い循環的複雑度)
|
||||
- 潜在的なnullポインター参照
|
||||
- SpotBugsが検出したセキュリティ問題
|
||||
|
||||
## Phase 3: Tests + Coverage
|
||||
## フェーズ3: テスト + カバレッジ
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
# すべてのテストを実行
|
||||
mvn clean test
|
||||
|
||||
# Generate coverage report
|
||||
# カバレッジレポートを生成
|
||||
mvn jacoco:report
|
||||
|
||||
# Enforce coverage threshold (80%)
|
||||
# カバレッジ閾値を強制(80%)
|
||||
mvn jacoco:check
|
||||
|
||||
# Or with Gradle
|
||||
# またはGradleで
|
||||
./gradlew test jacocoTestReport jacocoTestCoverageVerification
|
||||
```
|
||||
|
||||
### Test Categories
|
||||
### テストカテゴリ
|
||||
|
||||
#### Unit Tests
|
||||
Test service logic with mocked dependencies:
|
||||
#### ユニットテスト
|
||||
モック化された依存関係でサービスロジックをテスト:
|
||||
|
||||
```java
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -99,8 +97,8 @@ class UserServiceTest {
|
||||
}
|
||||
```
|
||||
|
||||
#### Integration Tests
|
||||
Test with real database (Testcontainers):
|
||||
#### 統合テスト
|
||||
実データベース(Testcontainers)でテスト:
|
||||
|
||||
```java
|
||||
@QuarkusTest
|
||||
@@ -126,8 +124,8 @@ class UserRepositoryIntegrationTest {
|
||||
}
|
||||
```
|
||||
|
||||
#### API Tests
|
||||
Test REST endpoints with REST Assured:
|
||||
#### APIテスト
|
||||
REST AssuredでRESTエンドポイントをテスト:
|
||||
|
||||
```java
|
||||
@QuarkusTest
|
||||
@@ -160,124 +158,77 @@ class UserResourceTest {
|
||||
}
|
||||
```
|
||||
|
||||
### Coverage Report
|
||||
### カバレッジレポート
|
||||
|
||||
Check `target/site/jacoco/index.html` for detailed coverage:
|
||||
- Overall line coverage (target: 80%+)
|
||||
- Branch coverage (target: 70%+)
|
||||
- Identify uncovered critical paths
|
||||
詳細カバレッジは`target/site/jacoco/index.html`を確認:
|
||||
- 全体行カバレッジ(目標: 80%以上)
|
||||
- ブランチカバレッジ(目標: 70%以上)
|
||||
- カバーされていない重要パスを特定
|
||||
|
||||
## Phase 4: Security Scanning
|
||||
## フェーズ4: セキュリティスキャン
|
||||
|
||||
### Dependency Vulnerabilities (Maven)
|
||||
### 依存関係脆弱性(Maven)
|
||||
|
||||
```bash
|
||||
mvn org.owasp:dependency-check-maven:check
|
||||
```
|
||||
|
||||
Review `target/dependency-check-report.html` for CVEs.
|
||||
CVEについて`target/dependency-check-report.html`を確認。
|
||||
|
||||
### Quarkus Security Audit
|
||||
### Quarkusセキュリティ監査
|
||||
|
||||
```bash
|
||||
# Check vulnerable extensions
|
||||
# 脆弱なエクステンションを確認
|
||||
mvn quarkus:audit
|
||||
|
||||
# List all extensions
|
||||
# すべてのエクステンションをリスト
|
||||
mvn quarkus:list-extensions
|
||||
```
|
||||
|
||||
### OWASP ZAP (API Security Testing)
|
||||
### 一般的なセキュリティチェック
|
||||
|
||||
- [ ] すべてのシークレットが環境変数に(コード内ではなく)
|
||||
- [ ] すべてのエンドポイントで入力バリデーション
|
||||
- [ ] 認証/認可が構成済み
|
||||
- [ ] CORSが適切に構成済み
|
||||
- [ ] セキュリティヘッダーが設定済み
|
||||
- [ ] パスワードがBCryptでハッシュ済み
|
||||
- [ ] SQLインジェクション保護(パラメータ化クエリ)
|
||||
- [ ] パブリックエンドポイントでレート制限
|
||||
|
||||
## フェーズ5: ネイティブコンパイル
|
||||
|
||||
GraalVMネイティブイメージ互換性をテスト:
|
||||
|
||||
```bash
|
||||
docker run -t owasp/zap2docker-stable zap-api-scan.py \
|
||||
-t http://localhost:8080/q/openapi \
|
||||
-f openapi
|
||||
```
|
||||
|
||||
### Common Security Checks
|
||||
|
||||
- [ ] All secrets in environment variables (not in code)
|
||||
- [ ] Input validation on all endpoints
|
||||
- [ ] Authentication/authorization configured
|
||||
- [ ] CORS properly configured
|
||||
- [ ] Security headers set
|
||||
- [ ] Passwords hashed with BCrypt
|
||||
- [ ] SQL injection protection (parameterized queries)
|
||||
- [ ] Rate limiting on public endpoints
|
||||
|
||||
## Phase 5: Native Compilation
|
||||
|
||||
Test GraalVM native image compatibility:
|
||||
|
||||
```bash
|
||||
# Build native executable
|
||||
# ネイティブ実行可能ファイルをビルド
|
||||
mvn package -Dnative
|
||||
|
||||
# Or with container
|
||||
# またはコンテナで
|
||||
mvn package -Dnative -Dquarkus.native.container-build=true
|
||||
|
||||
# Test native executable
|
||||
# ネイティブ実行可能ファイルをテスト
|
||||
./target/*-runner
|
||||
|
||||
# Run basic smoke tests
|
||||
# 基本的なスモークテストを実行
|
||||
curl http://localhost:8080/q/health/live
|
||||
curl http://localhost:8080/q/health/ready
|
||||
```
|
||||
|
||||
### Native Image Troubleshooting
|
||||
### ネイティブイメージトラブルシューティング
|
||||
|
||||
Common issues:
|
||||
- **Reflection**: Add reflection config for dynamic classes
|
||||
- **Resources**: Include resources with `quarkus.native.resources.includes`
|
||||
- **JNI**: Register JNI classes if using native libraries
|
||||
一般的な問題:
|
||||
- **Reflection**: 動的クラス用のreflection構成を追加
|
||||
- **Resources**: `quarkus.native.resources.includes`でリソースを含める
|
||||
- **JNI**: ネイティブライブラリ使用時にJNIクラスを登録
|
||||
|
||||
Example reflection config:
|
||||
例のreflection構成:
|
||||
```java
|
||||
@RegisterForReflection(targets = {MyDynamicClass.class})
|
||||
public class ReflectionConfiguration {}
|
||||
```
|
||||
|
||||
## Phase 6: Performance Testing
|
||||
|
||||
### Load Testing with K6
|
||||
|
||||
```javascript
|
||||
// load-test.js
|
||||
import http from 'k6/http';
|
||||
import { check } from 'k6';
|
||||
|
||||
export const options = {
|
||||
stages: [
|
||||
{ duration: '30s', target: 50 },
|
||||
{ duration: '1m', target: 100 },
|
||||
{ duration: '30s', target: 0 },
|
||||
],
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const res = http.get('http://localhost:8080/api/markets');
|
||||
check(res, {
|
||||
'status is 200': (r) => r.status === 200,
|
||||
'response time < 200ms': (r) => r.timings.duration < 200,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Run:
|
||||
```bash
|
||||
k6 run load-test.js
|
||||
```
|
||||
|
||||
### Metrics to Monitor
|
||||
|
||||
- Response time (p50, p95, p99)
|
||||
- Throughput (requests/sec)
|
||||
- Error rate
|
||||
- Memory usage
|
||||
- CPU usage
|
||||
|
||||
## Phase 7: Health Checks
|
||||
## フェーズ6: ヘルスチェック
|
||||
|
||||
```bash
|
||||
# Liveness
|
||||
@@ -286,198 +237,78 @@ curl http://localhost:8080/q/health/live
|
||||
# Readiness
|
||||
curl http://localhost:8080/q/health/ready
|
||||
|
||||
# All health checks
|
||||
# すべてのヘルスチェック
|
||||
curl http://localhost:8080/q/health
|
||||
|
||||
# Metrics (if enabled)
|
||||
# メトリクス(有効な場合)
|
||||
curl http://localhost:8080/q/metrics
|
||||
```
|
||||
|
||||
Expected responses:
|
||||
```json
|
||||
{
|
||||
"status": "UP",
|
||||
"checks": [
|
||||
{
|
||||
"name": "Database connection",
|
||||
"status": "UP"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
## 検証チェックリスト
|
||||
|
||||
## Phase 8: Container Image Build
|
||||
### コード品質
|
||||
- [ ] ビルドが警告なしで通過
|
||||
- [ ] 静的解析クリーン(高/中の問題なし)
|
||||
- [ ] コードがチーム規約に従う
|
||||
- [ ] PRにコメントアウトされたコードやTODOがない
|
||||
|
||||
```bash
|
||||
# Build container image
|
||||
mvn package -Dquarkus.container-image.build=true
|
||||
### テスト
|
||||
- [ ] すべてのテストが通過
|
||||
- [ ] コードカバレッジ ≥ 80%
|
||||
- [ ] 実データベースとの統合テスト
|
||||
- [ ] セキュリティテストが通過
|
||||
- [ ] パフォーマンスが許容範囲内
|
||||
|
||||
# Or with specific registry
|
||||
mvn package \
|
||||
-Dquarkus.container-image.build=true \
|
||||
-Dquarkus.container-image.registry=docker.io \
|
||||
-Dquarkus.container-image.group=myorg \
|
||||
-Dquarkus.container-image.tag=1.0.0
|
||||
### セキュリティ
|
||||
- [ ] 依存関係脆弱性なし
|
||||
- [ ] 認証/認可がテスト済み
|
||||
- [ ] 入力バリデーション完了
|
||||
- [ ] ソースコードにシークレットなし
|
||||
- [ ] セキュリティヘッダーが構成済み
|
||||
|
||||
# Test container
|
||||
docker run -p 8080:8080 myorg/my-quarkus-app:1.0.0
|
||||
```
|
||||
### デプロイメント
|
||||
- [ ] ネイティブコンパイル成功
|
||||
- [ ] コンテナイメージがビルド可能
|
||||
- [ ] ヘルスチェックが正しく応答
|
||||
- [ ] ターゲット環境で構成が有効
|
||||
|
||||
### Container Security Scan
|
||||
|
||||
```bash
|
||||
# Trivy
|
||||
trivy image myorg/my-quarkus-app:1.0.0
|
||||
|
||||
# Grype
|
||||
grype myorg/my-quarkus-app:1.0.0
|
||||
```
|
||||
|
||||
## Phase 9: Configuration Validation
|
||||
|
||||
```bash
|
||||
# Check all configuration properties
|
||||
mvn quarkus:info
|
||||
|
||||
# List all config sources
|
||||
curl http://localhost:8080/q/dev/io.quarkus.quarkus-vertx-http/config
|
||||
```
|
||||
|
||||
### Environment-Specific Checks
|
||||
|
||||
- [ ] Database URLs configured per environment
|
||||
- [ ] Secrets externalized (Vault, env vars)
|
||||
- [ ] Logging levels appropriate
|
||||
- [ ] CORS origins set correctly
|
||||
- [ ] Rate limiting configured
|
||||
- [ ] Monitoring/tracing enabled
|
||||
|
||||
## Phase 10: Documentation Review
|
||||
|
||||
- [ ] OpenAPI/Swagger docs up to date (`/q/swagger-ui`)
|
||||
- [ ] README has setup instructions
|
||||
- [ ] API changes documented
|
||||
- [ ] Migration guide for breaking changes
|
||||
- [ ] Configuration properties documented
|
||||
|
||||
Generate OpenAPI spec:
|
||||
```bash
|
||||
curl http://localhost:8080/q/openapi -o openapi.json
|
||||
```
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
### Code Quality
|
||||
- [ ] Build passes without warnings
|
||||
- [ ] Static analysis clean (no high/medium issues)
|
||||
- [ ] Code follows team conventions
|
||||
- [ ] No commented-out code or TODOs in PR
|
||||
|
||||
### Testing
|
||||
- [ ] All tests pass
|
||||
- [ ] Code coverage ≥ 80%
|
||||
- [ ] Integration tests with real database
|
||||
- [ ] Security tests pass
|
||||
- [ ] Performance within acceptable limits
|
||||
|
||||
### Security
|
||||
- [ ] No dependency vulnerabilities
|
||||
- [ ] Authentication/authorization tested
|
||||
- [ ] Input validation complete
|
||||
- [ ] Secrets not in source code
|
||||
- [ ] Security headers configured
|
||||
|
||||
### Deployment
|
||||
- [ ] Native compilation successful
|
||||
- [ ] Container image builds
|
||||
- [ ] Health checks respond correctly
|
||||
- [ ] Configuration valid for target environment
|
||||
|
||||
### Native Image
|
||||
- [ ] Native executable builds
|
||||
- [ ] Native tests pass
|
||||
- [ ] Startup time < 100ms
|
||||
- [ ] Memory footprint acceptable
|
||||
|
||||
## Automated Verification Script
|
||||
## 自動検証スクリプト
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "=== Phase 1: Build ==="
|
||||
echo "=== フェーズ1: ビルド ==="
|
||||
mvn clean verify -DskipTests
|
||||
|
||||
echo "=== Phase 2: Static Analysis ==="
|
||||
echo "=== フェーズ2: 静的解析 ==="
|
||||
mvn checkstyle:check pmd:check spotbugs:check
|
||||
|
||||
echo "=== Phase 3: Tests + Coverage ==="
|
||||
echo "=== フェーズ3: テスト + カバレッジ ==="
|
||||
mvn test jacoco:report jacoco:check
|
||||
|
||||
echo "=== Phase 4: Security Scan ==="
|
||||
echo "=== フェーズ4: セキュリティスキャン ==="
|
||||
mvn org.owasp:dependency-check-maven:check
|
||||
|
||||
echo "=== Phase 5: Native Compilation ==="
|
||||
echo "=== フェーズ5: ネイティブコンパイル ==="
|
||||
mvn package -Dnative -Dquarkus.native.container-build=true
|
||||
|
||||
echo "=== All Phases Complete ==="
|
||||
echo "Review reports:"
|
||||
echo " - Coverage: target/site/jacoco/index.html"
|
||||
echo " - Security: target/dependency-check-report.html"
|
||||
echo " - Native: target/*-runner"
|
||||
echo "=== 全フェーズ完了 ==="
|
||||
echo "レポートを確認:"
|
||||
echo " - カバレッジ: target/site/jacoco/index.html"
|
||||
echo " - セキュリティ: target/dependency-check-report.html"
|
||||
echo " - ネイティブ: target/*-runner"
|
||||
```
|
||||
|
||||
## CI/CD Integration
|
||||
## ベストプラクティス
|
||||
|
||||
### GitHub Actions Example
|
||||
|
||||
```yaml
|
||||
name: Verification
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@v3
|
||||
with:
|
||||
java-version: '21'
|
||||
distribution: 'temurin'
|
||||
|
||||
- name: Cache Maven packages
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/.m2
|
||||
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
|
||||
|
||||
- name: Build
|
||||
run: mvn clean verify -DskipTests
|
||||
|
||||
- name: Test with Coverage
|
||||
run: mvn test jacoco:report jacoco:check
|
||||
|
||||
- name: Security Scan
|
||||
run: mvn org.owasp:dependency-check-maven:check
|
||||
|
||||
- name: Upload Coverage
|
||||
uses: codecov/codecov-action@v3
|
||||
with:
|
||||
files: target/site/jacoco/jacoco.xml
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
- Run verification loop before every PR
|
||||
- Automate in CI/CD pipeline
|
||||
- Fix issues immediately; don't accumulate debt
|
||||
- Keep coverage above 80%
|
||||
- Update dependencies regularly
|
||||
- Test native compilation periodically
|
||||
- Monitor performance trends
|
||||
- Document breaking changes
|
||||
- Review security scan results
|
||||
- Validate configuration for each environment
|
||||
- すべてのPR前に検証ループを実行
|
||||
- CI/CDパイプラインで自動化
|
||||
- 問題を即座に修正し、技術的負債を蓄積しない
|
||||
- カバレッジを80%以上に維持
|
||||
- 依存関係を定期的に更新
|
||||
- ネイティブコンパイルを定期的にテスト
|
||||
- パフォーマンストレンドを監視
|
||||
- 破壊的変更を文書化
|
||||
- セキュリティスキャン結果をレビュー
|
||||
- 各環境の構成を検証
|
||||
|
||||
Reference in New Issue
Block a user