Skip to content

Commit

Permalink
test: 네트워크 테스트 코드 추가
Browse files Browse the repository at this point in the history
- 딱히 안지워도 되는 것들이라 이상태로 반영
  • Loading branch information
sieunju committed Dec 3, 2023
1 parent 452ce93 commit 622b567
Show file tree
Hide file tree
Showing 14 changed files with 12,004 additions and 56 deletions.
11,939 changes: 11,939 additions & 0 deletions assets/network_test_log.txt

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions core/src/main/java/com/hmju/core/network/NetworkConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ package com.hmju.core.network
* Created by juhongmin on 2022/01/12
*/
object NetworkConfig {
const val CONNECT_TIME_OUT = 5000L
const val READ_TIME_OUT = 5000L
const val WRITE_TIME_OUT = 5000L
const val CONNECT_TIME_OUT = 60_000L
const val READ_TIME_OUT = 60_000L
const val WRITE_TIME_OUT = 60_000L
const val HEADER_KEY_ACCEPT = "accept"
const val HEADER_VAL_ACCEPT = "application/json"
const val HEADER_KEY_CONTENT = "Content-Type"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ class PauseAbleThreadPoolExecutor constructor(
}
}

// private val TIME_DELAY = 5000
private val TIME_DELAY = 0

