Files
rogee aeddedf2a3 Reorganize repo: backend/, deploy/, docs/ layout + AGENTS.md
Restructure the monorepo into clear top-level directories:
- backend/: Go module root (cmd, internal, pkg, configs, migrations,
  docs/swagger, scripts, tests, go.mod, Makefile, .air.toml)
- deploy/: Docker (Dockerfile, docker-compose*), quickstart, fluentd
- docs/: project documentation + reports/ (moved from repo root)
- AGENTS.md: new AI coding-agent guide at repo root

Update all references to the new layout:
- Dockerfile: COPY backend/go.mod, COPY backend/ (context = repo root)
- docker-compose files: context ../.., dockerfile deploy/docker/Dockerfile,
  env_file ../../.env, volume mounts ../../backend:/app
- deploy/quickstart/compose.yaml: dockerfile deploy/docker/Dockerfile
- CI: working-directory: backend for go commands, file deploy/docker/Dockerfile,
  coverage path backend/coverage.out, health_check backend/scripts/
- backend/Makefile: docker target uses -f ../deploy/docker/Dockerfile ../
- README: architecture tree, quickstart, config paths updated

Move root stray scripts (rename_models.*, run_m11_tests.sh, verify_build.sh,
gorm_bool_main.go) to backend/scripts/legacy/. All moves via git mv to
preserve history. Build, vet, SQLite tests, and docker compose config verified.
2026-07-07 14:44:12 +08:00

219 lines
8.1 KiB
Markdown

