[BAEL-19886] - moved kotlin library articles to the kotlin-libraries-2 module

This commit is contained in:
catalin-burcea
2020-01-03 20:04:23 +02:00
parent e147cc73a6
commit 72db85b917
25 changed files with 61 additions and 443 deletions

View File

@@ -0,0 +1,276 @@
package com.baeldung.fuel
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.interceptors.cUrlLoggingRequestInterceptor
import com.github.kittinunf.fuel.gson.responseObject
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.rx.rx_object
import com.google.gson.Gson
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.io.File
import java.util.concurrent.CountDownLatch
internal class FuelHttpUnitTest {
@Test
fun whenMakingAsyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val latch = CountDownLatch(1)
"http://httpbin.org/get".httpGet().response{
request, response, result ->
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = "http://httpbin.org/get".httpGet().response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakingSyncHttpGetURLEncodedRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) =
"https://jsonplaceholder.typicode.com/posts"
.httpGet(listOf("id" to "1")).response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakingAsyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val latch = CountDownLatch(1)
Fuel.post("http://httpbin.org/post").response{
request, response, result ->
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakingSyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = Fuel.post("http://httpbin.org/post").response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakingSyncHttpPostRequestwithBody_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts")
.body("{ \"title\" : \"foo\",\"body\" : \"bar\",\"id\" : \"1\"}")
.response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(201,response.statusCode)
}
@Test
fun givenFuelInstance_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
FuelManager.instance.basePath = "http://httpbin.org"
FuelManager.instance.baseHeaders = mapOf("OS" to "macOS High Sierra")
FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor())
FuelManager.instance.addRequestInterceptor(tokenInterceptor())
val (request, response, result) = "/get"
.httpGet().response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun givenInterceptors_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
FuelManager.instance.basePath = "http://httpbin.org"
FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor())
FuelManager.instance.addRequestInterceptor(tokenInterceptor())
val (request, response, result) = "/get"
.httpGet().response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenDownloadFile_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() {
Fuel.download("http://httpbin.org/bytes/32768").destination { response, url ->
File.createTempFile("temp", ".tmp")
}.response{
request, response, result ->
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
}
@Test
fun whenDownloadFilewithProgressHandler_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = Fuel.download("http://httpbin.org/bytes/327680")
.destination { response, url -> File.createTempFile("temp", ".tmp")
}.progress { readBytes, totalBytes ->
val progress = readBytes.toFloat() / totalBytes.toFloat()
}.response ()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakeGetRequest_thenDeserializePostwithGson() {
val latch = CountDownLatch(1)
"https://jsonplaceholder.typicode.com/posts/1".httpGet().responseObject<Post> { _,_, result ->
val post = result.component1()
Assertions.assertEquals(1, post?.userId)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakePOSTRequest_thenSerializePostwithGson() {
val post = Post(1,1, "Lorem", "Lorem Ipse dolor sit amet")
val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts")
.header("Content-Type" to "application/json")
.body(Gson().toJson(post).toString())
.response()
Assertions.assertEquals(201,response.statusCode)
}
@Test
fun whenMakeGETRequestWithRxJava_thenDeserializePostwithGson() {
val latch = CountDownLatch(1)
"https://jsonplaceholder.typicode.com/posts?id=1"
.httpGet().rx_object(Post.Deserializer()).subscribe{
res, throwable ->
val post = res.component1()
Assertions.assertEquals(1, post?.get(0)?.userId)
latch.countDown()
}
latch.await()
}
// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library
// @Test
// fun whenMakeGETRequestUsingCoroutines_thenResponseStatusCode200() = runBlocking {
// val (request, response, result) = Fuel.get("http://httpbin.org/get").awaitStringResponse()
//
// result.fold({ data ->
// Assertions.assertEquals(200, response.statusCode)
//
// }, { error -> })
// }
// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library
// @Test
// fun whenMakeGETRequestUsingCoroutines_thenDeserializeResponse() = runBlocking {
// Fuel.get("https://jsonplaceholder.typicode.com/posts?id=1").awaitObjectResult(Post.Deserializer())
// .fold({ data ->
// Assertions.assertEquals(1, data.get(0).userId)
// }, { error -> })
// }
@Test
fun whenMakeGETPostRequestUsingRoutingAPI_thenDeserializeResponse() {
val latch = CountDownLatch(1)
Fuel.request(PostRoutingAPI.posts("1",null))
.responseObject(Post.Deserializer()) {
request, response, result ->
Assertions.assertEquals(1, result.component1()?.get(0)?.userId)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakeGETCommentRequestUsingRoutingAPI_thenResponseStausCode200() {
val latch = CountDownLatch(1)
Fuel.request(PostRoutingAPI.comments("1",null))
.responseString { request, response, result ->
Assertions.assertEquals(200, response.statusCode)
latch.countDown()
}
latch.await()
}
}

View File

@@ -0,0 +1,192 @@
package com.baeldung.kovenant
import nl.komponents.kovenant.*
import nl.komponents.kovenant.Kovenant.deferred
import nl.komponents.kovenant.combine.and
import nl.komponents.kovenant.combine.combine
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit
class KovenantTest {
@Before
fun setupTestMode() {
Kovenant.testMode { error ->
println("An unexpected error occurred")
Assert.fail(error.message)
}
}
@Test
fun testSuccessfulDeferred() {
val def = deferred<Long, Exception>()
Assert.assertFalse(def.promise.isDone())
def.resolve(1L)
Assert.assertTrue(def.promise.isDone())
Assert.assertTrue(def.promise.isSuccess())
Assert.assertFalse(def.promise.isFailure())
}
@Test
fun testFailedDeferred() {
val def = deferred<Long, Exception>()
Assert.assertFalse(def.promise.isDone())
def.reject(RuntimeException())
Assert.assertTrue(def.promise.isDone())
Assert.assertFalse(def.promise.isSuccess())
Assert.assertTrue(def.promise.isFailure())
}
@Test
fun testResolveDeferredTwice() {
val def = deferred<Long, Exception>()
def.resolve(1L)
try {
def.resolve(1L)
} catch (e: AssertionError) {
// Expected.
// This is slightly unusual. The AssertionError comes from Assert.fail() from setupTestMode()
}
}
@Test
fun testSuccessfulTask() {
val promise = task { 1L }
Assert.assertTrue(promise.isDone())
Assert.assertTrue(promise.isSuccess())
Assert.assertFalse(promise.isFailure())
}
@Test
fun testFailedTask() {
val promise = task { throw RuntimeException() }
Assert.assertTrue(promise.isDone())
Assert.assertFalse(promise.isSuccess())
Assert.assertTrue(promise.isFailure())
}
@Test
fun testCallbacks() {
val promise = task { 1L }
promise.success {
println("This was a success")
Assert.assertEquals(1L, it)
}
promise.fail {
println(it)
Assert.fail("This shouldn't happen")
}
promise.always {
println("This always happens")
}
}
@Test
fun testGetValues() {
val promise = task { 1L }
Assert.assertEquals(1L, promise.get())
}
@Test
fun testAllSucceed() {
val numbers = all(
task { 1L },
task { 2L },
task { 3L }
)
Assert.assertEquals(listOf(1L, 2L, 3L), numbers.get())
}
@Test
fun testOneFails() {
val runtimeException = RuntimeException()
val numbers = all(
task { 1L },
task { 2L },
task { throw runtimeException }
)
Assert.assertEquals(runtimeException, numbers.getError())
}
@Test
fun testAnySucceeds() {
val promise = any(
task {
TimeUnit.SECONDS.sleep(3)
1L
},
task {
TimeUnit.SECONDS.sleep(2)
2L
},
task {
TimeUnit.SECONDS.sleep(1)
3L
}
)
Assert.assertTrue(promise.isDone())
Assert.assertTrue(promise.isSuccess())
Assert.assertFalse(promise.isFailure())
}
@Test
fun testAllFails() {
val runtimeException = RuntimeException()
val ioException = IOException()
val illegalStateException = IllegalStateException()
val promise = any(
task {
TimeUnit.SECONDS.sleep(3)
throw runtimeException
},
task {
TimeUnit.SECONDS.sleep(2)
throw ioException
},
task {
TimeUnit.SECONDS.sleep(1)
throw illegalStateException
}
)
Assert.assertTrue(promise.isDone())
Assert.assertFalse(promise.isSuccess())
Assert.assertTrue(promise.isFailure())
}
@Test
fun testSimpleCombine() {
val promise = task { 1L } and task { "Hello" }
val result = promise.get()
Assert.assertEquals(1L, result.first)
Assert.assertEquals("Hello", result.second)
}
@Test
fun testLongerCombine() {
val promise = combine(
task { 1L },
task { "Hello" },
task { Currency.getInstance("USD") }
)
val result = promise.get()
Assert.assertEquals(1L, result.first)
Assert.assertEquals("Hello", result.second)
Assert.assertEquals(Currency.getInstance("USD"), result.third)
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.kovenant
import nl.komponents.kovenant.Promise
import nl.komponents.kovenant.any
import nl.komponents.kovenant.task
import org.junit.Assert
import org.junit.Ignore
import org.junit.Test
@Ignore
// Note that this can not run in the same test run if KovenantTest has already been executed
class KovenantTimeoutTest {
@Test
fun testTimeout() {
val promise = timedTask(1000) { "Hello" }
val result = promise.get()
Assert.assertEquals("Hello", result)
}
@Test
fun testTimeoutExpired() {
val promise = timedTask(1000) {
Thread.sleep(3000)
"Hello"
}
val result = promise.get()
Assert.assertNull(result)
}
fun <T> timedTask(millis: Long, body: () -> T) : Promise<T?, List<Exception>> {
val timeoutTask = task {
Thread.sleep(millis)
null
}
val activeTask = task(body = body)
return any(activeTask, timeoutTask)
}
}