diff --git a/personalization-sdk/build.gradle b/personalization-sdk/build.gradle index a10df113..1f0f174f 100644 --- a/personalization-sdk/build.gradle +++ b/personalization-sdk/build.gradle @@ -139,9 +139,10 @@ dependencies { implementation 'androidx.media3:media3-ui:1.4.1' implementation 'com.google.dagger:dagger:2.51.1' - implementation("androidx.test:core:1.6.1") - implementation("androidx.test:rules:1.6.1") - implementation("androidx.test.ext:junit:1.2.1") + // Instrumented tests only: as `implementation` they reached every host app's release build. + androidTestImplementation("androidx.test:core:1.6.1") + androidTestImplementation("androidx.test:rules:1.6.1") + androidTestImplementation("androidx.test.ext:junit:1.2.1") implementation("com.google.android.gms:play-services-ads-identifier:17.0.0") @@ -149,6 +150,7 @@ dependencies { testImplementation 'junit:junit:4.13.2' testImplementation 'io.mockk:mockk:1.13.11' + testImplementation 'androidx.test:core:1.6.1' testImplementation 'org.robolectric:robolectric:4.12.1' // compileOnly dependencies are absent from the unit test classpath, and the Compose compiler // plugin refuses to compile the test variant without the runtime it can see. These mirror the diff --git a/personalization-sdk/src/main/kotlin/com/personalization/HmsMessagingService.kt b/personalization-sdk/src/main/kotlin/com/personalization/HmsMessagingService.kt index a9fd84b7..561fd526 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/HmsMessagingService.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/HmsMessagingService.kt @@ -22,7 +22,7 @@ class HmsMessagingService : HmsMessageService() { // lazily-registered shop the push targets, so a cold-process push (app not running) reaches // the second shop instead of being dropped for not being live yet. if (data.isNotEmpty()) { - SDK.debug("HMS message data: $data") + SDK.debug("HMS message data keys: ${data.keys}") Rees46.handlePush(data, PushEventType.RECEIVED) } } catch (throwable: Throwable) { diff --git a/personalization-sdk/src/main/kotlin/com/personalization/MessagingService.kt b/personalization-sdk/src/main/kotlin/com/personalization/MessagingService.kt index 13a8acf9..05bbda9d 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/MessagingService.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/MessagingService.kt @@ -17,7 +17,7 @@ class MessagingService : FirebaseMessagingService() { try { // Check if message contains a data payload. if (remoteMessage.data.isNotEmpty()) { - SDK.debug("Message data payload: ${remoteMessage.data}") + SDK.debug("Message data payload keys: ${remoteMessage.data.keys}") // Route through the facade so a lazily-registered shop the push targets is materialized // on demand — the cold process FCM starts to deliver a data-only message only has the // eagerly-initialized shops live, so a lazy shop would otherwise be dropped at routing. @@ -26,7 +26,7 @@ class MessagingService : FirebaseMessagingService() { // Check if message contains a notification payload. if (remoteMessage.notification != null) { - SDK.debug("Message Notification Body: ${remoteMessage.notification?.body.orEmpty()}") + SDK.debug("Message has a notification payload") } } catch (throwable: Throwable) { SDK.error("Failed to handle push message", throwable) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt b/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt index 2e7aa771..8effe64d 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt @@ -371,7 +371,7 @@ open class SDK { .toJson(), listener = object : OnApiCallbackListener() { override fun onSuccess(response: JSONObject?) { - debug("Profile GAID sent successfully: $advertisingId") + debug("Profile GAID sent successfully") } override fun onError(code: Int, msg: String?) { diff --git a/personalization-sdk/src/main/kotlin/com/personalization/errors/response.error.kt.kt b/personalization-sdk/src/main/kotlin/com/personalization/errors/response.error.kt.kt index baffc528..53f1b94d 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/errors/response.error.kt.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/errors/response.error.kt.kt @@ -21,7 +21,6 @@ class JsonResponseErrorHandler( logError("Response is null or incorrect") false } else { - Log.i(tag, "Response is: $response") true } } diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/search/impl/SearchManagerImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/search/impl/SearchManagerImpl.kt index 77881062..dc95ad83 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/features/search/impl/SearchManagerImpl.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/search/impl/SearchManagerImpl.kt @@ -53,10 +53,9 @@ internal class SearchManagerImpl @Inject constructor( val searchParams = SearchParams() locations?.let { searchParams.put(SearchParams.Parameter.LOCATIONS, locations) - excludedMerchants?.let { - val excludeMerchantsString = excludedMerchants.joinToString(",") - searchParams.put(SearchParams.Parameter.EXCLUDED_MERCHANTS, excludeMerchantsString) - } + } + excludedMerchants?.let { + searchParams.put(SearchParams.Parameter.EXCLUDED_MERCHANTS, excludedMerchants.joinToString(",")) } excludedBrands?.let { searchParams.put(SearchParams.Parameter.EXCLUDED_BRANDS, excludedBrands.joinToString(",")) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImpl.kt index 37dd0d6a..ed3bb0a1 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImpl.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImpl.kt @@ -35,6 +35,9 @@ class NetworkRepositoryImpl @Inject constructor( private lateinit var baseUrl: String + /** How long a request may wait for the next bytes of an answer; tests shorten it. */ + internal var readTimeoutMs: Int = READ_TIMEOUT_MS + private val queue: MutableList = Collections.synchronizedList(ArrayList()) override fun initialize( @@ -183,6 +186,11 @@ class NetworkRepositoryImpl @Inject constructor( params: JSONObject, notificationSource: NotificationSource? ): JSONObject { + // A request with its own `from` or `code` (a story event, a push event) keeps them: the + // clicked push would replace that code and pair its `from` with someone else's code. + val pushSource = notificationSource?.takeUnless { + params.has(UserBasicParams.SOURCE_FROM) || params.has(UserBasicParams.SOURCE_CODE) + } addMultipleParams( params = params, paramsToAdd = mapOf( @@ -200,8 +208,8 @@ class NetworkRepositoryImpl @Inject constructor( key = UserBasicParams.STREAM, repoValue = userSettingsRepository.getStream(), ), - UserBasicParams.SOURCE_FROM to notificationSource?.type, - UserBasicParams.SOURCE_CODE to notificationSource?.id + UserBasicParams.SOURCE_FROM to pushSource?.type, + UserBasicParams.SOURCE_CODE to pushSource?.id ) ) return params @@ -239,88 +247,115 @@ class NetworkRepositoryImpl @Inject constructor( var responseCode = -1 var responseBodyForLog: String? = null var errorForLog: String? = null - try { + var connection: HttpURLConnection? = null + // The outcome is decided first and delivered once the connection is done with, so a + // callback that throws cannot change it. + val outcome: Outcome = try { val buildUri = build(networkMethod, params) val url = getUrl(networkMethod, buildUri) logUrl = url.toString() - val connection = getConnection(networkMethod, url, params) + connection = getConnection(networkMethod, url, params) connection.connect() responseCode = connection.responseCode - if (networkMethod is NetworkMethod.POST) { - SDK.debug("$responseCode: ${networkMethod.type} $url with body: $params") - } else { - SDK.debug("$responseCode: ${networkMethod.type} $buildUri") - } + // Method and path only: the query string and the body carry the user's data. + SDK.debug("$responseCode: ${networkMethod.type} ${networkMethod.method}") - if (responseCode >= 400) { - val error = readStream(connection.errorStream) - responseBodyForLog = error - SDK.error(error) - listener?.onError(responseCode, error) + if (responseCode in HTTP_SUCCESS) { + // A body the read timeout cuts short throws here and ends in onError. + val responseText = readStream(connection.inputStream) + responseBodyForLog = responseText + successOutcome(responseText) } else { - val responseText = try { - readStream(connection.inputStream) - } catch (e: Exception) { + // Below 400 there is no error stream: a redirect the connection did not follow. + // The status is the answer, so a body that fails to arrive does not replace it. + val error = try { + connection.errorStream?.let(::readStream).orEmpty() + } catch (e: IOException) { "" } - responseBodyForLog = responseText - - if (listener != null) { - when (responseCode) { - HttpURLConnection.HTTP_OK -> { - try { - if (responseText.isNotEmpty()) { - when (val json = JSONTokener(responseText).nextValue()) { - is JSONObject -> listener.onSuccess(json) - is JSONArray -> listener.onSuccess(json) - // Empty or invalid JSON, treat as success with empty object - else -> listener.onSuccess(JSONObject()) - } - } else { - // Empty response, treat as success - listener.onSuccess(JSONObject()) - } - } catch (e: Exception) { - // Failed to parse JSON, but response code is 200, treat as success - listener.onSuccess(JSONObject()) - } - } - HttpURLConnection.HTTP_NO_CONTENT -> { - // 204 No Content - successful response with no body - listener.onSuccess(JSONObject()) - } - } - } + responseBodyForLog = error + // Without the body: an error answer often repeats the request's data. + SDK.error("$responseCode: ${networkMethod.type} ${networkMethod.method}") + Outcome.Failure(responseCode, error) } - - connection.disconnect() } catch (e: ConnectException) { - SDK.error(e.message) + SDK.error("${networkMethod.type} ${networkMethod.method}: ${e.message}") errorForLog = e.message responseCode = 504 - listener?.onError(504, e.message) + Outcome.Failure(504, e.message) } catch (e: Exception) { - SDK.error(e.message, e) + SDK.error("${networkMethod.type} ${networkMethod.method}: ${e.message}", e) errorForLog = e.message - listener?.onError(-1, e.message) + Outcome.Failure(-1, e.message) } finally { - SDK.networkLogger?.onHttpCall( - method = networkMethod.type, - url = logUrl, - requestBody = requestBodyForLog, - responseCode = responseCode, - responseBody = responseBodyForLog, - durationMs = System.currentTimeMillis() - startTime, - error = errorForLog - ) + connection?.disconnect() + try { + SDK.networkLogger?.onHttpCall( + method = networkMethod.type, + url = logUrl, + requestBody = requestBodyForLog, + responseCode = responseCode, + responseBody = responseBodyForLog, + durationMs = System.currentTimeMillis() - startTime, + error = errorForLog + ) + } catch (e: Exception) { + SDK.error("NetworkLogger failed: ${e.message}", e) + } } + + listener?.let { deliver(it, outcome) } } thread.start() } + private sealed interface Outcome { + /** [body] is a [JSONObject] or a [JSONArray]. */ + class Success(val body: Any) : Outcome + class Failure(val code: Int, val message: String?) : Outcome + } + + /** Any 2xx is a success; an empty answer or one that is not JSON succeeds with an empty object. */ + private fun successOutcome(responseText: String): Outcome { + val json = try { + if (responseText.isEmpty()) null else JSONTokener(responseText).nextValue() + } catch (e: JSONException) { + null + } + return Outcome.Success(if (json is JSONObject || json is JSONArray) json else JSONObject()) + } + + /** + * A callback that throws is logged and must not take down the SDK's network thread. A failed + * onSuccess ends in one onError(-1): the SDK's own listeners parse the answer there and hand + * the model to the app, so without it a parse error would leave the app waiting for an answer. + */ + private fun deliver(listener: OnApiCallbackListener, outcome: Outcome) { + when (outcome) { + is Outcome.Success -> try { + when (val body = outcome.body) { + is JSONArray -> listener.onSuccess(body) + else -> listener.onSuccess(body as JSONObject) + } + } catch (e: Exception) { + SDK.error("onSuccess of a request failed: ${e.message}", e) + fail(listener, -1, e.message) + } + is Outcome.Failure -> fail(listener, outcome.code, outcome.message) + } + } + + private fun fail(listener: OnApiCallbackListener, code: Int, message: String?) { + try { + listener.onError(code, message) + } catch (e: Exception) { + SDK.error("onError of a request failed: ${e.message}", e) + } + } + private fun build( networkMethod: NetworkMethod, params: JSONObject @@ -357,7 +392,8 @@ class NetworkRepositoryImpl @Inject constructor( val connection = url.openConnection() as HttpURLConnection connection.setRequestProperty("User-Agent", SDK.userAgent()) connection.requestMethod = networkMethod.type - connection.connectTimeout = 5000 + connection.connectTimeout = CONNECT_TIMEOUT_MS + connection.readTimeout = readTimeoutMs if (networkMethod is NetworkMethod.POST) { connection.setRequestProperty("Content-Type", "application/json") @@ -373,26 +409,15 @@ class NetworkRepositoryImpl @Inject constructor( return connection } - private fun readStream(inputStream: InputStream): String { - var reader: BufferedReader? = null - val response = StringBuffer() - try { - reader = BufferedReader(InputStreamReader(inputStream)) - var line: String? - while ((reader.readLine().also { line = it }) != null) { - response.append(line) - } - } catch (e: IOException) { - e.printStackTrace() - } finally { - if (reader != null) { - try { - reader.close() - } catch (e: IOException) { - e.printStackTrace() - } - } + /** The whole answer, its lines joined; a read that fails midway throws instead of returning a part. */ + private fun readStream(inputStream: InputStream): String = + BufferedReader(InputStreamReader(inputStream)).use { reader -> + buildString { reader.forEachLine { append(it) } } } - return response.toString() + + private companion object { + const val CONNECT_TIMEOUT_MS = 5_000 + const val READ_TIMEOUT_MS = 10_000 + val HTTP_SUCCESS = 200..299 } } diff --git a/personalization-sdk/src/main/kotlin/com/personalization/ui/widgets/StoriesApiV3.kt b/personalization-sdk/src/main/kotlin/com/personalization/ui/widgets/StoriesApiV3.kt index 3a0c7127..62f05f71 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/ui/widgets/StoriesApiV3.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/ui/widgets/StoriesApiV3.kt @@ -110,7 +110,7 @@ internal object StoriesApiV3 { whenDid(sdk) { val body = eventBody(shopId(sdk), sdk.getDid().orEmpty(), event, storyId, slideId) val response = post(eventsUrl(domain, code), body) - if (response.code !in 200..299) SDK.error("stories v3: $event failed: ${response.code} ${response.body}") + if (response.code !in 200..299) SDK.error("stories v3: $event failed: ${response.code}") } } @@ -180,11 +180,14 @@ internal object StoriesApiV3 { SDK.networkLogger?.onHttpCall(method, url, body, -1, null, System.currentTimeMillis() - started, throwable.message) throw throwable } - SDK.debug("${response.code}: $method $url" + (body?.let { " with body: $it" } ?: "")) + // Method and path only: the query and the body carry did, the session and the user's answers. + SDK.debug("${response.code}: $method ${pathOf(url)}") SDK.networkLogger?.onHttpCall(method, url, body, response.code, response.body, System.currentTimeMillis() - started, null) return response } + private fun pathOf(url: String): String = runCatching { URL(url).path }.getOrDefault("") + private fun sendHttp(method: String, url: String, body: String?): Response { val connection = URL(url).openConnection() as HttpURLConnection try { diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/search/impl/SearchInstantParamsTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/search/impl/SearchInstantParamsTest.kt new file mode 100644 index 00000000..ad9aca19 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/search/impl/SearchInstantParamsTest.kt @@ -0,0 +1,56 @@ +package com.personalization.features.search.impl + +import com.personalization.sdk.domain.usecases.network.SendNetworkMethodUseCase +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.runs +import io.mockk.slot +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class SearchInstantParamsTest { + + private val params = slot() + private val network = mockk { + every { get(any(), capture(params), any()) } just runs + } + private val manager = SearchManagerImpl(network) + + @Test + fun `excluded merchants are sent without locations`() { + manager.searchInstant( + query = "shoes", + locations = null, + excludedMerchants = listOf("m1", "m2"), + excludedBrands = null, + onSearchInstant = {}, + onError = { _, _ -> } + ) + + assertEquals("m1,m2", params.captured.getString("excluded_merchants")) + assertFalse(params.captured.has("locations")) + } + + @Test + fun `excluded merchants are sent with locations`() { + manager.searchInstant( + query = "shoes", + locations = "msk", + excludedMerchants = listOf("m1"), + excludedBrands = null, + onSearchInstant = {}, + onError = { _, _ -> } + ) + + assertEquals("m1", params.captured.getString("excluded_merchants")) + assertEquals("msk", params.captured.getString("locations")) + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImplTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImplTest.kt new file mode 100644 index 00000000..93fcaacf --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImplTest.kt @@ -0,0 +1,304 @@ +package com.personalization.sdk.data.repositories.network + +import com.personalization.api.OnApiCallbackListener +import com.personalization.sdk.domain.models.NotificationSource +import com.personalization.sdk.domain.repositories.NotificationRepository +import com.personalization.sdk.domain.repositories.UserSettingsRepository +import io.mockk.every +import io.mockk.mockk +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowLog +import java.io.BufferedReader +import java.io.InputStreamReader +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +/** + * Drives [NetworkRepositoryImpl] against a local HTTP server: which answers reach which + * callback, how often, and what a host's failing callback does to the network thread. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class NetworkRepositoryImplTest { + + private data class Recorded(val method: String, val uri: String, val body: String) + + /** + * An answer of the local server; `null` from [handler] keeps the connection open, silent. + * [stall] sends the status, the headers and [body], then falls silent before the promised rest. + */ + private data class Reply(val code: Int, val body: String?, val stall: Boolean = false) + + private lateinit var server: ServerSocket + private val requests = CopyOnWriteArrayList() + + @Volatile + private var handler: (Recorded) -> Reply? = { Reply(200, "{}") } + + private val release = CountDownLatch(1) + private val notificationRepository = mockk() + private val uncaught = CopyOnWriteArrayList() + private var previousUncaughtHandler: Thread.UncaughtExceptionHandler? = null + private lateinit var repository: NetworkRepositoryImpl + + @Before + fun setUp() { + server = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1")) + Thread { + while (!server.isClosed) { + val socket = try { server.accept() } catch (e: Exception) { break } + Thread { serve(socket) }.start() + } + }.start() + + val settings = mockk(relaxed = true) { + every { getShopId() } returns "shop" + every { getDid() } returns "did" + every { getSid() } returns "sid" + every { getSegmentForABTesting() } returns "A" + every { getStream() } returns "android" + } + every { notificationRepository.getNotificationSource(any()) } returns null + + repository = NetworkRepositoryImpl(settings, notificationRepository) + repository.initialize("http://127.0.0.1:${server.localPort}/") + + previousUncaughtHandler = Thread.getDefaultUncaughtExceptionHandler() + Thread.setDefaultUncaughtExceptionHandler { _, e -> uncaught += e } + ShadowLog.clear() + } + + @After + fun tearDown() { + release.countDown() + server.close() + Thread.setDefaultUncaughtExceptionHandler(previousUncaughtHandler) + } + + @Test + fun `a 201 answer reaches onSuccess`() { + handler = { Reply(201, """{"id":1}""") } + + val listener = Recorder() + repository.post("track/custom", JSONObject(), listener) + + assertEquals(listOf("""success:{"id":1}"""), listener.awaitCalls()) + } + + @Test + fun `an empty 202 answer reaches onSuccess with an empty object`() { + handler = { Reply(202, null) } + + val listener = Recorder() + repository.post("track/custom", JSONObject(), listener) + + assertEquals(listOf("success:{}"), listener.awaitCalls()) + } + + @Test + fun `an answer outside 2xx below 400 reaches onError`() { + handler = { Reply(304, null) } + + val listener = Recorder() + repository.get("products/get", JSONObject(), listener) + + assertEquals(listOf("error:304"), listener.awaitCalls()) + } + + @Test + fun `an error answer without a body keeps its status`() { + handler = { Reply(404, null) } + + val listener = Recorder() + repository.get("products/get", JSONObject(), listener) + + assertEquals(listOf("error:404"), listener.awaitCalls()) + } + + @Test + fun `a failing onSuccess ends in one onError and does not crash the network thread`() { + handler = { Reply(200, "{}") } + + // The SDK's own listeners parse the answer in onSuccess: a parse error must reach the app. + val listener = Recorder(throwOnSuccess = true) + repository.post("track/custom", JSONObject(), listener) + + assertEquals(listOf("success:{}", "error:-1"), listener.awaitCalls()) + assertTrue("uncaught: $uncaught", uncaught.isEmpty()) + } + + @Test + fun `a failing onSuccess and onError end the request without crashing the network thread`() { + handler = { Reply(200, "{}") } + + val listener = Recorder(throwOnSuccess = true, throwOnError = true) + repository.post("track/custom", JSONObject(), listener) + + assertEquals(listOf("success:{}", "error:-1"), listener.awaitCalls()) + assertTrue("uncaught: $uncaught", uncaught.isEmpty()) + } + + @Test + fun `a throwing onError is called once and does not crash the network thread`() { + handler = { Reply(500, "oops") } + + val listener = Recorder(throwOnError = true) + repository.post("track/custom", JSONObject(), listener) + + assertEquals(listOf("error:500"), listener.awaitCalls()) + assertTrue("uncaught: $uncaught", uncaught.isEmpty()) + } + + @Test + fun `a server that stops answering ends in onError after the read timeout`() { + handler = { release.await(10, TimeUnit.SECONDS); null } + repository.readTimeoutMs = 300 + + val listener = Recorder() + repository.get("products/get", JSONObject(), listener) + + assertEquals(listOf("error:-1"), listener.awaitCalls(timeoutMs = 5_000)) + val log = ShadowLog.getLogs().joinToString("\n") { it.msg.orEmpty() } + assertTrue("the failed request is named: $log", log.contains("GET products/get:")) + } + + @Test + fun `a success answer cut short by the read timeout ends in onError`() { + handler = { Reply(200, """{"did":"abc",""", stall = true) } + repository.readTimeoutMs = 300 + + val listener = Recorder() + repository.get("init", JSONObject(), listener) + + assertEquals(listOf("error:-1"), listener.awaitCalls(timeoutMs = 5_000)) + } + + @Test + fun `a push click does not replace the request's own code`() { + every { notificationRepository.getNotificationSource(any()) } returns + NotificationSource(type = "bulk", id = "push-1", time = System.currentTimeMillis()) + + val listener = Recorder() + repository.post("track/stories", JSONObject().put("code", "story-1"), listener) + listener.awaitCalls() + + val body = JSONObject(requests.single().body) + assertEquals("story-1", body.getString("code")) + assertFalse("from of the push must not pair with the story's code", body.has("from")) + } + + @Test + fun `a push click is attributed to a request without its own code`() { + every { notificationRepository.getNotificationSource(any()) } returns + NotificationSource(type = "bulk", id = "push-1", time = System.currentTimeMillis()) + + val listener = Recorder() + repository.post("push/attributed", JSONObject(), listener) + listener.awaitCalls() + + val body = JSONObject(requests.single().body) + assertEquals("bulk", body.getString("from")) + assertEquals("push-1", body.getString("code")) + } + + @Test + fun `request and answer data stay out of the log`() { + handler = { Reply(200, """{"email":"answer@example.com"}""") } + + val get = Recorder() + repository.get("profile", JSONObject().put("email", "get@example.com"), get) + get.awaitCalls() + val post = Recorder() + repository.post("profile/set", JSONObject().put("phone", "+79990001122"), post) + post.awaitCalls() + handler = { Reply(422, """{"error":"invalid phone +79990004455"}""") } + val rejected = Recorder() + repository.post("profile/set", JSONObject().put("phone", "+79990004455"), rejected) + rejected.awaitCalls() + + val log = ShadowLog.getLogs().joinToString("\n") { "${it.tag}: ${it.msg}" } + assertFalse(log, log.contains("get@example.com")) + assertFalse(log, log.contains("79990001122")) + assertFalse(log, log.contains("answer@example.com")) + assertFalse(log, log.contains("79990004455")) + assertTrue(log, log.contains("422: POST profile/set")) + } + + /** Reads one HTTP/1.1 request from [socket], records it and writes the [handler]'s reply. */ + private fun serve(socket: Socket) = socket.use { + val reader = BufferedReader(InputStreamReader(it.getInputStream(), Charsets.UTF_8)) + val (method, uri) = reader.readLine()?.split(" ")?.let { line -> line[0] to line[1] } ?: return + var length = 0 + while (true) { + val header = reader.readLine() ?: break + if (header.isEmpty()) break + if (header.startsWith("Content-Length:", ignoreCase = true)) { + length = header.substringAfter(':').trim().toInt() + } + } + val body = CharArray(length).also { chars -> + var read = 0 + while (read < length) { + val n = reader.read(chars, read, length - read) + if (n < 0) break + read += n + } + } + val recorded = Recorded(method, uri, String(body)) + requests += recorded + val reply = handler(recorded) ?: return + val bytes = reply.body?.toByteArray(Charsets.UTF_8) ?: ByteArray(0) + val promised = if (reply.stall) bytes.size + 100 else bytes.size + val out = it.getOutputStream() + out.write( + ("HTTP/1.1 ${reply.code} Status\r\n" + + "Content-Length: $promised\r\n" + + "Connection: close\r\n\r\n").toByteArray(Charsets.US_ASCII) + ) + out.write(bytes) + out.flush() + if (reply.stall) release.await(10, TimeUnit.SECONDS) + } + + /** Records every callback; waits for the first one, then a little longer for repeats. */ + private class Recorder( + private val throwOnSuccess: Boolean = false, + private val throwOnError: Boolean = false, + ) : OnApiCallbackListener() { + + private val calls = CopyOnWriteArrayList() + private val first = CountDownLatch(1) + + override fun onSuccess(response: JSONObject?) = record("success:$response", throwOnSuccess) + + override fun onSuccess(response: JSONArray) = record("success:$response", throwOnSuccess) + + override fun onError(code: Int, msg: String?) = record("error:$code", throwOnError) + + private fun record(call: String, fail: Boolean) { + calls += call + first.countDown() + if (fail) throw IllegalStateException("host callback failed") + } + + fun awaitCalls(timeoutMs: Long = 3_000): List { + first.await(timeoutMs, TimeUnit.MILLISECONDS) + Thread.sleep(300) + return calls.toList() + } + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/ui/widgets/StoriesPollsApiTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/ui/widgets/StoriesPollsApiTest.kt index 2deb5d52..e9198005 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/ui/widgets/StoriesPollsApiTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/ui/widgets/StoriesPollsApiTest.kt @@ -98,6 +98,14 @@ class StoriesPollsApiTest { assertTrue(logs.toString(), logs.any { it.contains("/polls/mini_polls/gift_recipient/answers failed: 429 Too many requests") }) } + @Test + fun `a request is logged by method and path, without the identity and the answer`() { + answer(body = mapOf("text" to "my own answer")) + val logs = ShadowLog.getLogs().map { it.msg.orEmpty() } + assertTrue(logs.toString(), logs.any { it == "200: POST /api/v3/polls/mini_polls/gift_recipient/answers" }) + assertTrue(logs.toString(), logs.none { "did1" in it || "sid1" in it || "my own answer" in it }) + } + @Test fun `success takes the answer and results of the payload`() { reply = StoriesApiV3.Response(