Can't mock com.github.kittinunf.fuel.Fuel with mockk - kotlin

I need your help in the following problem: I can not get mocked the Fuel.get call.
What I've tried:
This is the service class, where Fuel will be called.
class JiraService {
private val logger: Logger = LoggerFactory.getLogger(JiraService::class.java)
fun checkIfUsersExistInJira(usernames: List<String>, jiraConfig: Configuration): Boolean {
var checkResultOk = true;
val encodedCredentials =
usernames.forEach {
Fuel.get("${jiraConfig[url]}/rest/api/2/groupuserpicker?query=${it}&maxResults=1")
.appendHeader("Authorization", "Basic ...")
.appendHeader("Content-Type", "application/json")
.responseObject(UserInfoDeserializer)
.third
.fold(
failure = { throwable ->
logger.error(
"Can't check users in jira for user $it",
throwable
)
},
success = { userExists ->
checkResultOk = checkResultOk && userExists
}
)
}
return checkResultOk
}
}
The test:
#ExtendWith(MockKExtension::class)
class JiraServiceTest {
private val jiraConfig = createJiraConf()
private val fuelRequest = mockk<Request>()
private val fuelResponse = mockk<Response>()
private val fuelMock = mockk<Fuel>()
#BeforeEach
fun setUp() {
mockkStatic(FuelManager::class)
every {
fuelMock.get(eq("${jiraConfig[url]}/rest/api/2/groupuserpicker?query=user_1#test.com&maxResults=1"))
.appendHeader(eq("Authorization"), any())
.appendHeader(eq("Content-Type"), eq("application/json"))
.responseObject(UserInfoDeserializer)
} returns ResponseResultOf(first = fuelRequest, second = fuelResponse, third = Result.success(false))
}
#Test
fun `will return FALSE for user not existing in jira`() {
// given
val usernames = listOf("user_1#test.com", "user_3#test.com", "user_4#test.com")
// when
JiraService().checkIfUsersExistInJira(usernames, jiraConfig)
// then
}
}
And I always see the error:
Caused by: some.url.net
com.github.kittinunf.fuel.core.FuelError$Companion.wrap(FuelError.kt:86)
com.github.kittinunf.fuel.toolbox.HttpClient.executeRequest(HttpClient.kt:39)
Caused by: java.net.UnknownHostException: some.url.net
...
So it always makes a real Fuel call ignoring fueMock.
What am I doing wrong?
Thanks for help!

If somebody need, following test works:
#ExtendWith(MockKExtension::class)
class JiraServiceTest {
private val jiraConfig = createJiraConf()
private val fuelRequest1 = mockk<DefaultRequest>()
private val fuelRequest3 = mockk<DefaultRequest>()
private val fuelRequest4 = mockk<DefaultRequest>()
private val fuelResponse = mockk<Response>()
#BeforeEach
fun setUp() {
mockkObject(Fuel)
every {
Fuel.get(eq("${jiraConfig[url]}/rest/api/2/groupuserpicker?query=user_1#test.com&maxResults=1"))
} returns fuelRequest1
every {
Fuel.get(eq("${jiraConfig[url]}/rest/api/2/groupuserpicker?query=user_3#test.com&maxResults=1"))
} returns fuelRequest3
every {
Fuel.get(eq("${jiraConfig[url]}/rest/api/2/groupuserpicker?query=user_4#test.com&maxResults=1"))
} returns fuelRequest4
every { fuelRequest1.appendHeader(any<String>(), any()) } returns fuelRequest1
every { fuelRequest3.appendHeader(any<String>(), any()) } returns fuelRequest3
every { fuelRequest4.appendHeader(any<String>(), any()) } returns fuelRequest4
every { fuelRequest1.responseObject(UserInfoDeserializer) } returns ResponseResultOf(
first = fuelRequest1,
second = fuelResponse,
third = Result.success(false)
)
every { fuelRequest3.responseObject(UserInfoDeserializer) } returns ResponseResultOf(
first = fuelRequest3,
second = fuelResponse,
third = Result.success(true)
)
every { fuelRequest4.responseObject(UserInfoDeserializer) } returns ResponseResultOf(
first = fuelRequest4,
second = fuelResponse,
third = Result.success(true)
)
}
#Test
fun `will return FALSE for user not existing in jira`() {
// given
val usernames = listOf("user_1#test.com", "user_3#test.com", "user_4#test.com")
// when
val result = JiraService().checkIfUsersExistInJira(usernames, jiraConfig)
// then
assertThat(result, equalTo(false))
}
#Test
fun `will return TRUE for users existing in jira`() {
// given
val usernames = listOf("user_3#test.com", "user_4#test.com")
// when
val result = JiraService().checkIfUsersExistInJira(usernames, jiraConfig)
// then
assertThat(result, equalTo(true))
}
}

