Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(Part 1) stream-chat-android-client unit tests - api package #5660

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ import io.getstream.chat.android.client.utils.HeadersUtil
import okhttp3.Interceptor
import okhttp3.Response

/**
* Interceptor that adds the default headers to the request.
*
* @param isAnonymous a function that returns true if the logged in user is anonymous.
* @param headersUtil a utility class for building headers.
*/
internal class HeadersInterceptor(
private val isAnonymous: () -> Boolean,
private val headersUtil: HeadersUtil,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright (c) 2014-2025 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.getstream.chat.android.client.api

import io.getstream.chat.android.test.TestCoroutineRule
import io.getstream.result.Error
import io.getstream.result.Result
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import org.amshove.kluent.`should be instance of`
import org.amshove.kluent.shouldBeEqualTo
import org.junit.Rule
import org.junit.Test

internal class ErrorCallTest {

@get:Rule
val coroutinesTestRule = TestCoroutineRule()

@Test
fun testErrorCallExecute() {
// given
val error = Error.GenericError("Generic error")
val errorCall = ErrorCall<Unit>(TestScope(), error)
// when
val result = errorCall.execute()
// then
result `should be instance of` Result.Failure::class
result as Result.Failure
result.value shouldBeEqualTo error
}

@Test
fun testErrorCallEnqueue() = runTest {
// given
val error = Error.GenericError("Generic error")
val errorCall = ErrorCall<Unit>(backgroundScope, error)
// when
errorCall.enqueue { result ->
// then
result `should be instance of` Result.Failure::class
result as Result.Failure
result.value shouldBeEqualTo error
}
}

@Test
fun testErrorCallAwait() = runTest {
// given
val error = Error.GenericError("Generic error")
val errorCall = ErrorCall<Unit>(TestScope(), error)
// when
val result = errorCall.await()
// then
result `should be instance of` Result.Failure::class
result as Result.Failure
result.value shouldBeEqualTo error
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ import okhttp3.Request
import okhttp3.Response
import java.util.concurrent.TimeUnit

internal class FakeChain(vararg val response: FakeResponse) : Interceptor.Chain {
internal class FakeChain(
vararg val response: FakeResponse,
val request: Request = Request.Builder()
.url("https://hello.url")
.build(),
) : Interceptor.Chain {

var chainIndex = 0

Expand Down Expand Up @@ -61,9 +66,7 @@ internal class FakeChain(vararg val response: FakeResponse) : Interceptor.Chain
}

override fun request(): Request {
return Request.Builder()
.url("https://hello.url")
.build()
return request
}

override fun withConnectTimeout(timeout: Int, unit: TimeUnit): Interceptor.Chain {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright (c) 2014-2025 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.getstream.chat.android.client.api.interceptor

import io.getstream.chat.android.client.api.FakeChain
import io.getstream.chat.android.client.api.FakeResponse
import org.amshove.kluent.shouldBeEqualTo
import org.junit.Test

internal class ApiKeyInterceptorTest {

@Test
fun testApiKeyIsAddedAsHeader() {
// given
val apiKey = "apiKeyValue"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
val apiKey = "apiKeyValue"
val apiKey = randomString()

val interceptor = ApiKeyInterceptor(apiKey)
// when
val response = interceptor.intercept(FakeChain(FakeResponse(200)))
// then
val apiKeyQueryParam = response.request.url.queryParameter("api_key")
apiKeyQueryParam shouldBeEqualTo apiKey
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2014-2025 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.getstream.chat.android.client.api.interceptor

import io.getstream.chat.android.client.api.FakeChain
import io.getstream.chat.android.client.api.FakeResponse
import io.getstream.chat.android.client.plugins.requests.ApiRequestsAnalyser
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doNothing
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever

internal class ApiRequestAnalyserInterceptorTest {

@Test
fun testApiRequestAnalyserInterceptorRegistersTheRequestInTheAnalyser() {
// given
val analyser = mock<ApiRequestsAnalyser>()
doNothing().whenever(analyser).registerRequest(any(), any())
val interceptor = ApiRequestAnalyserInterceptor(analyser)
// when
val chain = FakeChain(FakeResponse(200))
interceptor.intercept(chain)
// then
verify(analyser, times(1)).registerRequest(
requestName = chain.request().url.toString(),
data = mapOf("body" to "no_body"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we only testing when the response is empty?
Should we test other cases?
As commented on another comment, we can use @ParameterizedTest on that case.

)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright (c) 2014-2025 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.getstream.chat.android.client.api.interceptor

import io.getstream.chat.android.client.api.FakeChain
import io.getstream.chat.android.client.api.FakeResponse
import io.getstream.chat.android.client.utils.HeadersUtil
import org.amshove.kluent.`should be equal to`
import org.junit.Test
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever

internal class HeadersInterceptorTest {

@Test
fun testAnonymousUserHeaders() {
// given
val isAnonymous = { true }
val headersUtil = mock<HeadersUtil>()
whenever(headersUtil.buildSdkTrackingHeaders()).doReturn("sdkTrackingHeaders")
whenever(headersUtil.buildUserAgent()).doReturn("userAgent")
val interceptor = HeadersInterceptor(isAnonymous, headersUtil)
// when
val response = interceptor.intercept(FakeChain(FakeResponse(200)))
// then
response.request.header("User-Agent") `should be equal to` "userAgent"
response.request.header("Content-Type") `should be equal to` "application/json"
response.request.header("stream-auth-type") `should be equal to` "anonymous"
response.request.header("X-Stream-Client") `should be equal to` "sdkTrackingHeaders"
response.request.header("Cache-Control") `should be equal to` "no-cache"
}

@Test
fun testAuthenticatedUserHeaders() {
// given
val isAnonymous = { false }
val headersUtil = mock<HeadersUtil>()
whenever(headersUtil.buildSdkTrackingHeaders()).doReturn("sdkTrackingHeaders")
whenever(headersUtil.buildUserAgent()).doReturn("userAgent")
val interceptor = HeadersInterceptor(isAnonymous, headersUtil)
// when
val response = interceptor.intercept(FakeChain(FakeResponse(200)))
// then
response.request.header("User-Agent") `should be equal to` "userAgent"
response.request.header("Content-Type") `should be equal to` "application/json"
response.request.header("stream-auth-type") `should be equal to` "jwt"
response.request.header("X-Stream-Client") `should be equal to` "sdkTrackingHeaders"
response.request.header("Cache-Control") `should be equal to` "no-cache"
}
Comment on lines +30 to +64
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of writting the same test multiple times only because a single parameter is different, we can use @ParameterizedTest providing an input source with the different input/expected values.

On the other hand, consider to use randomString() when the value "is not important" and our code accepts whatever value, it could raise up hidden bubs in our code (hardcoded values, default behavior given a default value, ...)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't want to write a @ParameterizedTest for just 2 tests because I thought it would reduce the readability a bit. But I can change it anyway, since I will change some of the values with randomString()

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2014-2025 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.getstream.chat.android.client.api.interceptor

import io.getstream.chat.android.client.api.FakeChain
import io.getstream.chat.android.client.api.FakeResponse
import io.getstream.chat.android.client.api.models.ProgressRequestBody
import io.getstream.chat.android.client.utils.ProgressCallback
import io.getstream.result.Error
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.amshove.kluent.`should be instance of`
import org.junit.Test

internal class ProgressInterceptorTest {

@Test
fun testProgressInterceptor() {
// given
val interceptor = ProgressInterceptor()
val progressCallback = object : ProgressCallback {
override fun onSuccess(url: String?) { /* No-Op */ }
override fun onError(error: Error) { /* No-Op */ }
override fun onProgress(bytesUploaded: Long, totalBytes: Long) { /* No-Op */ }
}
val request = Request.Builder()
.url("https://hello.url")
.post("body".toRequestBody())
.tag(ProgressCallback::class.java, progressCallback)
.build()
Comment on lines +40 to +44
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about creating a Mother method to easily create Request with custom value?

val chain = FakeChain(FakeResponse(200), request = request)
// when
val response = interceptor.intercept(chain)
// then
response.request.body `should be instance of` ProgressRequestBody::class
}
}
Loading
Loading