Feat: Tambahkan unit & integration tests untuk lifecycle API key#1684
Open
pandigresik wants to merge 3 commits into
Open
Feat: Tambahkan unit & integration tests untuk lifecycle API key#1684pandigresik wants to merge 3 commits into
pandigresik wants to merge 3 commits into
Conversation
Contributor
|
🔄 AI PR Review sedang antri di server...
|
…DatabaseRestoreTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Feat: Tambahkan unit & integration tests untuk lifecycle API key (#1675)
Description
Menambahkan unit tests dan integration tests di OpenDK yang men-cover seluruh lifecycle API key: pembuatan, validasi, revocation/disable, scope enforcement, dan audit logging. Tests menggunakan SQLite in-memory sehingga dapat dijalankan tanpa dependensi MySQL, menjadikannya cocok untuk CI.
Changes made:
ApiKeymodel dengan status constants (active/revoked/disabled/expired), helper methods (isActive, isExpired, hasScope), dan key generation utilities.ApiKeyAuditLogmodel untuk mencatat setiap operasi API key (created, validated, revoked, disabled).KeyServiceyang mengelola lifecycle API key: create, validate (dengan scope check), revoke, disable, enable, dan audit logging.ApiKeyControllerdengan endpoint CRUD (index, store, show, revoke, destroy) yang menggunakanStoreApiKeyRequestuntuk validasi.ApiKeyMiddlewareyang memvalidasi API key dari bearer token, mendukung optional scope parameter, dan mengembalikan status code yang sesuai (401/403).StoreApiKeyRequestuntuk validasi input pembuatan API key (name required, scopes optional array, expires_at optional date).api-keysdengan middlewareauth:api(JWT auth tanpatoken.registered), dan routekey/validatedengan middlewareapi.key.api_keysdanapi_key_audit_logsdengan foreign key keusersmenggunakanunsignedInteger(compatibility dengan strukturusers.idexisting).ApiKeyFactory(dengan states: revoked, disabled, expired, withScope, withRawKey) danSamplePayloadFactory(dengan state: penduduk).ApiKeyIntegrationTest) yang menguji controller + middleware + database menggunakan SQLite in-memory.KeyServiceTest) yang menguji KeyService langsung (create, validate, revoke, disable/enable, scope, audit log).ApiKeyTestCasebase class yang force SQLite in-memory sebelum app boot, danWithApiKeyTestingtrait yang membuat schema SQLite-compatible.phpunit.xmldari atribut deprecated (beStrictAboutTodoAnnotatedTests, verbose, processUncoveredFiles, crap4j, phpcov) untuk kompatibilitas dengan PHPUnit 12.api.keydibootstrap/app.php.Reason for change:
Impact of change:
✅ Test Coverage: Module API key memiliki minimal 80% test coverage dengan 36 tests (101 assertions) yang menjalankan seluruh lifecycle.
✅ CI Compatibility: Tests dapat dijalankan dengan
php artisan test --testsuite=ApiKeytanpa MySQL, sehingga lebih cepat dan reliable di CI.✅ Code Quality: Penggunaan FormRequest untuk validasi, middleware untuk autentikasi, dan Service layer untuk business logic menjadikan kode lebih terstruktur dan maintainable.
✅ Negative Cases: Edge cases seperti revoked key, disabled key, insufficient scope, dan idempotency sudah ter-cover dalam tests.
Related Issue
Steps to Reproduce
Before (no tests):
After (with tests):
php artisan test --testsuite=ApiKeyTesting on related features:
Checklist
Technical Details
Technical Explanation
API Key Lifecycle Flow:
Test Architecture:
ApiKeyTestCaseextendsBaseTestCasedenganCreatesApplication,WithApiKeyTesting,WithSettingAplikasisetUpBeforeClass()force$_ENV['DB_CONNECTION'] = 'sqlite'sebelum app boot untuk override.env.testingyang menggunakan MySQLWithApiKeyTestingtrait membuat schema SQLite-compatible (tanpaALTER TABLE CHANGEyang tidak didukung SQLite)tearDown()Key Design Decisions:
users.iddi project ini menggunakanint unsigned(32-bit), sehingga FK keusersharus menggunakanunsignedIntegerbukanforeignId(yang defaultunsignedBigInteger)api-keyshanya membutuhkanauth:apimiddleware (tanpatoken.registered) karena management API keys adalah operasi autentikasi itu sendiriKeyService::validate()menggunakanHash::check()untuk membandingkan raw key dengan hashed key di database, sehingga raw key tidak pernah disimpanConfiguration changes
phpunit.xml: Hapus atribut deprecated (beStrictAboutTodoAnnotatedTests, verbose, processUncoveredFiles, crap4j, phpcov) dan tambahkan testsuiteApiKeybootstrap/app.php: Register middlewareapi.key→ApiKeyMiddleware::classroutes/api.php: Tambahkan route groupapi-keys(denganauth:api) dankey/validate(denganapi.key)Dependencies added
No new dependencies.
Testing
Automated Testing
Manual Testing
php artisan migrateuntuk membuat tabel api_keys dan api_key_audit_logsapi.keyBreaking Changes
None
Migration Guide
Jalankan
php artisan migrateuntuk membuat tabel baru:api_keys: Menyimpan data API key (hashed) milik setiap userapi_key_audit_logs: Mencatat setiap operasi API key (create, validate, revoke, disable)References
Additional notes:
SamplePayloadFactorydisediakan untuk test data payload API, dapat digunakan untuk integration testing lebih lanjutWithApiKeyTestingtrait dapat direuse untuk test lain yang membutuhkan schema users/das_setting di SQLite