Related

Why my return value is coming as NaN or default in kotlin?

For a while, I want to convert the entered currencies to each other and show them on the other screen, but when I check the view model with println, the result I can see is NaN when I make viewmodel.result in the ui. What is the reason for this and how can I solve it?
my ui
If the user presses oncofirm on the button, the operations in the view model are performed.
if (viewModel.isDialogShown) {
AlertDialog(
onDismiss = {
viewModel.onDismissClick()
},
onConfirm = {
viewModel.getConversionRateByCurrency()
viewModel.onDismissClick()
//viewModel.calculate()
println(viewModel.resultState)
With println(viewModel.resultState) comes 0.0
but when I press the button for the second time and say confirm, then the correct result comes.
my view model
#HiltViewModel
class ExchangeMainViewModel #Inject constructor(
private val exchangeInsertUseCase: InsertExchangeUseCase,
private val exchangeGetAllUseCase: GetAllExchangeUseCase,
private val getConversionRateByCurrencyUseCase: GetConversionRateByCurrencyUseCase
) : ViewModel() {
var isDialogShown by mutableStateOf(false)
private set
var dropDownMenuItem1 by mutableStateOf("")
var dropDownMenuItem2 by mutableStateOf("")
var outLineTxtFieldValue by mutableStateOf(TextFieldValue(""))
var firstConversionRate by mutableStateOf(0.0)
var secondConversionRate by mutableStateOf(0.0)
var resultState by mutableStateOf(0.0)
fun onConfirmClick() {
isDialogShown = true
}
fun onDismissClick() {
isDialogShown = false
}
fun check(context: Context): Boolean {
if (outLineTxtFieldValue.text.isNullOrEmpty() || dropDownMenuItem1 == "" || dropDownMenuItem2 == "") {
Toast.makeText(context, "please select a value and currency ", Toast.LENGTH_LONG).show()
return false
}
return true
}
fun getConversionRateByCurrency() {
viewModelScope.launch {
val firstRate = async {
getConversionRateByCurrencyUseCase.getConversionRateByCurrency(dropDownMenuItem1)
}
val secondRate = async {
getConversionRateByCurrencyUseCase.getConversionRateByCurrency(dropDownMenuItem2)
}
firstConversionRate = firstRate.await()
secondConversionRate = secondRate.await()
delay(200L)
val result = async {
calculate()
}
resultState = result.await()
}
}
private fun calculate(): Double {
if (!firstConversionRate.equals(0.0) && !secondConversionRate.equals(0.0)) {
val amount = outLineTxtFieldValue.text.toInt()
val resultOfCalculate = (amount / firstConversionRate) * secondConversionRate
return resultOfCalculate
}
return 1.1
}
}
I can see the value in the view model but not the ui. Also, I do a lot of checking with if and 0.0 because I couldn't get out of it, so I followed a method like this because I couldn't solve the problem. Anyone have a better idea?

Remote Mediator loads only the first page

I'm trying to add offline capabilities to my TMDB app. I've tried doing it with Room but RemoteMediator only loads the first page.
This is how I implemented the RemoteMediator class
#OptIn(ExperimentalPagingApi::class)
class MoviesPopularMediator(
private val service: ApiService,
private val database: PopularMoviesDatabase
) : RemoteMediator<Int, MoviesModel>() {
override suspend fun load(
loadType: LoadType,
state: PagingState<Int, MoviesModel>
): MediatorResult {
return try {
val loadKey = when(loadType){
LoadType.REFRESH -> {
1
}
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND ->{
state.lastItemOrNull()
?: return MediatorResult.Success(endOfPaginationReached = true)
getMoviesPage()
}
}
val response = service.getPopular(
page = state.config.pageSize,
)
val listing = response.body()
val results = listing?.results
if (listing != null) {
database.withTransaction {
if (loadKey != null) {
database.popularMoviesPageDao().savePopularMoviesPage(MoviesPage(page = listing.page, results = listing.results, total_pages = listing.total_pages))
}
if (results != null) {
database.popularMoviesDao().savePopularMovies(results)
}
}
}
MediatorResult.Success(endOfPaginationReached = response.body()?.page == response.body()?.total_pages)
} catch (exception: IOException) {
MediatorResult.Error(exception)
} catch (exception: HttpException) {
MediatorResult.Error(exception)
}
}
private suspend fun getMoviesPage(): MoviesPage? {
return database.popularMoviesPageDao().getPopularMoviesPage().firstOrNull()
}
}
I get the data from this api: https://api.themoviedb.org/3/.
Any ideas on how I should change this RemoteMediator so that it will load all pages?
If you need more details please feel free to ask

While loop doesn't seem to work with .putFile when uploading multiple images to Firebase storage in Kotlin

I have been trying to upload multiple images to Firebase Storage. But, I am not able to do it successfully. I could successfully upload the image (single) to the storage and add the URL of the image to the Firestore, now that I revised my code to upload up to five images, it could be any number of images from 1 to 5.
R.id.btn_submit -> {
if (validateDetails()) {
uploadImage()
}
}
The above code, calls the following function after validating the fields, which then calls the function uploadImageToCloudStorage. mSelectedImageFileUriList is private var mSelectedImageFileUriList: MutableList<Uri?>? = null. It all seems to work correctly.
private fun uploadImage() {
showProgressDialog(resources.getString(R.string.please_wait))
FirestoreClass().uploadImageToCloudStorage(
this#AddProductActivity,
mSelectedImageFileUriList,
Constants.PRODUCT_IMAGE,
Constants.PRODUCT_IMAGE_DIRECTORY_NAME,
et_product_title.text.toString().trim { it <= ' ' }
)
}
Following code is where I guess is a mistake.
fun uploadImageToCloudStorage(
activity: AddProductActivity,
imageFileURI: MutableList<Uri?>?,
imageType: String,
directoryName: String,
title: String
) {
var i = 0
val imageURLList = ArrayList<String>()
val itr = imageFileURI?.iterator()
if (itr != null) {
while (itr.hasNext()) {
val sRef: StorageReference = FirebaseStorage.getInstance().getReference(
"/$directoryName/" + imageType + "." + Constants.getFileExtension(
activity,
imageFileURI[i]
)
)
sRef.putFile(imageFileURI[i]!!)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.metadata!!.reference!!.downloadUrl
.addOnSuccessListener { uri ->
if (i < imageFileURI.size) {
i += 1
imageURLList.add(uri.toString())
} else {
activity.imageUploadSuccess(imageURLList)
}
}
}
.addOnFailureListener { exception ->
activity.hideProgressDialog()
Log.e(
activity.javaClass.simpleName,
exception.message,
exception
)
}
}
} else {
Toast.makeText(
activity,
"There is no images in the ArrayList of URI",
Toast.LENGTH_SHORT
).show()
}
}
EDIT: After receiving the first answer.
I have created a QueueSyn.kt file and added the code in the Answer. The activity where the images and the button are changed to
class AddProductActivity : BaseActivity(), View.OnClickListener, QueueSyncCallback {
The following function is called when the button is hit.
private fun uploadProductImage() {
showProgressDialog(resources.getString(R.string.please_wait))
QueueSync(
mSelectedImageFileUriList,
Constants.PRODUCT_IMAGE,
Constants.PRODUCT_IMAGE_DIRECTORY_NAME,
et_product_title.text.toString().trim { it <= ' ' },
this
).startUploading()
}
I have also implemented these two methods in the class AddProductActivity, but I don't know what should go inside this.
override fun completed(successList: MutableList<Uri>, failureList: MutableList<Uri>) {
TODO("Not yet implemented")
}
override fun getFileExtension(uri: Uri): String {
TODO("Not yet implemented")
}
Error:
This should work
import android.net.Uri
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import java.util.*
import kotlin.collections.ArrayList
interface QueueSyncCallback {
fun completed(successList: MutableList<Uri>, failureList: MutableList<Uri>)
fun getFileExtension(uri: Uri): String
}
class QueueSync(
imageFileURI: MutableList<Uri?>?,
private val imageType: String,
private val directoryName: String,
private val title: String,
private val callback: QueueSyncCallback,
private val maxActive: Int = 5
) {
private val queue: LinkedList<Uri> = LinkedList()
private val runningQueue: MutableList<Uri> = Collections.synchronizedList(
object : ArrayList<Uri>() {
override fun remove(element: Uri): Boolean {
val removed = super.remove(element)
if (isEmpty() && queue.isEmpty()) {
callback.completed(successList, failureList)
} else if (queue.isNotEmpty()) {
addToRunningQueue()
}
return removed
}
}
)
private val successList: MutableList<Uri> = Collections.synchronizedList(ArrayList())
private val failureList: MutableList<Uri> = Collections.synchronizedList(ArrayList())
init {
if (imageFileURI != null)
for (uri in imageFileURI) {
if (uri != null)
queue.add(uri)
}
}
private fun getLocation(uri: Uri) = "/$directoryName/$imageType.${callback.getFileExtension(uri)}"
fun startUploading() {
var i = 0
if (queue.isEmpty()) {
callback.completed(successList, failureList)
return
}
while (i < maxActive && queue.isNotEmpty()) {
addToRunningQueue()
i++
}
}
private fun addToRunningQueue() {
val uri = queue.poll()!!
runningQueue.add(uri)
uploadImageToCloudStorage(uri)
}
private fun uploadImageToCloudStorage(locationUri: Uri) {
val sRef: StorageReference = FirebaseStorage.getInstance().getReference(getLocation(locationUri))
sRef.putFile(locationUri)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.metadata!!.reference!!.downloadUrl
.addOnSuccessListener { uri ->
successList.add(uri)
runningQueue.remove(locationUri)
}
}
.addOnFailureListener {
failureList.add(locationUri)
runningQueue.remove(locationUri)
}
}
}
Since your need requires usage of threads so to prevent race conditions I had to use Collections.synchronizedList. To use this you need to implement QueueSyncCallback in your activity and pass it as a reference to QueueSync. Make sure that any piece of code written inside completed is wrapped inside runOnMainThread if it is going to access views in any way since completed will not run on main thread as far as I know. This should work however I am not able to test it since it is based on your current code.
Edit:- Answering after edit
override fun completed(successList: MutableList<Uri>, failureList: MutableList<Uri>) {
imageUploadSuccess(successList)
hideProgressDialog()
}
override fun getFileExtension(uri: Uri): String {
Constants.getFileExtension(this, imageFileURI[i])
}

Testing endpoint under auth with Ktor

I'm struggling to write tests for an endpoint that is under auth (token). In particular, when writing my test, I'm not able to chain the login request with my second request, despite providing the token received as part of the login request.
LoginEndpoint.kt
const val LOGIN_ENDPOINT = "$API_VERSION/login"
#Location(LOGIN_ENDPOINT)
class Login
fun Route.loginEndpoint(patientsRepository: Repository<Patient>, authProvider: AuthProvider) {
post<Login> {
val params = call.receive<Parameters>()
val userId = params["id"] ?: return#post call.respond(status = HttpStatusCode.BadRequest, message = "Missing user id")
val user = patientsRepository.get(userId)
if (user != null) {
val token = authProvider.generateToken(user.id!!)
call.respond(TextContent("{ \"token\": \"$token\" }", ContentType.Application.Json))
} else {
call.respond(status = HttpStatusCode.NotFound, message = "User with id $userId does not exist")
}
}
}
LoginEndpointTest.kt (passing, all good)
#Test
fun `given user exists then returns 200 and token`() {
val userId = "paco123"
val token = "magic_token_123"
withTestApplication({
givenTestModule()
}) {
every { authProvider.generateToken(userId) } answers { token }
givenPatientExists(userId)
with(handleRequest(HttpMethod.Post, "/$API_VERSION/login") {
addHeader("content-type", "application/x-www-form-urlencoded")
setBody("id=$userId")
}) {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals("{ \"token\": \"magic_token_123\" }", response.content)
}
}
}
private fun Application.givenTestModule() {
module(
testing = true,
repositoryModule = TestingRepositoryModule,
authProvider = authProvider
)
}
Now, the problematic endpoint.
ProfileEndpoint.kt
const val PATIENTS_API_ENDPOINT = "$API_VERSION/profile"
#Location(PATIENTS_API_ENDPOINT)
class ProfileEndpoint
fun Route.profileEndpoint(patientsRepository: Repository<Patient>) {
authenticate("jwt") {
get<ProfileEndpoint> {
val apiUser: Patient = call.apiUser!!
val id = apiUser.id!!
val patient = patientsRepository.get(id)
when (patient != null) {
false -> call.respond(status = HttpStatusCode.NotFound, message = "Patient with id $id does not exist")
true -> call.respond(status = HttpStatusCode.OK, message = patient.map())
}
}
}
}
Finally, my failing test
ProfileEndpointTest.kt
#Test
fun `given user is logged in then returns 200 and profile`() {
val userId = "paco123"
val token = "magic_token_123"
withTestApplication({
givenTestModule()
}) {
every { authProvider.generateToken(userId) } answers { token }
givenPatientExists(userId)
handleRequest(HttpMethod.Post, "/$API_VERSION/login") {
addHeader("content-type", "application/x-www-form-urlencoded")
setBody("id=$userId")
}
handleRequest(HttpMethod.Get, "/$API_VERSION/profile") {
addHeader("Authorization", "Bearer $token")
}.apply {
assertEquals(HttpStatusCode.OK, response.status())
}
}
}
The error is:
expected:<200 OK> but was:<401 Unauthorized>
Expected :200 OK
Actual :401 Unauthorized
AuthProvider.kt
open class AuthProvider(secret: String = System.getenv(Environment.JWT_SECRET)) {
private val algorithm = Algorithm.HMAC512(secret)
fun getVerifier(): JWTVerifier = JWT
.require(algorithm)
.withIssuer(APP_NAME)
.build()
fun generateToken(userId: String): String = JWT.create()
.withSubject(SUBJECT)
.withIssuer(APP_NAME)
.withClaim(CLAIM, userId)
.withExpiresAt(expiresAt())
.sign(algorithm)
private fun expiresAt() = Date(System.currentTimeMillis() + MILLIES_PER_DAY * TOKEN_DAYS_LENGTH)
}
val ApplicationCall.apiUser get() = authentication.principal<Patient>()
I've tried using cookiesSession like in this documentation's example https://ktor.io/servers/testing.html#preserving-cookies but it didn't work. Any help would be much appreciated.

How to simply add another source to MediatorLiveData in kotlin?

I want to combine multiple data sources in a MediatorLiveData. Unfortunately, there are not many examples yet. So in my ViewModel I have
//all lists have been declared before
val playerList = MediatorLiveData<List<Player>>()
init {
playerList.addSource(footballPlayerList) { value ->
playerList.value = value
}
playerList.addSource(basketballPlayerList) { value ->
playerList.value = value
}
}
But apparently this will always override the current value of playerList. I mean I could build some hacky workarounds with helper variables like _playerList but maybe there is an easier solution?
Having done quite some research.. I found it out. Here is an example
fun blogpostBoilerplateExample(newUser: String): LiveData<UserDataResult> {
val liveData1 = userOnlineDataSource.getOnlineTime(newUser)
val liveData2 = userCheckinsDataSource.getCheckins(newUser)
val result = MediatorLiveData<UserDataResult>()
result.addSource(liveData1) { value ->
result.value = combineLatestData(liveData1, liveData2)
}
result.addSource(liveData2) { value ->
result.value = combineLatestData(liveData1, liveData2)
}
return result
}
The actual combination of data is done in a separate combineLatestData method like so
private fun combineLatestData(
onlineTimeResult: LiveData<Long>,
checkinsResult: LiveData<CheckinsResult>
): UserDataResult {
val onlineTime = onlineTimeResult.value
val checkins = checkinsResult.value
// Don't send a success until we have both results
if (onlineTime == null || checkins == null) {
return UserDataLoading()
}
// TODO: Check for errors and return UserDataError if any.
return UserDataSuccess(timeOnline = onlineTime, checkins = checkins)
}
Here is a simple example
class MergeMultipleLiveData : ViewModel() {
private val fictionMenu: MutableLiveData<Resource<RssMenu>> = MutableLiveData()
private val nonFictionMenu: MutableLiveData<Resource<RssMenu>> = MutableLiveData()
val allCategoryMenus: MediatorLiveData<Resource<RssMenu>> = MediatorLiveData()
init {
getFictionMenus()
getNonFictionMenus()
getAllCategoryMenus()
}
private fun getAllCategoryMenus() = viewModelScope.launch(Dispatchers.IO) {
allCategoryMenus.addSource(fictionMenu) { value ->
allCategoryMenus.value = value
}
allCategoryMenus.addSource(nonFictionMenu) { value ->
allCategoryMenus.value = value
}
}
private fun getFictionMenus() = viewModelScope.launch(Dispatchers.IO) {
fictionMenu.postValue( // todo )
}
private fun getNonFictionMenus() = viewModelScope.launch(Dispatchers.IO) {
nonFictionMenu.postValue( // todo )
}
}
And in your fragment you can observer as;
viewModel.allCategoryMenus.observe(viewLifecycleOwner) {
// todo
}