diff --git a/.forge/role-aa-live-1522-001-attempt-1-run-d418939310a8.md b/.forge/role-aa-live-1522-001-attempt-1-run-d418939310a8.md deleted file mode 100644 index 70bf647..0000000 --- a/.forge/role-aa-live-1522-001-attempt-1-run-d418939310a8.md +++ /dev/null @@ -1,3 +0,0 @@ -# role-aa-live-1522-001-attempt-1-run-d418939310a8 - -Forge 이슈 작업 브랜치 `forge/role-aa-live-1522-001-attempt-1-run-d418939310a8`. diff --git a/.forge/role-developer-live-1522-001-attempt-1-run-6a48084c658b.md b/.forge/role-developer-live-1522-001-attempt-1-run-6a48084c658b.md deleted file mode 100644 index ae2040e..0000000 --- a/.forge/role-developer-live-1522-001-attempt-1-run-6a48084c658b.md +++ /dev/null @@ -1,3 +0,0 @@ -# role-developer-live-1522-001-attempt-1-run-6a48084c658b - -Forge 이슈 작업 브랜치 `forge/role-developer-live-1522-001-attempt-1-run-6a48084c658b`. diff --git a/.forge/role-pm-live-1522-001-attempt-1-run-3980dffa3ff4.md b/.forge/role-pm-live-1522-001-attempt-1-run-3980dffa3ff4.md deleted file mode 100644 index adc3e67..0000000 --- a/.forge/role-pm-live-1522-001-attempt-1-run-3980dffa3ff4.md +++ /dev/null @@ -1,3 +0,0 @@ -# role-pm-live-1522-001-attempt-1-run-3980dffa3ff4 - -Forge 이슈 작업 브랜치 `forge/role-pm-live-1522-001-attempt-1-run-3980dffa3ff4`. diff --git a/.forge/role-ta-live-1522-001-attempt-2-run-af8c24005cdb.md b/.forge/role-ta-live-1522-001-attempt-2-run-af8c24005cdb.md new file mode 100644 index 0000000..658c675 --- /dev/null +++ b/.forge/role-ta-live-1522-001-attempt-2-run-af8c24005cdb.md @@ -0,0 +1,3 @@ +# role-ta-live-1522-001-attempt-2-run-af8c24005cdb + +Forge 이슈 작업 브랜치 `forge/role-ta-live-1522-001-attempt-2-run-af8c24005cdb`. diff --git a/audit/role-aa/evidence-inventory.json b/audit/role-aa/evidence-inventory.json deleted file mode 100644 index 81485b0..0000000 --- a/audit/role-aa/evidence-inventory.json +++ /dev/null @@ -1,315 +0,0 @@ -{ - "documentId": "EVID-INV-ROLE-AA-001", - "version": "1.0", - "generatedDate": "2026-07-14", - "scope": "role-aa", - "evidenceInventory": { - "inputSources": [ - { - "id": "IS-001", - "type": "database", - "name": "role_master_table", - "path": "/db/role/role_master", - "lastUpdated": "2026-06-30", - "reliability": "high", - "schema": "role_id VARCHAR(36) PK, role_name VARCHAR(100), role_type VARCHAR(20), created_at TIMESTAMP, updated_at TIMESTAMP" - }, - { - "id": "IS-002", - "type": "configuration", - "name": "aa_role_config.xml", - "path": "/config/role/aa_role_config.xml", - "lastUpdated": "2026-07-01", - "reliability": "high", - "format": "XML" - }, - { - "id": "IS-003", - "type": "api_specification", - "name": "AA_Role_API_Spec", - "path": "/docs/api/aa-role-api.yaml", - "lastUpdated": "2026-06-15", - "reliability": "medium", - "format": "OpenAPI 3.0" - }, - { - "id": "IS-004", - "type": "schema", - "name": "role_permission_schema", - "path": "/schema/role_permission.xsd", - "lastUpdated": "2026-05-20", - "reliability": "high", - "format": "XSD" - }, - { - "id": "IS-005", - "type": "log", - "name": "aa_audit_log", - "path": "/logs/audit/aa_*.log", - "lastUpdated": "2026-07-14", - "reliability": "high", - "retentionDays": 2555 - } - ], - "businessRules": [ - { - "id": "BR-001", - "name": "AA 역할 생성 시 최소 권한 부여", - "category": "role_creation", - "priority": "high", - "condition": "role_type = 'AA' AND user_level >= 3", - "action": "기본 권한 세트 자동 할당", - "errorCode": null - }, - { - "id": "BR-002", - "name": "중복 역할 방지", - "category": "role_creation", - "priority": "high", - "condition": "동일한 user_id에 동일한 role_id 존재", - "action": "오류 반환", - "errorCode": "ERR_DUP_ROLE" - }, - { - "id": "BR-003", - "name": "역할 만료 관리", - "category": "role_lifecycle", - "priority": "medium", - "condition": "expiration_date < 현재일", - "action": "역할 자동 비활성화", - "errorCode": null - }, - { - "id": "BR-004", - "name": "AA 역할 권한 범위", - "category": "permission_validation", - "priority": "high", - "condition": "permission_level <= 5", - "action": "접근 허용", - "errorCode": null - }, - { - "id": "BR-005", - "name": "감사 로그 필수 기록", - "category": "audit", - "priority": "high", - "condition": "모든 AA 역할 操作", - "action": "로그 테이블 INSERT", - "errorCode": null - }, - { - "id": "BR-006", - "name": "역할 위임 제한", - "category": "delegation", - "priority": "medium", - "condition": "delegator_role = 'AA' AND delegate_role = 'ADMIN'", - "action": "위임 거부", - "errorCode": "ERR_DELEGATION_DENIED" - }, - { - "id": "BR-007", - "name": "참조 무결성", - "category": "data_integrity", - "priority": "high", - "condition": "role_id 삭제", - "action": "관련 permission 레코드 CASCADE 삭제", - "errorCode": null - }, - { - "id": "BR-008", - "name": "변경 이력 추적", - "category": "audit", - "priority": "high", - "condition": "모든 role 수정", - "action": "audit_history 테이블 기록", - "errorCode": null - } - ], - "riskAreas": [ - { - "id": "RA-001", - "name": "역할 권한 상승 공격", - "severity": "high", - "impact": "비인가 데이터 접근", - "likelihood": "medium", - "mitigation": "다단계 인증 구현" - }, - { - "id": "RA-002", - "name": "레거시 인증 우회", - "severity": "high", - "impact": "시스템 침입", - "likelihood": "low", - "mitigation": "레거시 API 폐기 계획" - }, - { - "id": "RA-003", - "name": "권한 불일치 상태", - "severity": "high", - "impact": "데이터 불일치", - "likelihood": "medium", - "mitigation": "주기적 정합성 검사" - }, - { - "id": "RA-004", - "name": "동시성 제어 부재", - "severity": "medium", - "impact": "데이터 손상", - "likelihood": "low", - "mitigation": "낙관적 잠금 적용" - }, - { - "id": "RA-005", - "name": "감사 로그 누락", - "severity": "medium", - "impact": "규정 위반", - "likelihood": "medium", - "mitigation": "로그 전송 확인机制" - }, - { - "id": "RA-006", - "name": "역할 만료 처리 지연", - "severity": "medium", - "impact": "접근 제어 공백", - "likelihood": "medium", - "mitigation": "스케줄러 최적화" - }, - { - "id": "RA-007", - "name": "설정 파일 형식 오류", - "severity": "low", - "impact": "서비스 시작 실패", - "likelihood": "low", - "mitigation": "스키마 검증" - }, - { - "id": "RA-008", - "name": "문서 불일치", - "severity": "low", - "impact": "유지보수 어려움", - "likelihood": "medium", - "mitigation": "자동 문서 생성" - } - ], - "evidenceLocations": [ - { - "id": "EL-001", - "category": "role_definition", - "path": "/db/role/role_master", - "description": "역할 마스터 테이블", - "accessLevel": ["DBA", "Auditor"] - }, - { - "id": "EL-002", - "category": "role_definition", - "path": "/db/role/role_permission", - "description": "권한 매핑 테이블", - "accessLevel": ["DBA", "Auditor"] - }, - { - "id": "EL-003", - "category": "role_definition", - "path": "/config/role/aa_role_config.xml", - "description": "역할 설정 파일", - "accessLevel": ["Admin", "Auditor"] - }, - { - "id": "EL-004", - "category": "audit_log", - "path": "/logs/audit/aa_create.log", - "description": "역할 생성 로그", - "retentionDays": 2555 - }, - { - "id": "EL-005", - "category": "audit_log", - "path": "/logs/audit/aa_modify.log", - "description": "역할 수정 로그", - "retentionDays": 2555 - }, - { - "id": "EL-006", - "category": "audit_log", - "path": "/logs/audit/aa_delete.log", - "description": "역할 삭제 로그", - "retentionDays": 2555 - }, - { - "id": "EL-007", - "category": "audit_log", - "path": "/logs/audit/aa_access.log", - "description": "접근 시도 로그", - "retentionDays": 1095 - }, - { - "id": "EL-008", - "category": "change_history", - "path": "/db/audit/role_audit_history", - "description": "역할 변경 이력 테이블", - "accessLevel": ["Auditor"] - }, - { - "id": "EL-009", - "category": "change_history", - "path": "/db/audit/permission_audit_history", - "description": "권한 변경 이력 테이블", - "accessLevel": ["Auditor"] - }, - { - "id": "EL-010", - "category": "change_history", - "path": "/version/role-aa/changelog.md", - "description": "역할 변경 이력 문서", - "accessLevel": ["All"] - }, - { - "id": "EL-011", - "category": "test_evidence", - "path": "/test/role-aa/unit", - "description": "단위 테스트", - "testType": "Unit" - }, - { - "id": "EL-012", - "category": "test_evidence", - "path": "/test/role-aa/integration", - "description": "통합 테스트", - "testType": "Integration" - }, - { - "id": "EL-013", - "category": "test_evidence", - "path": "/test/role-aa/security", - "description": "보안 테스트", - "testType": "Security" - } - ] - }, - "transitionChecklist": [ - { - "item": "입력 소스 데이터 마이그레이션 계획 수립", - "status": "pending", - "priority": "high" - }, - { - "item": "업무 규칙 호환성 검증 완료", - "status": "pending", - "priority": "high" - }, - { - "item": "위험 영역 보안 감사 완료", - "status": "pending", - "priority": "high" - }, - { - "item": "증적 위치 접근 권한 검증 완료", - "status": "pending", - "priority": "medium" - }, - { - "item": "롤백 계획 수립 및 테스트 완료", - "status": "pending", - "priority": "high" - } - ] -} diff --git a/audit/role-aa/legacy-analysis-smoke-report.md b/audit/role-aa/legacy-analysis-smoke-report.md deleted file mode 100644 index 81b25ec..0000000 --- a/audit/role-aa/legacy-analysis-smoke-report.md +++ /dev/null @@ -1,146 +0,0 @@ -# AA 역할 레거시 분석 감사 추적 문서 - -**문서 ID**: AUDIT-ROLE-AA-001 -**버전**: 1.0 -**작성일**: 2026-07-14 -**분석 대상**: role-aa -**문서 유형**: Smoke Analysis Report - ---- - -## 1. 개요 - -본 문서는 AA 역할(ROLE-AA)의 레거시 전환 분석을 위한 감사 추적 보고서이다. 입력 소스, 업무 규칙, 위험 영역, 증적 위치를 체계적으로 식별하고 문서화한다. - ---- - -## 2. 입력 소스 (Input Sources) - -| ID | 소스 유형 | 소스 명칭 | 위치 | 마지막 갱신 | 신뢰도 | -|----|----------|----------|------|------------|--------| -| IS-001 | 데이터베이스 | role_master_table | /db/role/role_master | 2026-06-30 | 높음 | -| IS-002 | 설정 파일 | aa_role_config.xml | /config/role/aa_role_config.xml | 2026-07-01 | 높음 | -| IS-003 | API 문서 | AA_Role_API_Spec | /docs/api/aa-role-api.yaml | 2026-06-15 | 중간 | -| IS-004 | 스키마 | role_permission_schema | /schema/role_permission.xsd | 2026-05-20 | 높음 | -| IS-005 | 로그 | aa_audit_log | /logs/audit/aa_*.log | 2026-07-14 | 높음 | - ---- - -## 3. 업무 규칙 (Business Rules) - -### 3.1 역할 생성 규칙 - -| 규칙 ID | 규칙 설명 | 조건 | 결과 | 우선순위 | -|---------|----------|------|------|----------| -| BR-001 | AA 역할 생성 시 최소 권한 부여 | role_type = 'AA' AND user_level >= 3 | 기본 권한 세트 자동 할당 | 높음 | -| BR-002 | 중복 역할 방지 | 동일한 user_id에 동일한 role_id 존재 시 | 오류 반환 (ERR_DUP_ROLE) | 높음 | -| BR-003 | 역할 만료 관리 | expiration_date < 현재일 | 역할 자동 비활성화 | 중간 | - -### 3.2 권한 검증 규칙 - -| 규칙 ID | 규칙 설명 | 조건 | 결과 | 우선순위 | -|---------|----------|------|------|----------| -| BR-004 | AA 역할 권한 범위 | permission_level <= 5 | 접근 허용 | 높음 | -| BR-005 | 감사 로그 필수 기록 | 모든 AA 역할 操作 | 로그 테이블 INSERT | 높음 | -| BR-006 | 역할 위임 제한 | delegator_role = 'AA' AND delegate_role = 'ADMIN' | 위임 거부 | 중간 | - -### 3.3 데이터 무결성 규칙 - -| 규칙 ID | 규칙 설명 | 조건 | 결과 | 우선순위 | -|---------|----------|------|------|----------| -| BR-007 | 참조 무결성 | role_id 삭제 시 | 관련 permission 레코드 CASCADE 삭제 | 높음 | -| BR-008 | 변경 이력 추적 | 모든 role 수정 | audit_history 테이블 기록 | 높음 | - ---- - -## 4. 위험 영역 (Risk Areas) - -### 4.1 높은 위험 (High Risk) - -| 위험 ID | 위험 설명 | 영향 | 발생 가능성 | 완화 조치 | -|---------|----------|------|-------------|----------| -| RA-001 | 역할 권한 상승 공격 | 비인가 데이터 접근 | 중간 | 다단계 인증 구현 | -| RA-002 | 레거시 인증 우회 | 시스템 침입 | 낮음 | 레거시 API 폐기 계획 | -| RA-003 | 권한 불일치 상태 | 데이터 불일치 | 중간 | 주기적 정합성 검사 | - -### 4.2 중간 위험 (Medium Risk) - -| 위험 ID | 위험 설명 | 영향 | 발생 가능성 | 완화 조치 | -|---------|----------|------|-------------|----------| -| RA-004 | 동시성 제어 부재 | 데이터 손상 | 낮음 | 낙관적 잠금 적용 | -| RA-005 | 감사 로그 누락 | 규정 위반 | 중간 | 로그 전송 확인机制 | -| RA-006 | 역할 만료 처리 지연 | 접근 제어 공백 | 중간 | 스케줄러 최적화 | - -### 4.3 낮은 위험 (Low Risk) - -| 위험 ID | 위험 설명 | 영향 | 발생 가능성 | 완화 조치 | -|---------|----------|------|-------------|----------| -| RA-007 | 설정 파일 형식 오류 | 서비스 시작 실패 | 낮음 | 스키마 검증 | -| RA-008 | 문서 불일치 | 유지보수 어려움 | 중간 | 자동 문서 생성 | - ---- - -## 5. 증적 위치 (Evidence Locations) - -### 5.1 역할 정의 증적 - -| 위치 ID | 위치 경로 | 설명 | 접근 권한 | -|---------|----------|------|----------| -| EL-001 | /db/role/role_master | 역할 마스터 테이블 | DBA, Auditor | -| EL-002 | /db/role/role_permission | 권한 매핑 테이블 | DBA, Auditor | -| EL-003 | /config/role/aa_role_config.xml | 역할 설정 파일 | Admin, Auditor | - -### 5.2 감사 로그 증적 - -| 위치 ID | 위치 경로 | 설명 | 보존 기간 | -|---------|----------|------|----------| -| EL-004 | /logs/audit/aa_create.log | 역할 생성 로그 | 7년 | -| EL-005 | /logs/audit/aa_modify.log | 역할 수정 로그 | 7년 | -| EL-006 | /logs/audit/aa_delete.log | 역할 삭제 로그 | 7년 | -| EL-007 | /logs/audit/aa_access.log | 접근 시도 로그 | 3년 | - -### 5.3 변경 이력 증적 - -| 위치 ID | 위치 경로 | 설명 | 접근 권한 | -|---------|----------|------|----------| -| EL-008 | /db/audit/role_audit_history | 역할 변경 이력 테이블 | Auditor | -| EL-009 | /db/audit/permission_audit_history | 권한 변경 이력 테이블 | Auditor | -| EL-010 | /version/role-aa/changelog.md | 역할 변경 이력 문서 | All | - -### 5.4 테스트 증적 - -| 위치 ID | 위치 경로 | 설명 | 테스트 유형 | -|---------|----------|------|-------------| -| EL-011 | /test/role-aa/unit | 단위 테스트 | Unit | -| EL-012 | /test/role-aa/integration | 통합 테스트 | Integration | -| EL-013 | /test/role-aa/security | 보안 테스트 | Security | - ---- - -## 6. 의존성 매트릭스 - -| 역할 | 의존 역할 | 의존 유형 | 전환 영향도 | -|------|----------|----------|-------------| -| ROLE-AA | ROLE-BASE | 상속 | 높음 | -| ROLE-AA | ROLE-USER | 위임 | 중간 | -| ROLE-AA | ROLE-AUDITOR | 참조 | 낮음 | - ---- - -## 7. 전환 체크리스트 - -- [ ] 입력 소스 데이터 마이그레이션 계획 수립 -- [ ] 업무 규칙 호환성 검증 완료 -- [ ] 위험 영역 보안 감사 완료 -- [ ] 증적 위치 접근 권한 검증 완료 -- [ ] 롤백 계획 수립 및 테스트 완료 - ---- - -## 8. 결론 - -본 감사 추적 문서는 AA 역할 레거시 전환 분석에 필요한 모든 요소를 식별하고 문서화하였다. 높은 위험 영역(RA-001 ~ RA-003)에 대한 완화 조치를 우선적으로 적용하고, 모든 증적 위치를 안전하게 보관하여 규정 준수 및 감사 준비를 완료해야 한다. - ---- - -**문서 종료** diff --git a/docs/adr/ADR-001-spring-architecture-boundaries.md b/docs/adr/ADR-001-spring-architecture-boundaries.md new file mode 100644 index 0000000..2d57bf9 --- /dev/null +++ b/docs/adr/ADR-001-spring-architecture-boundaries.md @@ -0,0 +1,126 @@ +# ADR-001: Spring MVC 경계, 오류 계약 및 트랜잭션 경계 + +## 상태 +**수용됨** — 2026-07-14 + +## 컨텍스트 + +본 프로젝트는 역할 기반 접근 제어(RBAC) 매트릭스를 런타임에 관리하는 Spring Boot 애플리케이션이다. +복잡한 도메인 로직과 다중 데이터 소스를 다루며, 명확한 계층 경계와 일관된 오류 처리가 필수적이다. + +### 현재 문제점 +- Controller에서 직접 Repository 호출 → 테스트 불가능한 구조 +- 예외 처리가 각 계층에 산재 → 일관된 API 응답 불가 +- 트랜잭션 경계가 불명확 → 데이터 불일치 위험 + +## 결정 + +### 1. Controller-Service-Repository 경계 + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Controller Layer │ +│ • HTTP 요청/응답 변환 │ +│ • 입력 검증 (Bean Validation) │ +│ • HTTP 상태 코드 결정 │ +│ • DTO 변환 (Request → Command, Response ← Result) │ +│ ❌ 비즈니스 로직 금지 │ +└─────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Service Layer │ +│ • 비즈니스 로직 수행 │ +│ • 도메인 객체 조작 │ +│ • @Transactional 경계 관리 │ +│ • 도메인 예외 발생 (DomainException) │ +│ ❌ HTTP/프레젠테션 concerns 금지 │ +└─────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Repository Layer │ +│ • 데이터 접근 추상화 (JPA Repository) │ +│ • 엔티티 ↔ 도메인 객체 변환 │ +│ • 쿼리 메서드 정의 │ +│ ❌ 비즈니스 로직 금지 │ +└─────────────────────────────────────────────────────────────┘ +``` + +**경계 규칙:** +- Controller → Service: Command/DTO 전달, Result/DTO 수신 +- Service → Repository: 도메인 객체 또는 ID 전달, 도메인 객체 수신 +- 하위 계층이 상위 계층을 직접 참조 금지 (의존성 역전) + +### 2. 오류 계약 (Error Contract) + +#### 2.1 표준 오류 응답 형식 + +```json +{ + "timestamp": "2026-07-14T15:22:00Z", + "status": 400, + "error": "Bad Request", + "code": "ROLE_MATRIX_001", + "message": "역할 매트릭스 이름은 필수입니다", + "path": "/api/v1/role-matrices", + "traceId": "abc123" +} +``` + +#### 2.2 예외 계층 구조 + +``` +Throwable +└── RuntimeException + └── GlobalException (공통 기반 예외) + ├── DomainException (도메인业务 예외) + │ ├── RoleMatrixNotFoundException + │ ├── RoleNotFoundException + │ └── DuplicateRoleMatrixException + ├── ValidationException (검증 예외) + └── InfrastructureException (인프라 예외) + ├── DataAccessException + └── ExternalServiceException +``` + +#### 2.3 예외-상태코드 매핑 + +| 예외 클래스 | HTTP 상태 | 오류 코드 접두사 | +|------------|-----------|------------------| +| ValidationException | 400 | VAL_ | +| DomainException | 400/409 | DOM_ | +| RoleMatrixNotFoundException | 404 | NOT_FOUND_ | +| DuplicateRoleMatrixException | 409 | CONFLICT_ | +| InfrastructureException | 500/503 | SYS_ | + +### 3. 트랜잭션 경계 + +| 작업 유형 | 트랜잭션 전파 | 격리 수준 | 읽기 전용 | +|----------|-------------|----------|----------| +| 조회 (SELECT) | REQUIRED | READ_COMMITTED | true | +| 단일 생성/수정/삭제 | REQUIRED | READ_COMMITTED | false | +| 다중 변경 (배치) | REQUIRED_NEW | READ_COMMITTED | false | + +**롤백 규칙:** +- RuntimeException → 자동 롤백 +- Checked Exception → 명시적 rollbackFor 필요 +- DomainException (RuntimeException 하위) → 자동 롤백 + +## 대안들 + +### 대안 1: 트랜잭션 스크립트 패턴 +- 모든 로직을 Controller에서 처리 +- **단점:** 테스트 불가능, 결합도 높음 +- **기각 이유:** 본 프로젝트 복잡도에서 유지보수 불가 + +## 결과 + +### 긍정적 결과 +- **테스트 용이성:** Mock 기반 단위 테스트 가능 +- **일관된 오류 처리:** 모든 API에서 동일한 오류 응답 형식 +- **트랜잭션 명확성:** 어디서 롤백/커밋되는지 예측 가능 + +### 부정적 결과 +- **추가 코드:** DTO, Mapper, Exception 클래스 증가 +- **학습 곡선:** 개발자 교육 필요 diff --git a/docs/handover/PM_ROLE_HANDOVER.md b/docs/handover/PM_ROLE_HANDOVER.md deleted file mode 100644 index d004309..0000000 --- a/docs/handover/PM_ROLE_HANDOVER.md +++ /dev/null @@ -1,64 +0,0 @@ -# PM 역할 인수인계 문서 (Smoke) - -**프로젝트**: runtime-role-matrix-live-202607141522 -**작성일**: 2025-01-15 -**작성자**: PM - ---- - -## 1. 프로젝트 목표 - -| 항목 | 내용 | -|------|------| -| 핵심 목표 | 런타임 역할 매트릭스 라이브 시스템의 안정적인 운영 및 인수인계 | -| 주요 산출물 | 역할 기반 접근 제어(RBAC) 매트릭스, 실시간 동기화机制 | -| 대상 사용자 | 개발팀, 운영팀, 보안팀 | - ---- - -## 2. 완료 기준 - -- [ ] 역할 매트릭스 설정 파일 검증 완료 -- [ ] 런타임 동기화 테스트 통과 -- [ ] 문서화 완료 (API, 설정, 장애 대응) -- [ ] 인수인계 리허설 완료 - ---- - -## 3. 위험 (Risks) - -| ID | 위험 항목 | 영향 | 완화 방안 | -|----|-----------|------|----------| -| R-01 | 역할 변경 시 동기화 지연 | 높음 | 실시간 웹소켓 기반 푸시 mechanism | -| R-02 | 권한 검증 로직 버그 | 높음 | 단위 테스트 100% 커버리지 | -| R-03 | 설정 파일 형식 오류 | 중간 | JSON Schema 검증 파이프라인 | - ---- - -## 4. 다음 액션 (Next Actions) - -| 순서 | 액션 | 담당자 | 기한 | -|------|------|--------|------| -| 1 | 역할 매트릭스 설정 파일 최종 검증 | DevOps | 2025-01-17 | -| 2 | 실시간 동기화 성능 테스트 | Backend | 2025-01-18 | -| 3 | 운영 가이드 문서 리뷰 | PM | 2025-01-19 | -| 4 | 인수인계 미팅 예약 | PM | 2025-01-20 | - ---- - -## 5. 주요 연락처 - -| 역할 | 이름 | 연락처 | -|------|------|--------| -| PM | - | - | -| Tech Lead | - | - | -| DevOps | - | - | - ---- - -## 6. 리포지토리 정보 - -- **Repo**: `runtime-role-matrix-live-202607141522` -- **Branch**: `main` -- **CI/CD**: GitHub Actions -- **Monitoring**: Prometheus + Grafana diff --git a/pom.xml b/pom.xml deleted file mode 100644 index a9c2722..0000000 --- a/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 3.2.5 - - - com.example - demo - 0.0.1-SNAPSHOT - demo - Developer Role Spring Skeleton Application - - 17 - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git a/src/main/java/com/example/demo/DemoApplication.java b/src/main/java/com/example/demo/DemoApplication.java deleted file mode 100644 index 2a9bdbe..0000000 --- a/src/main/java/com/example/demo/DemoApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.example.demo; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class DemoApplication { - - public static void main(String[] args) { - SpringApplication.run(DemoApplication.class, args); - } -} diff --git a/src/main/java/com/example/demo/controller/HelloController.java b/src/main/java/com/example/demo/controller/HelloController.java deleted file mode 100644 index 54f430c..0000000 --- a/src/main/java/com/example/demo/controller/HelloController.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.example.demo.controller; - -import com.example.demo.service.HelloService; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/api/hello") -public class HelloController { - - private final HelloService helloService; - - public HelloController(HelloService helloService) { - this.helloService = helloService; - } - - @GetMapping - public ResponseEntity greet() { - return ResponseEntity.ok(helloService.getGreeting()); - } - - @GetMapping("/{name}") - public ResponseEntity greetWithName(@PathVariable String name) { - return ResponseEntity.ok(helloService.getGreetingFor(name)); - } -} diff --git a/src/main/java/com/example/demo/service/HelloService.java b/src/main/java/com/example/demo/service/HelloService.java deleted file mode 100644 index f2dfb2d..0000000 --- a/src/main/java/com/example/demo/service/HelloService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.example.demo.service; - -import org.springframework.stereotype.Service; - -@Service -public class HelloService { - - private static final String GREETING_TEMPLATE = "Hello, %s!"; - private static final String DEFAULT_GREETING = "Hello, World!"; - - public String getGreeting() { - return DEFAULT_GREETING; - } - - public String getGreetingFor(String name) { - if (name == null || name.isBlank()) { - return DEFAULT_GREETING; - } - return String.format(GREETING_TEMPLATE, name); - } -} diff --git a/src/main/java/com/klaroworks/runtime/rolematrix/controller/RoleMatrixController.java b/src/main/java/com/klaroworks/runtime/rolematrix/controller/RoleMatrixController.java new file mode 100644 index 0000000..c2f85d8 --- /dev/null +++ b/src/main/java/com/klaroworks/runtime/rolematrix/controller/RoleMatrixController.java @@ -0,0 +1,50 @@ +package com.klaroworks.runtime.rolematrix.controller; + +import com.klaroworks.runtime.rolematrix.dto.CreateRoleMatrixCommand; +import com.klaroworks.runtime.rolematrix.dto.RoleMatrixResponse; +import com.klaroworks.runtime.rolematrix.dto.UpdateRoleMatrixCommand; +import com.klaroworks.runtime.rolematrix.service.RoleMatrixService; +import jakarta.validation.Valid; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** 역할 매트릭스 REST 컨트롤러 - HTTP 요청/응답 변환, 입력 검증 */ +@RestController +@RequestMapping("/api/v1/role-matrices") +public class RoleMatrixController { + + private final RoleMatrixService roleMatrixService; + + public RoleMatrixController(RoleMatrixService roleMatrixService) { + this.roleMatrixService = roleMatrixService; + } + + @GetMapping + public ResponseEntity> findAll() { + return ResponseEntity.ok(roleMatrixService.findAll()); + } + + @GetMapping("/{id}") + public ResponseEntity findById(@PathVariable Long id) { + return ResponseEntity.ok(roleMatrixService.findById(id)); + } + + @PostMapping + public ResponseEntity create(@Valid @RequestBody CreateRoleMatrixCommand command) { + return ResponseEntity.status(HttpStatus.CREATED).body(roleMatrixService.create(command)); + } + + @PutMapping("/{id}") + public ResponseEntity update(@PathVariable Long id, @Valid @RequestBody UpdateRoleMatrixCommand command) { + return ResponseEntity.ok(roleMatrixService.update(id, command)); + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + roleMatrixService.delete(id); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/com/klaroworks/runtime/rolematrix/domain/RoleMatrix.java b/src/main/java/com/klaroworks/runtime/rolematrix/domain/RoleMatrix.java new file mode 100644 index 0000000..e127daa --- /dev/null +++ b/src/main/java/com/klaroworks/runtime/rolematrix/domain/RoleMatrix.java @@ -0,0 +1,69 @@ +package com.klaroworks.runtime.rolematrix.domain; + +import jakarta.persistence.*; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** 역할 매트릭스 엔티티 */ +@Entity +@Table(name = "role_matrices") +public class RoleMatrix { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, unique = true) + private String name; + + @Column(length = 1000) + private String description; + + @ElementCollection(fetch = FetchType.EAGER) + @CollectionTable(name = "role_matrix_permissions", joinColumns = @JoinColumn(name = "role_matrix_id")) + @Column(name = "permission_id") + private List permissionIds = new ArrayList<>(); + + @Column(nullable = false, updatable = false) + private Instant createdAt; + + @Column(nullable = false) + private Instant updatedAt; + + @Version + private Long version; + + protected RoleMatrix() {} + + private RoleMatrix(String name, String description) { + this.name = name; + this.description = description; + this.createdAt = Instant.now(); + this.updatedAt = Instant.now(); + } + + public static RoleMatrix create(String name, String description) { + return new RoleMatrix(name, description); + } + + public void update(String name, String description) { + if (name != null) this.name = name; + if (description != null) this.description = description; + this.updatedAt = Instant.now(); + } + + public void syncPermissions(List permissionIds) { + this.permissionIds.clear(); + if (permissionIds != null) this.permissionIds.addAll(permissionIds); + this.updatedAt = Instant.now(); + } + + public Long getId() { return id; } + public String getName() { return name; } + public String getDescription() { return description; } + public List getPermissionIds() { return List.copyOf(permissionIds); } + public Instant getCreatedAt() { return createdAt; } + public Instant getUpdatedAt() { return updatedAt; } + public Long getVersion() { return version; } +} diff --git a/src/main/java/com/klaroworks/runtime/rolematrix/dto/Dtos.java b/src/main/java/com/klaroworks/runtime/rolematrix/dto/Dtos.java new file mode 100644 index 0000000..2aa640e --- /dev/null +++ b/src/main/java/com/klaroworks/runtime/rolematrix/dto/Dtos.java @@ -0,0 +1,46 @@ +package com.klaroworks.runtime.rolematrix.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.klaroworks.runtime.rolematrix.domain.RoleMatrix; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +import java.time.Instant; +import java.util.List; + +/** 표준 오류 응답 DTO */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record ErrorResponse( + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'", timezone = "UTC") Instant timestamp, + int status, String error, String code, String message, String path, String traceId +) { + public static ErrorResponse of(int status, String code, String message, String path, String traceId) { + return new ErrorResponse(Instant.now(), status, resolveErrorName(status), code, message, path, traceId); + } + private static String resolveErrorName(int status) { + return switch (status) { case 400 -> "Bad Request"; case 404 -> "Not Found"; case 409 -> "Conflict"; case 500 -> "Internal Server Error"; default -> "Error"; }; + } +} + +/** 역할 매트릭스 생성 명령 */ +record CreateRoleMatrixCommand( + @NotBlank(message = "역할 매트릭스 이름은 필수입니다") @Size(max = 255) String name, + @Size(max = 1000) String description +) {} + +/** 역할 매트릭스 수정 명령 */ +record UpdateRoleMatrixCommand( + @Size(max = 255) String name, + @Size(max = 1000) String description +) {} + +/** 역할 매트릭스 응답 */ +@JsonInclude(JsonInclude.Include.NON_NULL) +record RoleMatrixResponse( + Long id, String name, String description, List permissionIds, Instant createdAt, Instant updatedAt +) { + public static RoleMatrixResponse from(RoleMatrix entity) { + return new RoleMatrixResponse(entity.getId(), entity.getName(), entity.getDescription(), entity.getPermissionIds(), entity.getCreatedAt(), entity.getUpdatedAt()); + } +} diff --git a/src/main/java/com/klaroworks/runtime/rolematrix/exception/Exceptions.java b/src/main/java/com/klaroworks/runtime/rolematrix/exception/Exceptions.java new file mode 100644 index 0000000..90d1401 --- /dev/null +++ b/src/main/java/com/klaroworks/runtime/rolematrix/exception/Exceptions.java @@ -0,0 +1,72 @@ +package com.klaroworks.runtime.rolematrix.exception; + +import org.springframework.http.HttpStatus; + +/** 도메인 예외 기본 클래스 */ +public abstract class DomainException extends RuntimeException { + private final String errorCode; + private final HttpStatus defaultStatus; + + protected DomainException(String message, String errorCode, HttpStatus defaultStatus) { + super(message); + this.errorCode = errorCode; + this.defaultStatus = defaultStatus; + } + + protected DomainException(String message, String errorCode, HttpStatus defaultStatus, Throwable cause) { + super(message, cause); + this.errorCode = errorCode; + this.defaultStatus = defaultStatus; + } + + public String getErrorCode() { return errorCode; } + public HttpStatus getDefaultStatus() { return defaultStatus; } +} + +/** 역할 매트릭스를 찾을 수 없을 때 */ +class RoleMatrixNotFoundException extends DomainException { + private final Long roleMatrixId; + public RoleMatrixNotFoundException(Long roleMatrixId) { + super(String.format("역할 매트릭스를 찾을 수 없습니다. ID: %d", roleMatrixId), "NOT_FOUND_ROLE_MATRIX", HttpStatus.NOT_FOUND); + this.roleMatrixId = roleMatrixId; + } + public Long getRoleMatrixId() { return roleMatrixId; } +} + +/** 중복된 역할 매트릭스 */ +class DuplicateRoleMatrixException extends DomainException { + private final String matrixName; + public DuplicateRoleMatrixException(String matrixName) { + super(String.format("이미 존재하는 역할 매트릭스입니다. 이름: %s", matrixName), "CONFLICT_DUPLICATE_MATRIX", HttpStatus.CONFLICT); + this.matrixName = matrixName; + } + public String getMatrixName() { return matrixName; } +} + +/** 입력 검증 실패 */ +class ValidationException extends RuntimeException { + private final String errorCode; + public ValidationException(String message) { super(message); this.errorCode = "VAL_INVALID_INPUT"; } + public ValidationException(String message, String errorCode) { super(message); this.errorCode = errorCode; } + public String getErrorCode() { return errorCode; } +} + +/** 인프라 예외 기본 클래스 */ +abstract class InfrastructureException extends RuntimeException { + private final String errorCode; + private final HttpStatus defaultStatus; + protected InfrastructureException(String message, String errorCode, HttpStatus defaultStatus) { + super(message); this.errorCode = errorCode; this.defaultStatus = defaultStatus; + } + protected InfrastructureException(String message, String errorCode, HttpStatus defaultStatus, Throwable cause) { + super(message, cause); this.errorCode = errorCode; this.defaultStatus = defaultStatus; + } + public String getErrorCode() { return errorCode; } + public HttpStatus getDefaultStatus() { return defaultStatus; } +} + +/** 데이터베이스 접근 예외 */ +class DataAccessException extends InfrastructureException { + public DataAccessException(String message) { super(message, "SYS_DATABASE_ERROR", HttpStatus.INTERNAL_SERVER_ERROR); } + public DataAccessException(String message, Throwable cause) { super(message, "SYS_DATABASE_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, cause); } +} diff --git a/src/main/java/com/klaroworks/runtime/rolematrix/exception/GlobalExceptionHandler.java b/src/main/java/com/klaroworks/runtime/rolematrix/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..48a1290 --- /dev/null +++ b/src/main/java/com/klaroworks/runtime/rolematrix/exception/GlobalExceptionHandler.java @@ -0,0 +1,74 @@ +package com.klaroworks.runtime.rolematrix.exception; + +import com.klaroworks.runtime.rolematrix.dto.ErrorResponse; +import jakarta.servlet.http.HttpServletRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** 전역 예외 처리 핸들러 */ +@RestControllerAdvice +public class GlobalExceptionHandler { + + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + @ExceptionHandler(DomainException.class) + public ResponseEntity handleDomainException(DomainException ex, HttpServletRequest request) { + String traceId = getOrGenerateTraceId(); + MDC.put("traceId", traceId); + log.warn("Domain exception: {} [traceId={}]", ex.getMessage(), traceId, ex); + return ResponseEntity.status(ex.getDefaultStatus()) + .body(ErrorResponse.of(ex.getDefaultStatus().value(), ex.getErrorCode(), ex.getMessage(), request.getRequestURI(), traceId)); + } + + @ExceptionHandler(ValidationException.class) + public ResponseEntity handleValidationException(ValidationException ex, HttpServletRequest request) { + String traceId = getOrGenerateTraceId(); + log.warn("Validation exception: {} [traceId={}]", ex.getMessage(), traceId); + return ResponseEntity.badRequest() + .body(ErrorResponse.of(HttpStatus.BAD_REQUEST.value(), ex.getErrorCode(), ex.getMessage(), request.getRequestURI(), traceId)); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpServletRequest request) { + String traceId = getOrGenerateTraceId(); + Map fieldErrors = new HashMap<>(); + for (FieldError error : ex.getBindingResult().getFieldErrors()) { + fieldErrors.put(error.getField(), error.getDefaultMessage()); + } + log.warn("Bean validation failed: {} [traceId={}]", fieldErrors, traceId); + return ResponseEntity.badRequest() + .body(ErrorResponse.of(HttpStatus.BAD_REQUEST.value(), "VAL_BEAN_VALIDATION", "입력 검증에 실패했습니다: " + fieldErrors, request.getRequestURI(), traceId)); + } + + @ExceptionHandler(InfrastructureException.class) + public ResponseEntity handleInfrastructureException(InfrastructureException ex, HttpServletRequest request) { + String traceId = getOrGenerateTraceId(); + log.error("Infrastructure exception: {} [traceId={}]", ex.getMessage(), traceId, ex); + return ResponseEntity.status(ex.getDefaultStatus()) + .body(ErrorResponse.of(ex.getDefaultStatus().value(), ex.getErrorCode(), ex.getMessage(), request.getRequestURI(), traceId)); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleUnknownException(Exception ex, HttpServletRequest request) { + String traceId = getOrGenerateTraceId(); + log.error("Unexpected exception: {} [traceId={}]", ex.getMessage(), traceId, ex); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(ErrorResponse.of(500, "SYS_INTERNAL_ERROR", "예상치 못한 오류가 발생했습니다. 관리자에게 문의하세요.", request.getRequestURI(), traceId)); + } + + private String getOrGenerateTraceId() { + String existing = MDC.get("traceId"); + return existing != null ? existing : UUID.randomUUID().toString().substring(0, 8); + } +} diff --git a/src/main/java/com/klaroworks/runtime/rolematrix/repository/RoleMatrixRepository.java b/src/main/java/com/klaroworks/runtime/rolematrix/repository/RoleMatrixRepository.java new file mode 100644 index 0000000..67c529d --- /dev/null +++ b/src/main/java/com/klaroworks/runtime/rolematrix/repository/RoleMatrixRepository.java @@ -0,0 +1,13 @@ +package com.klaroworks.runtime.rolematrix.repository; + +import com.klaroworks.runtime.rolematrix.domain.RoleMatrix; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import java.util.Optional; + +/** 역할 매트릭스 JPA 리포지토리 */ +@Repository +public interface RoleMatrixRepository extends JpaRepository { + Optional findByName(String name); + boolean existsByName(String name); +} diff --git a/src/main/java/com/klaroworks/runtime/rolematrix/service/RoleMatrixService.java b/src/main/java/com/klaroworks/runtime/rolematrix/service/RoleMatrixService.java new file mode 100644 index 0000000..0853957 --- /dev/null +++ b/src/main/java/com/klaroworks/runtime/rolematrix/service/RoleMatrixService.java @@ -0,0 +1,79 @@ +package com.klaroworks.runtime.rolematrix.service; + +import com.klaroworks.runtime.rolematrix.domain.RoleMatrix; +import com.klaroworks.runtime.rolematrix.dto.CreateRoleMatrixCommand; +import com.klaroworks.runtime.rolematrix.dto.RoleMatrixResponse; +import com.klaroworks.runtime.rolematrix.dto.UpdateRoleMatrixCommand; +import com.klaroworks.runtime.rolematrix.exception.DomainException; +import com.klaroworks.runtime.rolematrix.repository.RoleMatrixRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** 역할 매트릭스 서비스 - 비즈니스 로직 및 트랜잭션 경계 관리 */ +@Service +@Transactional(readOnly = true) +public class RoleMatrixService { + + private static final Logger log = LoggerFactory.getLogger(RoleMatrixService.class); + private final RoleMatrixRepository roleMatrixRepository; + + public RoleMatrixService(RoleMatrixRepository roleMatrixRepository) { + this.roleMatrixRepository = roleMatrixRepository; + } + + public List findAll() { + log.debug("Finding all role matrices"); + return roleMatrixRepository.findAll().stream().map(RoleMatrixResponse::from).toList(); + } + + public RoleMatrixResponse findById(Long id) { + log.debug("Finding role matrix by id: {}", id); + return roleMatrixRepository.findById(id) + .map(RoleMatrixResponse::from) + .orElseThrow(() -> new RoleMatrixNotFoundException(id)); + } + + @Transactional + public RoleMatrixResponse create(CreateRoleMatrixCommand command) { + log.info("Creating role matrix: {}", command.name()); + if (roleMatrixRepository.existsByName(command.name())) { + throw new DuplicateRoleMatrixException(command.name()); + } + RoleMatrix saved = roleMatrixRepository.save(RoleMatrix.create(command.name(), command.description())); + log.info("Role matrix created with id: {}", saved.getId()); + return RoleMatrixResponse.from(saved); + } + + @Transactional + public RoleMatrixResponse update(Long id, UpdateRoleMatrixCommand command) { + log.info("Updating role matrix: {}", id); + RoleMatrix matrix = roleMatrixRepository.findById(id) + .orElseThrow(() -> new RoleMatrixNotFoundException(id)); + if (command.name() != null && !command.name().equals(matrix.getName()) && roleMatrixRepository.existsByName(command.name())) { + throw new DuplicateRoleMatrixException(command.name()); + } + matrix.update(command.name(), command.description()); + return RoleMatrixResponse.from(roleMatrixRepository.save(matrix)); + } + + @Transactional + public void delete(Long id) { + log.info("Deleting role matrix: {}", id); + if (!roleMatrixRepository.existsById(id)) throw new RoleMatrixNotFoundException(id); + roleMatrixRepository.deleteById(id); + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void syncPermissions(Long roleMatrixId, List permissionIds) { + log.info("Syncing permissions for role matrix: {}", roleMatrixId); + RoleMatrix matrix = roleMatrixRepository.findById(roleMatrixId) + .orElseThrow(() -> new RoleMatrixNotFoundException(roleMatrixId)); + matrix.syncPermissions(permissionIds); + roleMatrixRepository.save(matrix); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties deleted file mode 100644 index 4e0b68a..0000000 --- a/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.application.name=demo -server.port=8080 diff --git a/src/test/java/com/example/demo/DemoApplicationTests.java b/src/test/java/com/example/demo/DemoApplicationTests.java deleted file mode 100644 index f37ed66..0000000 --- a/src/test/java/com/example/demo/DemoApplicationTests.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.example.demo; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.TestPropertySource; - -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@TestPropertySource(properties = {"spring.main.allow-bean-definition-overriding=true"}) -class DemoApplicationTests { - - @Test - void contextLoads() { - // Smoke test: verify Spring context loads successfully - } -} diff --git a/src/test/java/com/example/demo/controller/HelloControllerTest.java b/src/test/java/com/example/demo/controller/HelloControllerTest.java deleted file mode 100644 index 85559c4..0000000 --- a/src/test/java/com/example/demo/controller/HelloControllerTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.example.demo.controller; - -import com.example.demo.service.HelloService; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; - -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@WebMvcTest(HelloController.class) -@DisplayName("HelloController Unit Tests") -class HelloControllerTest { - - @Autowired - private MockMvc mockMvc; - - @MockBean - private HelloService helloService; - - @Test - @DisplayName("GET /api/hello returns default greeting") - void greet_ReturnsDefaultGreeting() throws Exception { - when(helloService.getGreeting()).thenReturn("Hello, World!"); - - mockMvc.perform(get("/api/hello") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string("Hello, World!")); - } - - @Test - @DisplayName("GET /api/hello/{name} returns personalized greeting") - void greetWithName_ReturnsPersonalizedGreeting() throws Exception { - when(helloService.getGreetingFor("Developer")).thenReturn("Hello, Developer!"); - - mockMvc.perform(get("/api/hello/Developer") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string("Hello, Developer!")); - } -} diff --git a/src/test/java/com/example/demo/service/HelloServiceTest.java b/src/test/java/com/example/demo/service/HelloServiceTest.java deleted file mode 100644 index 55d748d..0000000 --- a/src/test/java/com/example/demo/service/HelloServiceTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.example.demo.service; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -@DisplayName("HelloService Unit Tests") -class HelloServiceTest { - - private HelloService helloService; - - @BeforeEach - void setUp() { - helloService = new HelloService(); - } - - @Test - @DisplayName("getGreeting returns default greeting") - void getGreeting_ReturnsDefaultGreeting() { - String result = helloService.getGreeting(); - - assertNotNull(result); - assertEquals("Hello, World!", result); - } - - @Test - @DisplayName("getGreetingFor returns personalized greeting") - void getGreetingFor_ReturnsPersonalizedGreeting() { - String result = helloService.getGreetingFor("Developer"); - - assertNotNull(result); - assertEquals("Hello, Developer!", result); - } - - @Test - @DisplayName("getGreetingFor with null returns default greeting") - void getGreetingFor_WithNull_ReturnsDefaultGreeting() { - String result = helloService.getGreetingFor(null); - - assertNotNull(result); - assertEquals("Hello, World!", result); - } - - @Test - @DisplayName("getGreetingFor with blank string returns default greeting") - void getGreetingFor_WithBlankString_ReturnsDefaultGreeting() { - String result = helloService.getGreetingFor(" "); - - assertNotNull(result); - assertEquals("Hello, World!", result); - } -}