private var isPaused = false
Expand All @@ -60,7 +61,7 @@ class PauseAbleThreadPoolExecutor constructor(
super.beforeExecute(t, r)
pauseLock.lock()
if (isCallRefreshToken()) {
Timber.d("Dispatcher 토큰을 재발급합니다. ${t.name}")
Timber.tag("Network_Test").w("Dispatcher 토큰을 재발급합니다. ${t.name}")
handleTokenRefresh()
}

Expand Down Expand Up @@ -130,7 +131,6 @@ class PauseAbleThreadPoolExecutor constructor(
*/
@Synchronized
private fun handleTokenRefresh() {
// 해당 로직은 4초 미만으로 구성되어야함
isPaused = true
// val refreshToken = reqRefreshToken()
val refreshToken = reqRetryRefreshToken().blockingGet()
Expand Down
8 changes: 4 additions & 4 deletions core/src/main/java/com/hmju/core/network/di/RemoteModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ internal object RemoteModule {
.readTimeout(NetworkConfig.READ_TIME_OUT, TimeUnit.MILLISECONDS)
.writeTimeout(NetworkConfig.WRITE_TIME_OUT, TimeUnit.MILLISECONDS)
.addInterceptor(headerInterceptor)
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(trackingInterceptor)
// .addInterceptor(httpLoggingInterceptor)
// .addInterceptor(trackingInterceptor)
.build()

@Singleton
Expand Down Expand Up @@ -119,8 +119,8 @@ internal object RemoteModule {
.dispatcher(dispatcher)
.authenticator(tokenAuthenticator)
.addInterceptor(headerInterceptor)
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(trackingInterceptor)
// .addInterceptor(httpLoggingInterceptor)
// .addInterceptor(trackingInterceptor)
.build()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import com.hmju.core.login_manager.LoginManager
import com.hmju.core.network.NetworkConfig
import okhttp3.Interceptor
import okhttp3.Response
import timber.log.Timber
import java.util.concurrent.TimeUnit

/**
* Description : Header Interceptor
Expand All @@ -20,6 +22,19 @@ class HeaderInterceptor(
.header(NetworkConfig.HEADER_KEY_CONTENT, NetworkConfig.HEADER_VAL_CONTENT)
.header(NetworkConfig.HEADER_KEY_AUTHORIZATION, loginManager.getToken())
.build()
return chain.proceed(req)

val startNs = System.nanoTime()
val response: Response
try {
response = chain.proceed(req)
} catch (e: Exception) {
throw e
}
val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)
val str = StringBuilder()
str.appendLine("Code ${response.code} Request ${response.request.url.encodedPath} (${tookMs}ms)")
str.appendLine("Authorization: ${req.header("Authorization")}")
Timber.tag("Network_Test").d(str.toString())
return response
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package com.hmju.core.network.interceptor
import com.hmju.core.network.NetworkConfig
import okhttp3.Interceptor
import okhttp3.Response
import timber.log.Timber
import java.util.concurrent.TimeUnit

/**
* Description : 토큰 갱신용 Interceptor
Expand All @@ -11,10 +13,22 @@ import okhttp3.Response
*/
class RefreshTokenInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val origin = chain.request()
return chain.proceed(origin.newBuilder().apply {
header(NetworkConfig.HEADER_KEY_ACCEPT, NetworkConfig.HEADER_VAL_ACCEPT)
header(NetworkConfig.HEADER_KEY_CONTENT, NetworkConfig.HEADER_VAL_CONTENT)
}.build())
val req = chain.request().newBuilder()
.header(NetworkConfig.HEADER_KEY_ACCEPT, NetworkConfig.HEADER_VAL_ACCEPT)
.header(NetworkConfig.HEADER_KEY_CONTENT, NetworkConfig.HEADER_VAL_CONTENT)
.build()

val startNs = System.nanoTime()
val response: Response
try {
response = chain.proceed(req)
} catch (e: Exception) {
throw e
}
val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)
val str = StringBuilder()
str.append("Code ${response.code} Request ${response.request.url.encodedPath} (${tookMs}ms)")
Timber.tag("Network_Test").w(str.toString())
return response
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ class TokenAuthenticator(
Timber.d("TokenAuthenticator ${response.code}")
return if (response.code == 401) {
handleTokenRefresh()
response.request.newBuilder()
val req = response.request.newBuilder()
.header(NetworkConfig.HEADER_KEY_AUTHORIZATION, loginManager.getToken())
.build()
Timber.tag("Network_Test").e("Authenticator ${req.url.encodedPath}")
req
} else {
null
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@ import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.features.base_mvvm.usecase.GetGoodsUseCase
import com.hmju.core.login_manager.LoginManager
import com.hmju.core.model.params.GoodsParameter
import com.hmju.core.ui.base.FragmentViewModel
import com.hmju.core.ui.base.IntentKey
import com.hmju.core.ui.lifecycle.OnActivityResult
import com.hmju.core.ui.lifecycle.OnCreated
import com.hmju.core.ui.lifecycle.OnResumed
import com.hmju.core.model.params.GoodsParameter
import com.hmju.core.login_manager.LoginManager
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.rxjava3.kotlin.addTo
import javax.inject.Inject

/**
Expand All @@ -36,11 +35,6 @@ class LifecycleViewModel @Inject constructor(
_activityResult.value = "asdfasdf"
// activityStack.value = getActivityStackStr()
// fragmentStack.value = getFragmentStackStr()
goodsUseCase(queryMap)
.subscribe({
loginManager.setToken(it[0].imagePath)
}, {
}).addTo(compositeDisposable)
}

@OnResumed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import com.hmju.core.model.params.GoodsParameter
import com.hmju.core.login_manager.LoginManager
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.kotlin.addTo
import timber.log.Timber
import javax.inject.Inject
import kotlin.random.Random
Expand Down Expand Up @@ -46,10 +47,9 @@ class MvvmLifecycleTest2ViewModel @Inject constructor(
getGoodsUseCase(GoodsParameter())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
loginManager.setToken(it[Random.nextInt(10)].message)
}, {

})
}).addTo(compositeDisposable)
}

fun moveTest3Page() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import com.hmju.core.model.params.GoodsParameter
import com.hmju.core.login_manager.LoginManager
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.kotlin.addTo
import timber.log.Timber
import javax.inject.Inject

Expand Down Expand Up @@ -54,11 +55,10 @@ class MvvmLifecycleTest3ViewModel @Inject constructor(
getGoodsUseCase(queryMap)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
loginManager.setToken(it[0].imagePath)
Timber.d("SUCC $it")
}, {
Timber.e("Error $it")
})
}).addTo(compositeDisposable)
}

fun moveTest2Page() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,17 @@ import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.features.base_mvvm.usecase.GetGoodsUseCase
import com.hmju.core.login_manager.LoginManager
import com.hmju.core.model.params.GoodsParameter
import com.hmju.core.ui.base.ActivityViewModel
import com.hmju.core.ui.base.BaseActivity
import com.hmju.core.ui.base.IntentKey
import com.hmju.core.ui.lifecycle.*
import com.hmju.core.model.params.GoodsParameter
import com.hmju.core.login_manager.LoginManager
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.rxjava3.kotlin.addTo
import io.reactivex.rxjava3.schedulers.Schedulers
import timber.log.Timber
import javax.inject.Inject
import kotlin.random.Random

/**
* Description :
Expand Down Expand Up @@ -59,7 +58,6 @@ class MvvmLifecycleTestViewModel @Inject constructor(
}

fun onRandomToken() {
loginManager.setToken("Token ${System.currentTimeMillis()}")
savedStateHandle.set("HiKey", "dddfefefeffe")
savedStateHandle.set("Hello....", System.currentTimeMillis())
savedStateHandle.set(IntentKey.TOKEN, "ChangeResult")
Expand All @@ -70,7 +68,6 @@ class MvvmLifecycleTestViewModel @Inject constructor(
}

fun onClick3() {
loginManager.setToken("Token ${System.currentTimeMillis()}_${Random.nextBytes(10000)}")
// movePage(
// MovePageEvent(
// target = MvvmLifecycleTest2Activity::class.java,
Expand Down
22 changes: 3 additions & 19 deletions features/main/src/main/java/com/features/main/MainViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,14 @@ package com.features.main

import com.feature.async_migrate_bridge.AsyncMigrateBridge
import com.features.base_mvvm_bridge.BaseMvvmBridge
import com.hmju.core.ui.base.ActivityViewModel
import com.hmju.core.ui.lifecycle.OnCreated
import com.hmju.core.ui.lifecycle.OnIntent
import com.features.network_bridge.NetworkBridge
import com.features.recyclerview_bridge.RecyclerViewBridge
import com.hmju.core.login_manager.LoginManager
import com.hmju.core.ui.base.ActivityViewModel
import com.hmju.core.ui.lifecycle.OnIntent
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.kotlin.addTo
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.random.Random

/**
* Description :
Expand All @@ -39,17 +34,6 @@ class MainViewModel @Inject constructor(
Timber.d("[s] onCreate Intent Data ===============================================")
}

@OnCreated
fun randomLogin() {
Flowable.interval(3000, TimeUnit.MILLISECONDS)
.subscribe({
loginManager.setToken(if (Random.nextInt(100) > 30) "Token" else "")
// Timber.d("isLoginCheck ${loginManager.isLogin()}")
}, {

}).addTo(compositeDisposable)
}

fun moveToNetworkPage() {
networkRequirements.moveToNetworkPage()
}
Expand All @@ -62,7 +46,7 @@ class MainViewModel @Inject constructor(
mvvmRequirements.moveToBaseMvvm()
}

fun moveToAsyncMigratePage(){
fun moveToAsyncMigratePage() {
asyncMigrateBridge.moveToAsyncMigrate()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class RefreshTokenFragment :
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
Timber.d("Response $it")
loginManager.setToken(it.token)
// loginManager.setToken(it.token)
}, {
Timber.e("Error $it")
}).addTo(compositeDisposable)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,10 @@ class NetworkV2FragmentViewModel @Inject constructor(
val takeCount = takeMs.toFloat() / 333.0
Flowable.interval(0, 333L, TimeUnit.MILLISECONDS)
.takeUntil { System.currentTimeMillis() >= endTimeMs }
.flatMap { startJwtRequest(it).toFlowable() }
.doOnNext {
startJwtRequest(it).subscribe().addTo(compositeDisposable)
}
// .flatMap { startJwtRequest(it).toFlowable() }
.doOnNext {
val percentage = (it.toFloat() / takeCount) * 100.0
_progressText.postValue("${percentage.toInt()}%")
Expand Down Expand Up @@ -191,7 +194,7 @@ class NetworkV2FragmentViewModel @Inject constructor(
}

private fun reqJwtTest1(): Single<Int> {
return apiService.fetchJwtTest(3000)
return apiService.fetchJwtTest(300)
.map { 1 }
.onErrorReturn { 11 }
.subscribeOn(Schedulers.io())
Expand All @@ -205,7 +208,7 @@ class NetworkV2FragmentViewModel @Inject constructor(
}

private fun reqJwtTest3(): Single<Int> {
return apiService.fetchJwtTest2(2000)
return apiService.fetchJwtTest2(200)
.map { 3 }
.onErrorReturn { 13 }
.subscribeOn(Schedulers.io())
Expand Down

0 comments on commit 622b567

Please sign in to comment.