From e4855c9cf89f9a77f988e78c08925d568662cea3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9D=BC=ED=98=81?= Date: Thu, 3 Sep 2026 18:47:50 +0900 Subject: [PATCH 1/2] =?UTF-8?q?refactor(platform):=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=EB=A7=8C=20=EC=B0=B8=EC=A1=B0=ED=95=98=EB=8D=98=20bui?= =?UTF-8?q?ld-logic=C2=B7app=20=EC=84=A0=EC=96=B8=209=EA=B0=9C=EB=A5=BC=20?= =?UTF-8?q?private=20=EB=A1=9C=20=EC=A4=84=EC=9D=B8=EB=8B=A4=20(#1671)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 테스트 소스는 프로덕션 공개 범위의 근거가 될 수 없다. 이슈가 세어 둔 11개 후보를 현재 develop(8cbd5d812)에서 전수 재판정해, 프로덕션 참조가 같은 파일 안에만 있는 9개를 private 로 좁혔다. 후보 5개 파일은 이슈 기준 커밋(dcd8a8ec9) 이후 변경이 0줄이라 파일·행·심볼이 그대로 유효했다 — 해소된 항목은 없다. 남긴 둘은 MainViewModel.pendingNotificationEntry 와 consumeNotificationEntry() 다. 이슈는 「예정된 adapter 를 실제로 연결하거나 미완성 API 를 제거」하라고 적었는데, 앞쪽이 열린 PR #1641 의 NotificationEntryEffect.kt 에서 이미 코드로 서 있다. 지금 지우면 그 PR 이 컴파일되지 않는다. 같은 이유로 확인한 NotificationIntentContract.resolve() 는 #1641 도 소비처를 만들지 않아(파라미터만 추가) 함께 좁혔다. 좁힌 선언을 참조하던 테스트는 전부 owner 의 관찰 가능한 동작으로 다시 썼다. @VisibleForTesting 도, 테스트를 살리기 위한 internal 유지도 없다. - BuildFingerprintTest 는 Gradle TestKit 으로 스텁 프로젝트를 돌려 빌드에 최종 적용되는 versionName 접미사를 고정한다. 검증 대상이 계산식이 아니라 QA 가 dumpsys 로 읽을 값이라는 점에서도 이 방향이 맞다. 환경변수는 매번 명시적으로 넘긴다 — CI 러너에 GITHUB_SHA 가 이미 있어 git 경로 테스트가 조용히 CI 경로로 새면 로컬에서만 초록인 테스트가 된다. - VersionCodeTest 는 기대값을 프로덕션 상수 대신 리터럴로 적는다. 상수끼리 비교하면 값이 바뀌어도 초록이라 계약을 아무도 지키지 않는다. - FcmNotificationContentResolverTest 를 AfternoteFirebaseMessagingServiceTest 로 옮겨 Robolectric 에서 실제 onMessageReceived 를 돌리고 게시된 알림을 읽는다. occurrence tag 같은 내부 개념도 「같은 발생은 하나로 합쳐지고 다른 발생은 둘로 남는다」로 바꿔 단언했다. - NotificationIntentContractTest 는 진짜 Intent 로 fromIntent() 를 부른다. 더해 NotificationPendingIntentFactory 가 만든 PendingIntent 를 되읽는 왕복 테스트를 넣었다 — 쓰는 쪽과 읽는 쪽이 같은 extra 키를 쓰는지는 왕복으로만 확인된다. konsist 의 ProductionVisibilityKonsistTest 는 checkExact 라 해소된 항목이 목록에 남으면 stale 로 실패한다. ISSUE_1671_PLATFORM 의 8건을 지우고 자리는 빈 set 으로 남겼다. 형제 이슈의 목록은 건드리지 않았다. --- .../AfternoteFirebaseMessagingService.kt | 6 +- .../NotificationIntentContract.kt | 6 +- .../AfternoteFirebaseMessagingServiceTest.kt | 147 ++++++++++++++++++ .../FcmNotificationContentResolverTest.kt | 81 ---------- .../NotificationIntentContractTest.kt | 84 ++++++---- .../src/main/kotlin/BuildFingerprint.kt | 6 +- build-logic/src/main/kotlin/VersionCode.kt | 4 +- .../src/test/kotlin/BuildFingerprintTest.kt | 133 +++++++++++++--- .../src/test/kotlin/VersionCodeTest.kt | 11 +- .../ProductionVisibilityKonsistTest.kt | 13 +- 10 files changed, 340 insertions(+), 151 deletions(-) create mode 100644 app/src/test/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingServiceTest.kt delete mode 100644 app/src/test/java/com/afternote/afternote_fe/messaging/FcmNotificationContentResolverTest.kt diff --git a/app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt b/app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt index c4bc384aec..7742570f30 100644 --- a/app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt +++ b/app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt @@ -115,12 +115,12 @@ class AfternoteFirebaseMessagingService : FirebaseMessagingService() { } } -internal data class FcmNotificationContent( +private data class FcmNotificationContent( val title: String, val body: String?, ) -internal object FcmNotificationIdentity { +private object FcmNotificationIdentity { fun occurrenceId(messageId: String?): String = messageId ?.takeIf(String::isNotBlank) @@ -130,7 +130,7 @@ internal object FcmNotificationIdentity { fun notificationTag(occurrenceId: String): String = "fcm:$occurrenceId" } -internal object FcmNotificationContentResolver { +private object FcmNotificationContentResolver { fun resolve( notificationTitle: String?, notificationBody: String?, diff --git a/app/src/main/java/com/afternote/afternote_fe/notification/NotificationIntentContract.kt b/app/src/main/java/com/afternote/afternote_fe/notification/NotificationIntentContract.kt index d6fcf99cd2..21e0601b35 100644 --- a/app/src/main/java/com/afternote/afternote_fe/notification/NotificationIntentContract.kt +++ b/app/src/main/java/com/afternote/afternote_fe/notification/NotificationIntentContract.kt @@ -52,7 +52,11 @@ internal object NotificationIntentContract { }.getOrNull(), ) - internal fun resolve( + /** + * Intent 에서 꺼낸 원시 값만 받아 판정한다. `Intent` 를 직접 읽지 않는 덕에 «무엇을 거부하는가» + * 가 Android API 접근과 섞이지 않는다. 밖에서는 [fromIntent] 하나로만 들어온다. + */ + private fun resolve( isNotificationEntry: Boolean, rawSource: String?, occurrenceId: String?, diff --git a/app/src/test/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingServiceTest.kt b/app/src/test/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingServiceTest.kt new file mode 100644 index 0000000000..7a863ba1d9 --- /dev/null +++ b/app/src/test/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingServiceTest.kt @@ -0,0 +1,147 @@ +package com.afternote.afternote_fe.messaging + +import android.Manifest +import android.app.Application +import android.app.Notification +import android.app.NotificationManager +import android.os.Bundle +import com.google.firebase.messaging.RemoteMessage +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +/** + * FCM 메시지 한 건이 실제로 어떤 알림이 되는지의 회귀 기준. + * + * 제목·본문 결정과 occurrence 식별은 `AfternoteFirebaseMessagingService.kt` 안에서만 쓰이는 + * file-local 구현이라 직접 부르지 않는다 (#1671). 대신 Firebase 가 부르는 `onMessageReceived` + * 에 진짜 [RemoteMessage] 를 넣고 **게시된 알림**을 읽는다. + * + * 그래서 «occurrence 별 tag» 같은 내부 개념도 밖에서 보이는 결과로 바꿔 단언한다 — 같은 발생을 + * 두 번 받으면 알림이 하나로 합쳐지고, 다른 발생이면 둘로 남는 것이 그 tag 가 존재하는 이유다. + * + * `onCreate()` 는 부르지 않는다. Hilt 진입점이라 주입이 먼저 도는데 이 테스트가 검증하는 경로는 + * 주입된 협력자를 쓰지 않는다. 알림 채널은 `GlobalApplication` 이 하듯 여기서 직접 만든다. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35], application = Application::class) +class AfternoteFirebaseMessagingServiceTest { + private lateinit var service: AfternoteFirebaseMessagingService + + @Before + fun setUp() { + val application = RuntimeEnvironment.getApplication() + shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS) + FcmNotificationChannel.create(application) + service = Robolectric.buildService(AfternoteFirebaseMessagingService::class.java).get() + } + + @Test + fun `notification payload가 data payload보다 우선한다`() { + service.onMessageReceived( + remoteMessage( + notificationTitle = "알림 제목", + notificationBody = "알림 본문", + data = mapOf("title" to "data 제목", "body" to "data 본문"), + ), + ) + + assertEquals("알림 제목", contentTitleOfSingleNotification()) + assertEquals("알림 본문", contentTextOfSingleNotification()) + } + + @Test + fun `제목이 없으면 fallback 제목으로 알림을 띄운다`() { + service.onMessageReceived(remoteMessage(data = mapOf("body" to "data 본문"))) + + assertEquals("AFTERNOTE", contentTitleOfSingleNotification()) + assertEquals("data 본문", contentTextOfSingleNotification()) + } + + @Test + fun `제목도 본문도 없는 메시지는 알림을 만들지 않는다`() { + service.onMessageReceived( + remoteMessage(notificationTitle = " ", data = mapOf("body" to "")), + ) + + assertEquals(0, postedNotifications().size) + } + + @Test + fun `같은 message id를 다시 받으면 알림이 하나로 합쳐진다`() { + service.onMessageReceived(remoteMessage(messageId = "message-1", notificationTitle = "첫 번째")) + service.onMessageReceived(remoteMessage(messageId = "message-1", notificationTitle = "다시 온 같은 발생")) + + assertEquals(1, postedNotifications().size) + assertEquals("다시 온 같은 발생", contentTitleOfSingleNotification()) + } + + @Test + fun `서로 다른 message id는 각각 남는다`() { + service.onMessageReceived(remoteMessage(messageId = "message-1", notificationTitle = "첫 번째")) + service.onMessageReceived(remoteMessage(messageId = "message-2", notificationTitle = "두 번째")) + + assertEquals(2, postedNotifications().size) + } + + @Test + fun `Java hash가 충돌하는 message id도 서로 다른 알림으로 남는다`() { + assertEquals("Aa".hashCode(), "BB".hashCode()) + + service.onMessageReceived(remoteMessage(messageId = "Aa", notificationTitle = "첫 번째")) + service.onMessageReceived(remoteMessage(messageId = "BB", notificationTitle = "두 번째")) + + assertEquals(2, postedNotifications().size) + } + + @Test + fun `message id가 없는 메시지는 발생마다 따로 남는다`() { + service.onMessageReceived(remoteMessage(messageId = null, notificationTitle = "첫 번째")) + service.onMessageReceived(remoteMessage(messageId = " ", notificationTitle = "두 번째")) + + assertEquals(2, postedNotifications().size) + } + + private fun postedNotifications(): List { + val manager = RuntimeEnvironment.getApplication().getSystemService(NotificationManager::class.java) + return shadowOf(manager).allNotifications + } + + private fun contentTitleOfSingleNotification(): String = shadowOf(singleNotification()).contentTitle.toString() + + private fun contentTextOfSingleNotification(): String = shadowOf(singleNotification()).contentText.toString() + + private fun singleNotification(): Notification { + val notifications = postedNotifications() + assertEquals("알림이 정확히 하나 게시돼야 한다", 1, notifications.size) + return notifications.single() + } + + /** + * FCM 이 전달하는 그대로의 wire payload 를 만든다. `gcm.n.*` 는 notification payload, + * 접두사 없는 키는 data payload, `google.message_id` 는 발생 식별자다. + */ + private fun remoteMessage( + notificationTitle: String? = null, + notificationBody: String? = null, + data: Map = emptyMap(), + messageId: String? = "message-1", + ): RemoteMessage = + RemoteMessage( + Bundle().apply { + messageId?.let { putString("google.message_id", it) } + if (notificationTitle != null || notificationBody != null) { + putString("gcm.n.e", "1") + notificationTitle?.let { putString("gcm.n.title", it) } + notificationBody?.let { putString("gcm.n.body", it) } + } + data.forEach { (key, value) -> putString(key, value) } + }, + ) +} diff --git a/app/src/test/java/com/afternote/afternote_fe/messaging/FcmNotificationContentResolverTest.kt b/app/src/test/java/com/afternote/afternote_fe/messaging/FcmNotificationContentResolverTest.kt deleted file mode 100644 index 0f16c9dbef..0000000000 --- a/app/src/test/java/com/afternote/afternote_fe/messaging/FcmNotificationContentResolverTest.kt +++ /dev/null @@ -1,81 +0,0 @@ -package com.afternote.afternote_fe.messaging - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNotEquals -import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue -import org.junit.Test - -class FcmNotificationContentResolverTest { - @Test - fun `notification payload takes priority over data payload`() { - val content = - FcmNotificationContentResolver.resolve( - notificationTitle = "알림 제목", - notificationBody = "알림 본문", - data = mapOf("title" to "data 제목", "body" to "data 본문"), - fallbackTitle = "AFTERNOTE", - ) - - assertEquals(FcmNotificationContent(title = "알림 제목", body = "알림 본문"), content) - } - - @Test - fun `data body uses fallback title when title is absent`() { - val content = - FcmNotificationContentResolver.resolve( - notificationTitle = null, - notificationBody = null, - data = mapOf("body" to "data 본문"), - fallbackTitle = "AFTERNOTE", - ) - - assertEquals(FcmNotificationContent(title = "AFTERNOTE", body = "data 본문"), content) - } - - @Test - fun `blank payload does not create a notification`() { - val content = - FcmNotificationContentResolver.resolve( - notificationTitle = " ", - notificationBody = null, - data = mapOf("body" to ""), - fallbackTitle = "AFTERNOTE", - ) - - assertNull(content) - } - - @Test - fun `message id가 있으면 occurrence token으로 보존한다`() { - assertEquals("message-1", FcmNotificationIdentity.occurrenceId("message-1")) - } - - @Test - fun `message id가 없거나 blank이면 매 발생마다 고유 token을 만든다`() { - val missing = FcmNotificationIdentity.occurrenceId(null) - val blank = FcmNotificationIdentity.occurrenceId(" ") - - assertTrue(missing.isNotBlank()) - assertTrue(blank.isNotBlank()) - assertNotEquals(missing, blank) - } - - @Test - fun `notification tag는 occurrence마다 다르고 프로세스 상태와 무관하게 결정적이다`() { - val first = FcmNotificationIdentity.notificationTag("occurrence-1") - - assertEquals(first, FcmNotificationIdentity.notificationTag("occurrence-1")) - assertNotEquals(first, FcmNotificationIdentity.notificationTag("occurrence-2")) - } - - @Test - fun `Java hash가 충돌하는 message id도 서로 다른 notification tag를 만든다`() { - assertEquals("Aa".hashCode(), "BB".hashCode()) - - val first = FcmNotificationIdentity.notificationTag("Aa") - val second = FcmNotificationIdentity.notificationTag("BB") - - assertNotEquals(first, second) - } -} diff --git a/app/src/test/java/com/afternote/afternote_fe/notification/NotificationIntentContractTest.kt b/app/src/test/java/com/afternote/afternote_fe/notification/NotificationIntentContractTest.kt index 774d5d65d7..d12223c289 100644 --- a/app/src/test/java/com/afternote/afternote_fe/notification/NotificationIntentContractTest.kt +++ b/app/src/test/java/com/afternote/afternote_fe/notification/NotificationIntentContractTest.kt @@ -1,47 +1,50 @@ package com.afternote.afternote_fe.notification +import android.app.Application +import android.content.Intent +import com.afternote.core.common.notification.NotificationPendingIntentFactory import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +/** + * 알림 진입 Intent 해석 계약의 회귀 기준. + * + * 판정 자체는 `fromIntent()` 뒤의 file-local 구현이라 직접 부르지 않는다 (#1671). 대신 + * `MainActivity` 가 실제로 부르는 `fromIntent(Intent)` 에 진짜 [Intent] 를 넣는다 — 그래야 + * extra 키 이름과 타입까지 계약에 포함된다. 값을 꺼내는 쪽만 검증하면 키를 바꿔 쓰는 회귀는 + * 지나간다. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35], application = Application::class) class NotificationIntentContractTest { @Test fun `marker 없는 일반 launcher 진입은 알림 이벤트가 아니다`() { - val request = - NotificationIntentContract.resolve( - isNotificationEntry = false, - rawSource = "fcm", - occurrenceId = "occurrence-1", - ) - - assertNull(request) + assertNull(NotificationIntentContract.fromIntent(Intent(Intent.ACTION_MAIN))) + assertNull(NotificationIntentContract.fromIntent(notificationIntent(isNotificationEntry = false))) } @Test fun `알 수 없거나 비어 있는 source는 거부한다`() { listOf(null, "", " ", "unknown").forEach { rawSource -> - val request = - NotificationIntentContract.resolve( - isNotificationEntry = true, - rawSource = rawSource, - occurrenceId = "occurrence-1", - ) + val request = NotificationIntentContract.fromIntent(notificationIntent(source = rawSource)) - assertNull(request) + assertNull("source '$rawSource' 를 받으면 안 된다", request) } } @Test fun `occurrence token이 없거나 비어 있으면 거부한다`() { listOf(null, "", " ").forEach { occurrenceId -> - val request = - NotificationIntentContract.resolve( - isNotificationEntry = true, - rawSource = "daily", - occurrenceId = occurrenceId, - ) + val request = NotificationIntentContract.fromIntent(notificationIntent(occurrenceId = occurrenceId)) - assertNull(request) + assertNull("occurrence '$occurrenceId' 를 받으면 안 된다", request) } } @@ -49,14 +52,43 @@ class NotificationIntentContractTest { fun `허용한 source와 occurrence token만 내부 요청으로 보존한다`() { NotificationEntrySource.entries.forEach { source -> val request = - NotificationIntentContract.resolve( - isNotificationEntry = true, - rawSource = source.contractValue, - occurrenceId = "occurrence-${source.contractValue}", + NotificationIntentContract.fromIntent( + notificationIntent( + source = source.contractValue, + occurrenceId = "occurrence-${source.contractValue}", + ), ) assertEquals(source, request?.source) assertEquals("occurrence-${source.contractValue}", request?.occurrenceId) } } + + @Test + fun `알림을 만든 PendingIntent 를 그대로 되읽는다`() { + // 쓰는 쪽(core:common)과 읽는 쪽(app)이 같은 키 계약을 쓰는지는 왕복으로만 확인된다. + val pendingIntent = + NotificationPendingIntentFactory.create( + context = RuntimeEnvironment.getApplication(), + source = NotificationEntrySource.DAILY.contractValue, + occurrenceId = "occurrence-1", + ) + assertNotNull("런처 Intent 를 찾지 못해 PendingIntent 가 만들어지지 않았다", pendingIntent) + + val request = NotificationIntentContract.fromIntent(shadowOf(pendingIntent!!).savedIntent) + + assertEquals(NotificationEntrySource.DAILY, request?.source) + assertEquals("occurrence-1", request?.occurrenceId) + } + + private fun notificationIntent( + isNotificationEntry: Boolean = true, + source: String? = NotificationEntrySource.FCM.contractValue, + occurrenceId: String? = "occurrence-1", + ): Intent = + Intent(Intent.ACTION_MAIN).apply { + putExtra(NotificationPendingIntentFactory.EXTRA_NOTIFICATION_ENTRY, isNotificationEntry) + source?.let { putExtra(NotificationPendingIntentFactory.EXTRA_NOTIFICATION_SOURCE, it) } + occurrenceId?.let { putExtra(NotificationPendingIntentFactory.EXTRA_NOTIFICATION_OCCURRENCE_TOKEN, it) } + } } diff --git a/build-logic/src/main/kotlin/BuildFingerprint.kt b/build-logic/src/main/kotlin/BuildFingerprint.kt index 21197cc51b..9ac618827a 100644 --- a/build-logic/src/main/kotlin/BuildFingerprint.kt +++ b/build-logic/src/main/kotlin/BuildFingerprint.kt @@ -9,7 +9,7 @@ import javax.inject.Inject const val CI_COMMIT_SHA_ENV = "GITHUB_SHA" const val SHORT_COMMIT_SHA_LENGTH = 7 -const val UNKNOWN_COMMIT_MARKER = "unknown" +private const val UNKNOWN_COMMIT_MARKER = "unknown" /** * debug `versionName` 에 붙일 빌드 지문을 만든다 — `1.0+a3f91c2` · `1.0+a3f91c2-dirty` · `1.0+unknown`. @@ -23,7 +23,7 @@ const val UNKNOWN_COMMIT_MARKER = "unknown" * [UNKNOWN_COMMIT_MARKER] 를 남기는 것도 같은 이유다 — 접미사 없는 `1.0` 은 "sha 를 못 읽었다"와 * "이 기능이 없던 빌드"를 구분해 주지 않아, 없는 근거를 만들 여지를 남긴다. */ -fun debugVersionNameSuffix( +private fun debugVersionNameSuffix( rawCommitSha: String?, hasUncommittedChanges: Boolean, ): String { @@ -37,7 +37,7 @@ fun debugVersionNameSuffix( * 입력이 두 갈래라 정규화가 필요하다 — CI 의 `GITHUB_SHA` 도 로컬 `git rev-parse HEAD` 도 40자다. * QA 대장 파일명(`docs/qa/evidence/.json`)과 대조하려면 자릿수가 일정해야 한다. */ -fun shortCommitSha(rawCommitSha: String?): String? { +private fun shortCommitSha(rawCommitSha: String?): String? { val value = rawCommitSha?.trim()?.lowercase() ?: return null if (!value.matches(Regex("[0-9a-f]{$SHORT_COMMIT_SHA_LENGTH,40}"))) return null return value.take(SHORT_COMMIT_SHA_LENGTH) diff --git a/build-logic/src/main/kotlin/VersionCode.kt b/build-logic/src/main/kotlin/VersionCode.kt index cc6a9babab..6f8b55737d 100644 --- a/build-logic/src/main/kotlin/VersionCode.kt +++ b/build-logic/src/main/kotlin/VersionCode.kt @@ -1,8 +1,8 @@ import org.gradle.api.GradleException const val AFTERNOTE_VERSION_CODE_ENV = "AFTERNOTE_VERSION_CODE" -const val DEFAULT_AFTERNOTE_VERSION_CODE = 1 -const val MAX_PLAY_VERSION_CODE = 2_100_000_000 +private const val DEFAULT_AFTERNOTE_VERSION_CODE = 1 +private const val MAX_PLAY_VERSION_CODE = 2_100_000_000 /** * Keeps ordinary local/Firebase builds on the existing versionCode while allowing an approved Play diff --git a/build-logic/src/test/kotlin/BuildFingerprintTest.kt b/build-logic/src/test/kotlin/BuildFingerprintTest.kt index 366fb7f308..14c0fb96c8 100644 --- a/build-logic/src/test/kotlin/BuildFingerprintTest.kt +++ b/build-logic/src/test/kotlin/BuildFingerprintTest.kt @@ -1,43 +1,132 @@ +import org.gradle.testkit.runner.GradleRunner import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Rule import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +/** + * debug `versionName` 접미사의 빌드 계약 회귀 테스트 (Gradle TestKit). + * + * 지문을 만드는 두 함수는 `BuildFingerprint.kt` 안에서만 쓰이는 file-local 구현이라 테스트가 + * 직접 부르지 않는다 (#1671). 대신 빌드 스크립트가 실제로 부르는 `resolveDebugVersionNameSuffix()` + * 를 스텁 프로젝트에서 돌려 **빌드에 최종 적용되는 문자열**을 고정한다 — 검증 대상이 계산식이 + * 아니라 «QA 가 `dumpsys` 로 읽게 될 값» 이라는 점도 이 방향이 맞다(#1135). + * + * 환경변수를 매번 명시적으로 넘긴다. CI 러너에는 `GITHUB_SHA` 가 이미 있어서, git 경로를 검증하는 + * 테스트가 조용히 CI 경로로 새어 들어가면 로컬에서만 초록인 테스트가 된다. + */ class BuildFingerprintTest { - private val fullSha = "a3f91c2b8d4e5f60718293a4b5c6d7e8f9012345" + @get:Rule + val projectDir = TemporaryFolder() - @Test - fun `커밋을 읽었고 워킹트리가 깨끗하면 short sha 만 붙인다`() { - assertEquals("+a3f91c2", debugVersionNameSuffix(fullSha, hasUncommittedChanges = false)) + @Before + fun setUp() { + writeStubProject() } @Test - fun `커밋 안 된 변경이 있으면 dirty 를 함께 붙인다`() { - assertEquals("+a3f91c2-dirty", debugVersionNameSuffix(fullSha, hasUncommittedChanges = true)) + fun `CI 는 GITHUB_SHA 를 다듬어 앞 7자리만 붙인다`() { + assertEquals("+a3f91c2", suffixWithCommitSha(" A3F91C2B8D4E5F60718293A4B5C6D7E8F9012345 ")) } @Test - fun `커밋을 특정할 수 없으면 접미사를 생략하지 않고 unknown 을 남긴다`() { - assertEquals("+$UNKNOWN_COMMIT_MARKER", debugVersionNameSuffix(null, hasUncommittedChanges = false)) - // 커밋을 모르면 무엇 대비 dirty 인지도 말할 수 없다 — dirty 를 붙이지 않는다. - assertEquals("+$UNKNOWN_COMMIT_MARKER", debugVersionNameSuffix(null, hasUncommittedChanges = true)) + fun `16진수가 아닌 GITHUB_SHA 는 커밋으로 받지 않고 unknown 을 남긴다`() { + // 접미사를 생략하면 «sha 를 못 읽었다» 와 «이 기능이 없던 빌드» 를 구분할 수 없다. + assertEquals("+unknown", suffixWithCommitSha("not-a-sha")) } @Test - fun `sha 는 앞 7자리로 정규화한다`() { - assertEquals("a3f91c2", shortCommitSha(fullSha)) - assertEquals("a3f91c2", shortCommitSha("a3f91c2")) - assertEquals("a3f91c2", shortCommitSha(" A3F91C2B8D \n")) + fun `커밋을 특정할 수 없는 빌드에도 접미사를 남긴다`() { + // git 저장소가 아니라 rev-parse 가 실패한다. 커밋을 모르면 dirty 도 말할 수 없어 붙이지 않는다. + assertEquals("+unknown", suffixFromGitWorkingTree()) } @Test - fun `16진수가 아니거나 7자리에 못 미치는 값은 커밋으로 받지 않는다`() { - listOf("", " ", "a3f91c", "z3f91c2", "a3f91c2-dirty", "HEAD", "$fullSha" + "0").forEach { invalid -> - assertNull("커밋으로 받으면 안 된다: '$invalid'", shortCommitSha(invalid)) - } + fun `워킹트리가 깨끗하면 short sha 만 붙이고 변경이 있으면 dirty 를 함께 붙인다`() { + val shortSha = initGitRepositoryWithSingleCommit() + + assertEquals("+$shortSha", suffixFromGitWorkingTree()) + + projectDir.newFile("uncommitted.txt").writeText("edited\n") + + // untracked 도 dirty 로 센다 — 거짓 clean 은 검증하지 않은 코드에 QA 증거를 붙이게 한다. + assertEquals("+$shortSha-dirty", suffixFromGitWorkingTree()) } - @Test - fun `정규화에 실패한 값은 커밋 없이 빌드한 것과 같게 다룬다`() { - assertEquals("+$UNKNOWN_COMMIT_MARKER", debugVersionNameSuffix("not-a-sha", hasUncommittedChanges = false)) + private fun suffixWithCommitSha(ciCommitSha: String): String = resolvedSuffix(System.getenv() + mapOf(CI_COMMIT_SHA to ciCommitSha)) + + private fun suffixFromGitWorkingTree(): String = resolvedSuffix(System.getenv() - CI_COMMIT_SHA) + + private fun resolvedSuffix(environment: Map): String { + val output = + GradleRunner + .create() + .withProjectDir(projectDir.root) + .withEnvironment(environment) + .withArguments("showBuildFingerprint") + .build() + .output + + return SUFFIX_MARKER.find(output)?.groupValues?.get(1) + ?: error("빌드 출력에서 접미사를 찾지 못했다:\n$output") + } + + /** 스텁 프로젝트를 git 저장소로 만들고 커밋한 뒤 기대 short sha 를 돌려준다. */ + private fun initGitRepositoryWithSingleCommit(): String { + // Gradle 이 빌드마다 만드는 산출물까지 dirty 로 세면 clean 경로를 검증할 수 없다. + projectDir.newFile(".gitignore").writeText(".gradle/\nbuild/\n") + git("init") + git("add", "--all") + git("-c", "user.email=build-logic@example.com", "-c", "user.name=build-logic", "commit", "--message", "stub") + return git("rev-parse", "HEAD").take(7) + } + + private fun git(vararg arguments: String): String { + val process = + ProcessBuilder(listOf("git", *arguments)) + .directory(projectDir.root) + .redirectErrorStream(true) + .start() + val output = + process.inputStream + .bufferedReader() + .readText() + .trim() + val exitCode = process.waitFor() + check(exitCode == 0) { "git ${arguments.joinToString(" ")} 실패($exitCode):\n$output" } + return output + } + + private fun writeStubProject() { + val classpathLiteral = + guardClasspath() + .split(File.pathSeparator) + .filter { it.isNotBlank() } + .joinToString(", ") { "\"${it.replace("\\", "/")}\"" } + projectDir.newFile("settings.gradle.kts").writeText("rootProject.name = \"fingerprint-stub\"\n") + projectDir.newFile("build.gradle.kts").writeText( + """ + buildscript { + dependencies { + classpath(files($classpathLiteral)) + } + } + + println("suffix=[" + resolveDebugVersionNameSuffix() + "]") + + tasks.register("showBuildFingerprint") + """.trimIndent() + "\n", + ) + } + + private fun guardClasspath(): String = + System.getProperty("guardClasspath") + ?: error("guardClasspath 시스템 프로퍼티 누락 — build-logic/build.gradle.kts 의 Test 태스크 설정 참고") + + private companion object { + const val CI_COMMIT_SHA = "GITHUB_SHA" + val SUFFIX_MARKER = Regex("suffix=\\[(.*)]") } } diff --git a/build-logic/src/test/kotlin/VersionCodeTest.kt b/build-logic/src/test/kotlin/VersionCodeTest.kt index 6d74b55ac0..0288fffb83 100644 --- a/build-logic/src/test/kotlin/VersionCodeTest.kt +++ b/build-logic/src/test/kotlin/VersionCodeTest.kt @@ -3,16 +3,23 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertThrows import org.junit.Test +/** + * `versionCode` 주입 계약의 회귀 기준. + * + * 기대값을 프로덕션 상수로 쓰지 않고 리터럴로 적는다 (#1671). 상수끼리 비교하면 값이 바뀌어도 + * 테스트는 계속 통과해 «Play 상한이 2_100_000_000 이다» 라는 계약을 아무도 지키지 않는다. + * 여기 적힌 숫자가 바뀌어야 할 때는 계약이 바뀐 때뿐이다. + */ class VersionCodeTest { @Test fun `override가 없으면 기존 versionCode를 유지한다`() { - assertEquals(DEFAULT_AFTERNOTE_VERSION_CODE, resolveAfternoteVersionCode(null)) + assertEquals(1, resolveAfternoteVersionCode(null)) } @Test fun `유효한 Play versionCode를 주입한다`() { assertEquals(101, resolveAfternoteVersionCode("101")) - assertEquals(MAX_PLAY_VERSION_CODE, resolveAfternoteVersionCode("$MAX_PLAY_VERSION_CODE")) + assertEquals(2_100_000_000, resolveAfternoteVersionCode("2100000000")) } @Test diff --git a/konsist/src/test/kotlin/com/afternote/konsist/ProductionVisibilityKonsistTest.kt b/konsist/src/test/kotlin/com/afternote/konsist/ProductionVisibilityKonsistTest.kt index b51b77e408..91992b23a4 100644 --- a/konsist/src/test/kotlin/com/afternote/konsist/ProductionVisibilityKonsistTest.kt +++ b/konsist/src/test/kotlin/com/afternote/konsist/ProductionVisibilityKonsistTest.kt @@ -281,17 +281,8 @@ class ProductionVisibilityKonsistTest { } private companion object { - val ISSUE_1671_PLATFORM = - setOf( - "app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt::class FcmNotificationContent [internal]", - "app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt::object FcmNotificationContentResolver [internal]", - "app/src/main/java/com/afternote/afternote_fe/messaging/AfternoteFirebaseMessagingService.kt::object FcmNotificationIdentity [internal]", - "build-logic/src/main/kotlin/BuildFingerprint.kt::function debugVersionNameSuffix [implicit-public]", - "build-logic/src/main/kotlin/BuildFingerprint.kt::function shortCommitSha [implicit-public]", - "build-logic/src/main/kotlin/BuildFingerprint.kt::property UNKNOWN_COMMIT_MARKER [implicit-public]", - "build-logic/src/main/kotlin/VersionCode.kt::property DEFAULT_AFTERNOTE_VERSION_CODE [implicit-public]", - "build-logic/src/main/kotlin/VersionCode.kt::property MAX_PLAY_VERSION_CODE [implicit-public]", - ) + /** #1671 이 8건을 전부 `private` 로 줄였다. 형제 이슈들이 각자 자기 목록을 비우는 중이라 자리는 남긴다. */ + val ISSUE_1671_PLATFORM = emptySet() val ISSUE_1672_CORE = setOf( From df42c0a3a589251bb2de6e6989048dc15a9e0c61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9D=BC=ED=98=81?= Date: Fri, 4 Sep 2026 01:01:16 +0900 Subject: [PATCH 2/2] =?UTF-8?q?test(platform):=20shortCommitSha=20?= =?UTF-8?q?=EC=9D=98=20=EA=B2=BD=EA=B3=84=20=EC=97=B4=EA=B1=B0=EB=A5=BC=20?= =?UTF-8?q?=EB=90=98=EC=82=B4=EB=A6=B0=EB=8B=A4=20(#1671)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 리뷰 지적 반영. not-a-sha 하나만 남기면 아래 두 회귀를 통과시킨다 — 그 입력에는 7자리 hex 런이 없어 어떤 완화에도 안 걸리기 때문이다. - matches(완전일치)를 containsMatchIn 으로 바꾸면 a3f91c2-dirty 에서 +a3f91c2 라는 거짓 clean 지문이 나온다. KDoc 이 말하는 QA 증거 사고가 이것이다. - {7,40} 하한이 무너지면 6자 입력에서 자릿수가 흔들린다. 두 입력을 같은 테스트에 넣어 Gradle 실행을 3회로 묶었고, 무엇이 무너지면 무엇이 나오는지 표로 적었다. 결정 실험으로 확인했다 — matches 를 containsMatchIn 으로 바꾸자 expected:<+unknown> but was:<+a3f91c2> 로 실패했다. --- .../src/test/kotlin/BuildFingerprintTest.kt | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/build-logic/src/test/kotlin/BuildFingerprintTest.kt b/build-logic/src/test/kotlin/BuildFingerprintTest.kt index 14c0fb96c8..482e5d037c 100644 --- a/build-logic/src/test/kotlin/BuildFingerprintTest.kt +++ b/build-logic/src/test/kotlin/BuildFingerprintTest.kt @@ -31,10 +31,29 @@ class BuildFingerprintTest { assertEquals("+a3f91c2", suffixWithCommitSha(" A3F91C2B8D4E5F60718293A4B5C6D7E8F9012345 ")) } + /** + * 형식에 안 맞는 `GITHUB_SHA` 는 커밋으로 받지 않는다. + * + * **세 입력이 각각 다른 회귀를 잡는다.** 케이스당 Gradle 실행 1회가 들어 한 테스트에 묶었다. + * + * | 입력 | 무너지면 나오는 값 | 무엇이 깨진 것인가 | + * |---|---|---| + * | `not-a-sha` | — | hex 런이 없어 어떤 완화에도 안 걸린다. 기본 경로 | + * | `a3f91c2-dirty` | `+a3f91c2` | `matches`(완전일치)를 `containsMatchIn`/`find` 로 바꾼 것. **거짓 clean 지문** | + * | `a3f91c`(6자) | `+a3f91c` | `{7,40}` 하한이 무너진 것. 자릿수가 흔들린다 | + * + * 가운데가 KDoc 이 말하는 QA 증거 사고 그 자체다 — dirty 빌드가 clean 지문을 달고 나간다. + */ @Test fun `16진수가 아닌 GITHUB_SHA 는 커밋으로 받지 않고 unknown 을 남긴다`() { // 접미사를 생략하면 «sha 를 못 읽었다» 와 «이 기능이 없던 빌드» 를 구분할 수 없다. assertEquals("+unknown", suffixWithCommitSha("not-a-sha")) + + // 부분 일치로 완화하면 여기서 «+a3f91c2» 라는 거짓 clean 지문이 나온다. + assertEquals("+unknown", suffixWithCommitSha("a3f91c2-dirty")) + + // 하한이 무너지면 여기서 «+a3f91c» 로 자릿수가 흔들린다. + assertEquals("+unknown", suffixWithCommitSha("a3f91c")) } @Test