Skip to content

Commit

Permalink
Fix problems with tests
Browse files Browse the repository at this point in the history
  • Loading branch information
serras committed Nov 8, 2023
1 parent a359b79 commit f137b22
Show file tree
Hide file tree
Showing 14 changed files with 45 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,22 @@ import arrow.retrofit.adapter.mock.ErrorMock
import arrow.retrofit.adapter.mock.ResponseMock
import arrow.retrofit.adapter.retrofit.SuspendApiTestClient
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.test.runTest
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.SocketPolicy
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlinx.coroutines.test.runTest

class ArrowEitherCallAdapterTest {

lateinit var server: MockWebServer
lateinit var service: SuspendApiTestClient

@Test fun beforeAny = runTime {
@BeforeTest fun initialize() {
server = MockWebServer()
server.start()
service = Retrofit.Builder()
Expand All @@ -30,7 +32,9 @@ class ArrowEitherCallAdapterTest {
.create(SuspendApiTestClient::class.java)
}

@Test fun afterAny = runTime { server.shutdown() }
@AfterTest fun shutdown() {
server.shutdown()
}

@Test fun shouldReturnResponseMockFor200WithValidJson() = runTest {
server.enqueue(MockResponse().setBody("""{"response":"Arrow rocks"}"""))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import arrow.retrofit.adapter.mock.ErrorMock
import arrow.retrofit.adapter.mock.ResponseMock
import arrow.retrofit.adapter.retrofit.SuspendApiTestClient
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.test.runTest
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.SocketPolicy
Expand All @@ -14,7 +15,6 @@ import retrofit2.converter.gson.GsonConverterFactory
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlinx.coroutines.test.runTest

class ArrowResponseEAdapterTest {

Expand All @@ -37,7 +37,7 @@ class ArrowResponseEAdapterTest {
fun shutdown() {
server.shutdown()
}

@Test
fun shouldReturnResponseMockFor200WithValidJson() = runTest {
server.enqueue(MockResponse().setBody("""{"response":"Arrow rocks"}"""))
Expand All @@ -61,7 +61,7 @@ class ArrowResponseEAdapterTest {
body shouldBe Unit.right()
}
}

@Test
fun shouldReturnUnitWhenServiceMethodReturnsUnitAndJsonBodyReceived() = runTest {
server.enqueue(MockResponse().setBody("""{"response":"Arrow rocks"}"""))
Expand All @@ -85,7 +85,7 @@ class ArrowResponseEAdapterTest {
body shouldBe ErrorMock(42).left()
}
}

@Test
fun shouldThrowFor200WithInvalidJson() = runTest {
server.enqueue(MockResponse().setBody("""not a valid JSON"""))
Expand All @@ -94,7 +94,7 @@ class ArrowResponseEAdapterTest {

responseE.isFailure shouldBe true
}

@Test
fun shouldThrowFor400AndInvalidJson() = runTest {
server.enqueue(MockResponse().setBody("""not a valid JSON""").setResponseCode(400))
Expand All @@ -103,7 +103,7 @@ class ArrowResponseEAdapterTest {

responseE.isFailure shouldBe true
}

@Test
fun shouldThrowWhenServerDisconnects() = runTest {
server.enqueue(MockResponse().apply { socketPolicy = SocketPolicy.DISCONNECT_AFTER_REQUEST })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package arrow.core

import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.matchers.shouldBe
import kotlin.test.Test
import kotlinx.coroutines.test.runTest
import kotlin.test.Test

class NonFatalJvmTest {
val fatals: List<Throwable> =
Expand All @@ -21,7 +21,7 @@ class NonFatalJvmTest {
NonFatal(it) shouldBe false
}
}

@Test fun testFatalsUsingThrowableNonFatalOrThrow() = runTest {
fatals.forEach {
shouldThrowAny {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class CyclicBarrierSpec {

@Test
fun awaitingAllInParallelResumesAllCoroutines() = runTest {
checkAll(Arb.int(1, 100)) { i ->
checkAll(Arb.int(1, 20)) { i ->
val barrier = CyclicBarrier(i)
(0 until i).parMap { barrier.await() }
}
Expand Down Expand Up @@ -85,7 +85,7 @@ class CyclicBarrierSpec {

@Test
fun resetCancelsAllAwaiting() = runTest {
checkAll(Arb.int(2, 100)) { i ->
checkAll(Arb.int(2, 20)) { i ->
val barrier = CyclicBarrier(i)
val exitCase = CompletableDeferred<ExitCase>()

Expand All @@ -103,7 +103,7 @@ class CyclicBarrierSpec {

@Test
fun shouldCleanUpUponReset() = runTest {
checkAll(Arb.int(2, 100)) { i ->
checkAll(Arb.int(2, 20)) { i ->
val barrier = CyclicBarrier(i)
val exitCase = CompletableDeferred<ExitCase>()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ class FlowTest {

@Test
fun fixedDelay() = runTest {
checkAll(Arb.positiveInt().map(Int::toLong), Arb.int(1..100)) { waitPeriod, n ->
checkAll(Arb.positiveInt().map(Int::toLong), Arb.int(1..20)) { waitPeriod, n ->
val emissionDuration = waitPeriod / 10L
var state: Long? = null

Expand All @@ -261,7 +261,7 @@ class FlowTest {

@Test
fun fixedRate() = runTest {
checkAll(Arb.positiveInt().map(Int::toLong), Arb.int(1..100)) { waitPeriod, n ->
checkAll(Arb.positiveInt().map(Int::toLong), Arb.int(1..20)) { waitPeriod, n ->
val emissionDuration = waitPeriod / 10
var state: Long? = null

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ import kotlin.coroutines.intrinsics.intercepted
import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn
import kotlin.coroutines.startCoroutine

fun <A> Arb.Companion.flow(arbA: Arb<A>): Arb<Flow<A>> =
fun <A> Arb.Companion.flow(arbA: Arb<A>, range: IntRange = 1 .. 20): Arb<Flow<A>> =
Arb.choose(
10 to Arb.list(arbA).map { it.asFlow() },
10 to Arb.list(arbA).map { channelFlow { it.forEach { send(it) } }.buffer(Channel.RENDEZVOUS) },
10 to Arb.list(arbA, range).map { it.asFlow() },
10 to Arb.list(arbA, range).map { channelFlow { it.forEach { send(it) } }.buffer(Channel.RENDEZVOUS) },
1 to Arb.constant(emptyFlow()),
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package arrow.optics

import io.kotest.matchers.shouldBe
import io.kotest.property.Arb
import io.kotest.property.arbitrary.Codepoint
import io.kotest.property.arbitrary.ascii
import io.kotest.property.arbitrary.list
import io.kotest.property.arbitrary.string
import io.kotest.property.checkAll
Expand All @@ -11,30 +13,32 @@ import kotlin.test.Test
data class Person(val name: String, val friends: List<String>)

sealed interface Cutlery
object Fork : Cutlery
object Spoon : Cutlery
data object Fork : Cutlery
data object Spoon : Cutlery

class ReflectionTest {
private val asciiString: Arb<String> = Arb.string(codepoints = Codepoint.ascii())

@Test fun lensesForFieldGet() = runTest {
checkAll(Arb.string(), Arb.list(Arb.string())) { nm, fs ->
checkAll(asciiString, Arb.list(asciiString, 1..20)) { nm, fs ->
val p = Person(nm, fs.toMutableList())
Person::name.lens.get(p) shouldBe nm
}
}

@Test fun lensesForFieldSet() = runTest {
checkAll(Arb.string(), Arb.list(Arb.string())) { nm, fs ->
checkAll(asciiString, Arb.list(asciiString, 1..20)) { nm, fs ->
val p = Person(nm, fs.toMutableList())
val m = Person::name.lens.modify(p) { it.capitalize() }
m shouldBe Person(nm.capitalize(), fs)
val m = Person::name.lens.modify(p) { it.lowercase() }
m shouldBe Person(nm.lowercase(), fs)
}
}

@Test fun traversalForListSet() = runTest {
checkAll(Arb.string(), Arb.list(Arb.string())) { nm, fs ->
checkAll(asciiString, Arb.list(asciiString, 1..20)) { nm, fs ->
val p = Person(nm, fs)
val m = Person::friends.every.modify(p) { it.capitalize() }
m shouldBe Person(nm, fs.map { it.capitalize() })
val m = Person::friends.every.modify(p) { it.lowercase() }
m shouldBe Person(nm, fs.map { it.lowercase() })
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
@file:OptIn(ExperimentalTime::class)

package arrow.resilience

import arrow.atomic.Atomic
Expand All @@ -14,7 +12,6 @@ import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import kotlin.time.Duration
import kotlin.time.Duration.Companion.nanoseconds
import kotlin.time.ExperimentalTime
import kotlin.time.TimeMark
import kotlin.time.TimeSource

Expand Down Expand Up @@ -50,9 +47,7 @@ import kotlin.time.TimeSource
* import arrow.resilience.CircuitBreaker
* import kotlinx.coroutines.delay
* import kotlin.time.Duration.Companion.seconds
* import kotlin.time.ExperimentalTime
*
* @ExperimentalTime
* suspend fun main(): Unit {
* //sampleStart
* val circuitBreaker = CircuitBreaker(
Expand Down Expand Up @@ -92,9 +87,7 @@ import kotlin.time.TimeSource
* import arrow.resilience.retry
* import kotlinx.coroutines.delay
* import kotlin.time.Duration.Companion.seconds
* import kotlin.time.ExperimentalTime
*
* @ExperimentalTime
* suspend fun main(): Unit {
* suspend fun apiCall(): Unit {
* println("apiCall . . .")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import arrow.resilience.CircuitBreaker.OpeningStrategy
import arrow.resilience.CircuitBreaker.OpeningStrategy.SlidingWindow
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.runTest
Expand All @@ -20,20 +19,18 @@ import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime
import kotlin.time.TestTimeSource

@OptIn(ExperimentalTime::class, ExperimentalCoroutinesApi::class)
class CircuitBreakerTest {
val dummy = RuntimeException("dummy")
val maxFailures = 5
val exponentialBackoffFactor = 2.0
val resetTimeout = 500.milliseconds
val maxTimeout = 1000.milliseconds
private val dummy = RuntimeException("dummy")
private val maxFailures = 5
private val exponentialBackoffFactor = 2.0
private val resetTimeout = 500.milliseconds
private val maxTimeout = 1000.milliseconds

@Test
fun shouldWorkForSuccessfulAsyncTasks(): TestResult = runTest {
val cb = CircuitBreaker(resetTimeout = resetTimeout, openingStrategy = OpeningStrategy.Count(maxFailures),)
val cb = CircuitBreaker(resetTimeout = resetTimeout, openingStrategy = OpeningStrategy.Count(maxFailures))
var effect = 0
val iterations = stackSafeIteration()
Schedule.recurs<Unit>(iterations.toLong()).repeat {
Expand All @@ -44,7 +41,7 @@ class CircuitBreakerTest {

@Test
fun shouldWorkForSuccessfulImmediateTasks(): TestResult = runTest {
val cb = CircuitBreaker(resetTimeout = resetTimeout, openingStrategy = OpeningStrategy.Count(maxFailures),)
val cb = CircuitBreaker(resetTimeout = resetTimeout, openingStrategy = OpeningStrategy.Count(maxFailures))
var effect = 0
val iterations = stackSafeIteration()
Schedule.recurs<Unit>(iterations.toLong()).repeat {
Expand All @@ -55,7 +52,7 @@ class CircuitBreakerTest {

@Test
fun staysClosedAfterLessThanMaxFailures(): TestResult = runTest {
val cb = CircuitBreaker(resetTimeout = resetTimeout, openingStrategy = OpeningStrategy.Count(maxFailures),)
val cb = CircuitBreaker(resetTimeout = resetTimeout, openingStrategy = OpeningStrategy.Count(maxFailures))

val result = recurAndCollect<Either<Throwable, Unit>>(4).repeat {
Either.catch { cb.protectOrThrow { throw dummy } }
Expand All @@ -67,7 +64,7 @@ class CircuitBreakerTest {

@Test
fun closedCircuitBreakerResetsFailureCountAfterSuccess(): TestResult = runTest {
val cb = CircuitBreaker(resetTimeout = resetTimeout, openingStrategy = OpeningStrategy.Count(maxFailures),)
val cb = CircuitBreaker(resetTimeout = resetTimeout, openingStrategy = OpeningStrategy.Count(maxFailures))

val result = recurAndCollect<Either<Throwable, Unit>>(4).repeat {
Either.catch { cb.protectOrThrow { throw dummy } }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,8 @@ import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import kotlin.test.fail
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.ExperimentalTime

@OptIn(ExperimentalCoroutinesApi::class)
@ExperimentalTime
class FlowTest {

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.fail

@OptIn(ExperimentalCoroutinesApi::class)
@Suppress("unused")
class SagaSpec {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import arrow.atomic.updateAndGet
import arrow.core.Either
import arrow.resilience.Schedule.Decision.Continue
import arrow.resilience.Schedule.Decision.Done
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withTimeout
Expand All @@ -19,17 +18,13 @@ import kotlin.time.Duration
import kotlin.time.Duration.Companion.ZERO
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime

internal data class SideEffect(var counter: Int = 0) {
fun increment() {
counter++
}
}

@OptIn(ExperimentalCoroutinesApi::class)
@ExperimentalTime
@Suppress("UNREACHABLE_CODE", "UNUSED_VARIABLE")
class ScheduleTest {
class MyException : Exception()

Expand Down Expand Up @@ -287,19 +282,16 @@ fun <A, B> Schedule.Decision<A, B>.delay(): Duration? = when (this) {
is Done -> null
}

@ExperimentalTime
private fun fibs(one: Duration): Sequence<Duration> =
generateSequence(Pair(one, one)) { (a, b) ->
Pair(b, (a + b))
}.map { it.first }

@ExperimentalTime
private fun exp(base: Duration): Sequence<Duration> =
generateSequence(Pair(base, 1.0)) { (_, n) ->
Pair(base * 2.0.pow(n), n + 1)
}.map { it.first }

@ExperimentalTime
private fun linear(base: Duration): Sequence<Duration> =
generateSequence(Pair(base, 1.0)) { (_, n) ->
Pair((base * n), (n + 1))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import arrow.core.Either
import arrow.resilience.CircuitBreaker
import kotlinx.coroutines.delay
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime

@ExperimentalTime
suspend fun main(): Unit {
val circuitBreaker = CircuitBreaker(
resetTimeout = 2.seconds,
Expand Down
Loading

0 comments on commit f137b22

Please sign in to comment.