# GoChat Test Coverage Report
> Generated: Initial template
> Target: 80%+ coverage across all modules
> Reference: Chatwoot RSpec coverage patterns mapped to Go testing conventions
## Coverage Targets Per Module
| Module | Target Coverage | Priority | Status |
|--------|----------------|----------|--------|
| `internal/model` | 90% | High | Pending |
| `internal/repository` | 85% | High | Pending |
| `internal/service` | 80% | High | Pending |
| `internal/auth` | 85% | High | Pending |
| `internal/handler` | 75% | Medium | Pending |
| `internal/middleware` | 80% | Medium | Pending |
| `internal/channel` | 75% | Medium | Pending |
| `internal/channel/provider` | 70% | Medium | Pending |
| `internal/config` | 80% | Low | Pending |
| `internal/app` | 60% | Low | Pending |
| `internal/router` | 70% | Low | Pending |
| `internal/ws` | 75% | Medium | Pending |
| `internal/pubsub` | 75% | Medium | Pending |
| `pkg/crypto` | 90% | High | Pending |
| `pkg/logger` | 80% | Medium | Pending |
## Module Coverage Details
### internal/model (Target: 90%)
Model tests focus on:
- CRUD operations via GORM (Create, Read, Update, Delete)
- Association integrity (foreign keys, belongs-to, has-many)
- Validation rules (required fields, unique constraints, format checks)
- Soft delete behavior (DeletedAt field, recovery)
- Custom types (JSONB permissions, enum fields)
- Edge cases (null fields, empty strings, boundary values)
Key test files:
- `internal/model/base_test.go` — Base model fields, timestamps, soft delete
- `internal/model/user_test.go` — User CRUD, role validation, email uniqueness
- `internal/model/account_test.go` — Account CRUD, locale/timezone defaults
- `internal/model/conversation_test.go` — Conversation status transitions, assignee
- `internal/model/message_test.go` — Message types, content validation, privacy
- `internal/model/custom_role_test.go` — Permission matrix parsing, role CRUD
- `internal/model/contact_test.go` — Contact identification, channel binding
### internal/repository (Target: 85%)
Repository tests focus on:
- BaseRepository generic CRUD operations
- Specialized repository query methods (FindByAccount, FindByStatus, etc.)
- Pagination (offset/limit)
- Error handling (record not found, duplicate key)
- Soft-delete scoped queries
- Transaction support
Key test files:
- `internal/repository/repository_test.go` — BaseRepository[T] generic CRUD
- `internal/repository/user_repo_test.go` — FindByEmail, FindByAccount
- `internal/repository/conversation_repo_test.go` — FindByAccount, FindByStatus, FindByAssignee
- `internal/repository/message_repo_test.go` — FindByConversation, Search
- `internal/repository/account_repo_test.go` — Account CRUD operations
### internal/service (Target: 80%)
Service tests focus on:
- Business logic correctness
- Input validation
- Error handling and propagation
- Cross-service coordination
- Authorization checks (RBAC integration)
- AI/Copilot features (Captain, LLM Provider)
Key test files:
- `internal/service/auth_service_test.go` — Login, Register, Refresh, Logout flows
- `internal/service/conversation_service_test.go` — CRUD, status transitions, assignment
- `internal/service/message_service_test.go` — Create, Search, privacy controls
- `internal/service/rbac_service_test.go` — Role assignment, permission checking, custom roles
- `internal/service/captain_service_test.go` — Captain Assistant CRUD, Document, Scenario
- `internal/service/copilot_service_test.go` — Thread, Message, AI reply suggestions
- `internal/service/llm_provider_test.go` — LLM Provider interface compliance
### internal/auth (Target: 85%)
Auth tests focus on:
- JWT token generation and validation
- Refresh token lifecycle
- Permission system (administrator, agent, custom_role)
- Policy context construction
- MFA (TOTP) verification
- OAuth provider integration
Key test files:
- `internal/auth/jwt_test.go` — Token pair generation, expiry, validation
- `internal/auth/permission_test.go` — Permission sets for each role level
- `internal/auth/policy_test.go` — PolicyContext authorization checks
- `internal/auth/mfa_test.go` — TOTP generation and verification
- `internal/auth/oauth_test.go` — OAuth provider flow
### internal/handler (Target: 75%)
Handler tests focus on:
- HTTP request/response correctness
- Route parameter binding
- Authentication middleware integration
- Response format (JSON structure, status codes)
- Error response formatting
Key test files:
- `internal/handler/auth/auth_handler_test.go` — Auth endpoints
- `internal/handler/api_v1/conversation_handler_test.go` — Conversation API
- `internal/handler/api_v1/message_handler_test.go` — Message API
- `internal/handler/webhook/webhook_handler_test.go` — Webhook processing
- `internal/handler/ws/ws_handler_test.go` — WebSocket connection
### internal/middleware (Target: 80%)
Middleware tests focus on:
- Authentication extraction from headers
- Role-based access control enforcement
- CORS configuration
- Rate limiting behavior
- Request logging
### internal/channel (Target: 75%)
Channel tests focus on:
- Channel provider interface compliance
- Webhook processing pipeline
- Message broker routing
- Provider-specific configuration validation
- Incoming/outgoing message transformation
### pkg/crypto (Target: 90%)
Crypto tests focus on:
- Password hashing (bcrypt)
- JWT token generation and validation
- Token expiry handling
- Invalid token rejection
### pkg/logger (Target: 80%)
Logger tests focus on:
- Log level filtering
- Structured logging output
- Context-aware logging
## Test Strategy Matrix
| Test Type | Scope | Tool | Count Target |
|-----------|-------|------|-------------|
| Unit Tests | Single function/method | `go test` | 200+ |
| Integration Tests | Service + Repository | `go test` with SQLite | 50+ |
| E2E Tests | Full HTTP flow | httptest + SQLite | 30+ |
| Benchmark Tests | Performance | `go test -bench` | 20+ |
| Mock Tests | External dependencies | httptest mock server | 15+ |
## Coverage Collection Method
```bash
# Run all tests with coverage
go test -coverprofile=coverage.out -covermode=atomic ./...
# View per-function coverage
go tool cover -func=coverage.out
# Generate HTML report
go tool cover -html=coverage.out -o coverage.html
# Run benchmarks
go test -bench=. -benchmem ./internal/service/ ./internal/repository/ ./pkg/crypto/
```
## Coverage Quality Gates
- **Critical modules** (model, repository, auth, crypto): Must achieve 85%+ coverage
- **Business logic** (service, middleware): Must achieve 80%+ coverage
- **HTTP layer** (handler, channel): Must achieve 75%+ coverage
- **Infrastructure** (app, config, router): Must achieve 60%+ coverage
- **Overall project**: Must achieve 80%+ average coverage
## Chatwoot Test Pattern Mapping
| Chatwoot Pattern | Go Equivalent | Coverage Focus |
|-----------------|---------------|---------------|
| `spec/models/` (RSpec model specs) | `internal/model/*_test.go` | Model CRUD + validations |
| `spec/services/` (service_object specs) | `internal/service/*_test.go` | Business logic |
| `spec/controllers/` (controller specs) | `internal/handler/*_test.go` | HTTP API responses |
| `spec/policies/` (Pundit policy specs) | `internal/auth/*_test.go` | RBAC permission checks |
| `spec/integration/` (integration specs) | `tests/e2e/*_test.go` | Full flow scenarios |
| `spec/jobs/` (Sidekiq job specs) | `internal/worker/*_test.go` | Background task processing |
| FactoryBot fixtures | SQLite in-memory GORM seeds | Test data setup |
| Shoulda Matchers | testify/assert + custom validators | Assertion helpers |
## Running the Report
```bash
# Quick unit test coverage
./scripts/coverage/generate_report.sh --quick
# Full coverage with HTML report
./scripts/coverage/generate_report.sh --html
# Include E2E tests
./scripts/coverage/generate_report.sh --e2e --html
# Include benchmarks
./scripts/coverage/generate_report.sh --bench --html
```
## Continuous Improvement
Coverage targets should be reviewed quarterly. As new features are added:
1. Each new module must have tests before merge
2. Coverage must not decrease on existing modules
3. Critical paths (auth, payments, data integrity) require 90%+ coverage
4. Use `go test -race` to catch concurrent access issues